- Home /
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!!!!
Answer by coastwise · Dec 05, 2012 at 03:10 AM
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);
Your answer
Follow this Question
Related Questions
Facing the target 0 Answers
Instantiated Bullet Force not being applied 0 Answers
Random instantiate at same frame with each instantiate having unique random direction 1 Answer
I need to instantiate a empty gameObject 2 Units right/left of a 'Enemies' Transform? 3 Answers
Instantiate prefab from original position to click mouse point position 0 Answers