- Home /
Trying to get enemy to aim at the player and shoot at it
Here's my code (I use Javascript):
#pragma strict
//Find Player
var Target : Transform;
//Projectile itself
var projectile: Rigidbody2D;
var seconds : float = 5;
var projectileSpeed : float = 5;
var fire : boolean;
function fireAtPlayer(){
while(true){
fire = true;
yield WaitForSeconds(seconds);
fire = false;
yield WaitForSeconds(seconds);
}
}
function shoot(){
if(fire){
var clone = Instantiate(projectile, transform.position, transform.rotation);
clone.velocity = rigidbody2D.AddForce(transform.forward * projectileSpeed);
}
}
function Start () {
fireAtPlayer();
}
function Update () {
transform.LookAt(Target);
shoot();
}
I get this error: Line 22 :Cannot convert void to UnityEngine.Vector2
I'm kinda new to programming so
Answer by frogsbo · Feb 02, 2014 at 10:09 AM
void means he doesnt recognise the function as a vector2 type
take off pragma strict.
use transform lookat.
read turret tutorials.
google turret tutorial tornado.
I already used Transform.LookAt in the update function I need the Enemy to shoot at where it's looking at so
Answer by markmmiller · Feb 02, 2014 at 11:05 AM
The error is because the function rigidbody2D.AddForce(); doesn't return a value but you are trying to use it to set the velocity of the clone.
Instead if you want to add the velocity to the clone object you could do this.
clone.rigidbody2D.AddForce(etc);
Presuming it has a rigidbody attached.
The AddForce function automatically alters the velocity of the rigidbody so you don't have to do the assignment.
function shoot(){
if(fire){
var clone = Instantiate(projectile, transform.position, transform.rotation);
clone.rigidbody2D.AddForce(transform.forward * projectileSpeed);
}
}
I got this code, and it somewhat works, everytime fire is true, it will spawn the projectile. Only problem is it's not targeting the player and it spams the projectile in every frame if fire = true
That's because shoot is being called every frame, you should set fire to false straight after it's fire.
if(fire)
{
//Spawn your bullet
fire = false;
}
You will have to calculate the direction to the player from the enemy, just now it seems to be from either the players face or the AIs facing direction rather than the vector between them.
you might need to do something like (players.position - ai.position).