- Home /
Player Attack Script. I Need Help!
I have created a player attack script in C#:
public class PlayerAttack : MonoBehaviour {
public GameObject target;
public float attackTimer;
public float coolDown;
// Use this for initialization
void Start () {
attackTimer = 0;
coolDown = 2;
}
// Update is called once per frame
void Update () {
if (attackTimer > 0)
attackTimer -= Time.deltaTime;
if (attackTimer < 0)
attackTimer = 0;
if (Input.GetKeyUp (KeyCode.Mouse0)) {
if (attackTimer == 0){
Attack();
attackTimer = coolDown;
}
}
}
private void Attack(){
float distance = Vector3.Distance (target.transform.position, transform.position);
Vector3 dir = (target.transform.position - transform.position).normalized;
float direction = Vector3.Dot (dir, transform.forward);
Debug.Log (direction);
if (distance < 2.5f) {
if(direction > 0){
EnemyHealth eh = (EnemyHealth)target.GetComponent ("EnemyHealth");
eh.AdjustCurrentHealth (-10);
}
}
}
}
I'm not very good at coding, I'm a newbie, so can anyone help me convert this script to use Raycasting. I want the script to check if the collider that the raycast hit is tagged "Enemy", check if the distance to the enemy is less than 2.5, and if the attackTimer is at 0. Then after all of the conditions are met, attack by taking away the enemy's 10 health points, and starting the cooldown again.
Comment
If you use a raycast, you can only attack an enemy directly in front of you. You can use an overlapsphere and detect if the enemy is within a certain angle from the player