logic question! looking & firing at a target

hello – im super new to unity and ive been hammering away trying figure out the basics

i have a little 2d shooter-majigger a la galaga, etc. i have a fixed turret at the top of the screen that i want to follow and shoot at the player. i have a spawn point for instantiated bullets in front of the turret, which itself properly tracks the player. this game is physics based.

what i cant seem to figure out is how to have the bullets shoot directed toward the player – this is my code


    tempBullet = Instantiate(prefabBullet, 
    				transform.position, 
    				transform.rotation);
    tempBullet.rigidbody.AddForce(Vector3.up * force);

obviously this will always shoot the bullet up, irrespective of the ‘swinging spawn point’. what math/function would i use to make it shoot at the player?

thanks!!!

Well, assuming you have the player’s position in a Vector3 called playerPosition you could do the following:

Vector3 dirToShoot = transform.position - playerPosition;
tempBullet.rigidbody.AddForce(dirToShoot.normalized * force); 
// if you don't normalize, the farther away the bullet the faster it will go. (bug, or feature? you decide!)

Or, you say the turret is correctly tracking the player? Why not instantiate the bullet using the turret’s rotation, then you can simply use AddRelativeForce

tempBullet.rigidbody.AddRelativeForce(Vector3.forward * force);