Shooting at player

Hello! I wanted to make basic visual effect of incoming bullets (of course slower than bullets from machine gun in real world :slight_smile: ) coming from bad cubes to player.

Here is my “try code” - moving and shooting part:

public float minDistance = 3;
public float maxDistance = 15;

void Update () {

     float distance = Vector3.Distance(myCharacter.position, player.position);
    
     if (distance <= maxDistance && distance >= minDistance) {

         transform.LookAt (player);  
         myCharacter.rotation = Quaternion.Slerp (myCharacter.rotation, Quaternion.LookRotation  (player.position - myCharacter.position), rotationSpeed * Time.deltaTime);
     transform.Translate (moveSpeed * Vector3.forward * Time.deltaTime);
     }

     if (distance <= 20 && distance >= 7 ) {
              Shoot ();
     }
}


public int count = 1;
public float forceValue = 1200;
public Rigidbody bulletPref;
Transform bulletPos;

void Shoot(){
     int freq = 90;
     if (count % freq == 0) {
            transform.LookAt(player);
            Rigidbody bullet = Instantiate (bulletPref, myCharacter.position, myCharacter.rotation) as Rigidbody;
            bullet.rigidbody.AddForce (myCharacter.forward* forceValue );
     }
     count++;
 }

}

But it is working only sometimes. At other time bullet is going in different direction (180 degrees wrong). What can I do? I must use Raycast?

Thx for any advice or working example.

Any suggestion?

My guess is that myCharacter is not looking at the player and shooting the bullet in its forward direction. Is my character, a sphere or a capsule? change it to a cube or something and see which is its forward direction it shoots in. Since you are using Vector3.distance, it will fire a bullet even when its not facing the player and you are using slerp so it slowly rotates and shoots when its not facing you.

use the dot product to get the angle and if the player is in sight then shoot.

myCharacter is a capsule (1st person view). I will test it tomorrow and write if my problem will be solved or will change. Thx you for a clue :slight_smile: