- Home /
Question by
HarryMoran327 · Oct 12, 2016 at 06:04 AM ·
c#rotationscripting problemtransform
How to rotate a projectile to face the player in 2D?
Hey guys
I'm making a 2d space shooter, and I've run into a problem recently. There's one enemy that fires a projectile at the player position (at the time of firing) which works fine, but I'm trying to rotate the projectile to point towards the player position as well (I'm programming in C# BTW). All the other examples I've tried haven't worked, and I was wondering if you guys could share any advice?
Thanks :-)
Harry
Comment
Answer by Twin-Stick · Oct 12, 2016 at 12:52 PM
Hi There, if it's something like a missile - something like the below code would work (tweak as required of course :) )
Let me know if this helps! Nathan.
// Variables, don't have to be public but handy to modify quickly when testing
public float speed; // Experiment with this to what feels right - 3f;
public gameObject target; // Target the missile is heading towards, ie; player
//---------------------------------------------------------------//
// Set in a function then call during Update() //
//---------------------------------------------------------------//
private void SeekAndDestroy(){
// Vector2 should work just as well if 2D only game
Vector3 lookTarget = target.transform.position - transform.position;
Vector3 Movement = transform.forward * speed;
transform.rotation = Quaternion.Slerp( transform.rotation,
Quaternion.LookRotation(lookTarget),
Time.deltaTime);
transform.position += Movement * Time.deltaTime;
}