- Home /
How to correctly do an enemy ranged attack script?
So i have been working on a game that is top down 2d rpg. i have an enemy who is supposed to detect if the player is within a certain distance and if so to start attacking by throwing a rock. right now his detection sensor is not working correctly and he only will throw one rock at my player. here is my code so far. any help would be great thank you!
public Transform target;
public float attackRange;
public int damage;
//private float lastAttackTime;
private bool attacking;
public float attackTime;
private float attackTimeCounter;
//public float attackDelay;
public GameObject Rock;
public float speed;
public Transform WeaponSpawn;
public Vector3 direction;
//public RigidBody2D Projectile;
Animator anim;
// Use this for initialization
void Start () {
//Rock = GetComponent<Rigidbody2D> ();
anim = GetComponent<Animator> ();
}
// Update is called once per frame
void Update () {
Rock.SetActive (true);
if(attackTimeCounter > 0){
attackTimeCounter -= Time.deltaTime;
}
if(attackTimeCounter <= 0){
attacking = false;
anim.SetBool("Is_Attacking", false);
}
float distanceToPlayer = Vector3.Distance (transform.position, target.position);
if (distanceToPlayer < attackRange) {
Debug.Log ("an object is in range");
GameObject clone;
clone = Instantiate(Rock, WeaponSpawn.position, WeaponSpawn.rotation) as GameObject;
Attack (clone);
Vector3 targetDirection = target.position - transform.position;
//Instantiate(Rock, WeaponSpawn.position, WeaponSpawn.rotation);
//Rock.GetComponent<Rigidbody2D>().velocity = new Vector3 (target.position.x * speed, target.position.y * speed, 0f);
//direction = new Vector3 (target.position.x * speed, target.position.y * speed, 0f);
float angle = Mathf.Atan2 (targetDirection.y, targetDirection.x) * Mathf.Rad2Deg;
Quaternion q = Quaternion.AngleAxis (angle, Vector3.forward);
//transform.rotation = Quaternion.RotateTowards (transform.rotation, q, 90 * Time.deltaTime);
}
if(distanceToPlayer > attackRange){
Debug.Log ("an object is not in range");
anim.SetBool ("Is_Attacking", false);
}
}
void Attack (GameObject Clone){
Instantiate(Rock, WeaponSpawn.position, WeaponSpawn.rotation);
direction = new Vector3 (target.position.x * speed, target.position.y * speed, 0f);
anim.SetBool ("Is_Attacking", true);
}
}
Why do you create a clone in the Update function and never use it, are you sure you want to create a rock every frame the user is in range, ... ? Perhaps you should clean your code, by removing all unused parts (for this problem) and then post it again, this would make it easier to find your problem.
Your answer
Follow this Question
Related Questions
Player attacks once but the enemy takes double damages! 1 Answer
How do I hurt enemies by jumping on them without getting killed? 1 Answer
2D Enemy AI range problem 2 Answers
I need help making my enemy AI have an attack delay 2 Answers
How to perform some code if you are close to an object 2 Answers