- Home /
make Enemy shoot at player
im creating a top-down shooter and i cant find a way to have the enemy shoot at the player...what im trying to do is have the enemy rotate towards the player and then shoot bullets every few seconds...this is the enemy script that i currently have...everything works fine but the firing...any ideas or suggestions pleaseeeee
var lookAtTarget : Transform; var speed : int; var range : int; var damp : float; var ENEMY_HEALTH = 30; var nextFire = 1; private var fireRate = 0.0; var enemyBullet : Transform; var death : Transform ; var health : Transform;
function Awake() { if (!lookAtTarget) { lookAtTarget = GameObject.FindWithTag("Player").transform; } }
function Update() {
if(ENEMY_HEALTH <= 0)
{
Instantiate(death, transform.position, transform.rotation);
Instantiate(health, transform.position, transform.rotation);
Debug.Log("DEAD");
Destroy(gameObject);
}
if(lookAtTarget && CanAttackTarget())
{
//transform.LookAt(lookAtTarget);
var rotate = Quaternion.LookRotation(lookAtTarget.transform.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotate, damp);
transform.Translate (0,0,speed*Time.deltaTime);
if(Time.time >= nextFire)
{
nextFire = Time.time + fireRate;
var bullet = Instantiate(enemyBullet, transform.position, transform.rotation);
bullet.rigidbody.velocity = transform.forward * speed;
}
}
}
function CanAttackTarget() { //check if in range if(Vector3.Distance(transform.position, lookAtTarget.position) > range) { return false; }
return true;
}
function OnParticleCollision () { Debug.Log("hit"); ENEMY_HEALTH--; }
Answer by VS48 · Oct 29, 2010 at 06:16 AM
Your code is almost entirely correct.
if(Time.time >= nextFire)
{
nextFire = Time.time + fireRate;
In your code, 'fireRate' is always going to be 0 (unless you left out some code), so you will be firing on every frame after game time passes 'nextFire' seconds. This is probably a typo -- 'fireRate' should probably be 'nextFire'.
Your movement and rotation code is correct.
Thank you friend'. God bless you'. It's from Brazil here.
Answer by bob 7 · May 09, 2011 at 06:03 PM
can you email me at mashoodsk8@yahoo.co.uk on how to make enemy shoot and die when shot at?
Your answer
![](https://koobas.hobune.stream/wayback/20220613081221im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Problem with enemy shooting 4 Answers
C # script Enemy shoots left 2d platform. 2 Answers
No collision on trigger and character controller 1 Answer
Enemy raycast chase player 0 Answers
Shoot directions 2 Answers