Instantiating with velocity and normalizing, wrong direction

Hello:)

I am trying to make a helicopter shoot at the object with a specific tag that is the nearest. It already selects it and aims towards it, but now I need to shoot a bullet, directly to this object. This is where the problems occur. This is what I have so far.
It’s a timer that will trigger Shoot() every two seconds. And it calculates the distance between the EmptyGameobject that spawns the bullet and the target(called “doel”).

function Update () {
shoot -= Time.deltaTime;
if(shoot <= 0){
	Shoot();
}
if(doel != null){
	distance = Vector3.Distance (transform.position, doel.transform.position);
}

}

function Shoot(){
	if(PlayerPrefs.GetInt("HeliShoot") == 1){
        var bullet : Rigidbody = Instantiate(HeliBullet, transform.position, transform.rotation);
        bullet.velocity = (doel.transform.position).normalized * distance;
		shoot = 2;
	}
}

It shoots the bullet, but in a seemingly random direction. It doesn’t even get near ‘doel’. I think I should change something in the .normalized * distance area, but I can’t figure out what.

Thanks in advance:D

2 Answers

2

Try

bullet.velocity = distance.normalized * bullet_speed;
Where bullet_speed is m/s bullet velocity

First, you can use InvokeRepeating(Shoot, 2 ) for that kind of thing. Or a coroutine.

Now, your problem is during the bullet creation. Unless your helicopter is at (0,0,0), doel.transform.position won’t give your the vector helico → doel, use (doel.transform.position - transform.position) instead.

Also, using the distance as force will give you something strange, the bullet will just fall when it’s close, and go superfast when it’s far. Use a constant instead.

Finally, and it’s optional, you could consider using AddForce instead of velocity.