How to figure out which direction to turn a projectile to face an enemy
I'm making a homing system for the projectiles in my 2D game. The projectiles move in whichever way they are facing. I basically just want to rotate the projectile while it's moving until it's facing the enemy that it's homing onto, which, given that it moves in the direction that it's facing, means it will eventually collide with the enemy. The problem is, I don't know how to determine which way (clockwise or counterclockwise) would be the shortest rotation.
Given this situation: (Projectile left, enemy right), It's easy to see that counterclockwise would be the shorter rotation.
But I'm not quite sure how to calculate that.
These are examples of how the path of the projectile should look (roughly):
I don't want the projectile to move in a straight line to the enemy, but rather smoothly turn towards it as it's moving.
Answer by Glurth · Feb 17, 2016 at 03:25 PM
To answer your question specifically: take a look at this function, which always returns the smaller angle, (though I'm not sure if it ill give the angles' direction too). http://docs.unity3d.com/ScriptReference/Vector3.Angle.html
That being said, I suggest you also take a look at http://docs.unity3d.com/ScriptReference/Transform.LookAt.html
This transform function will enable you to point your object at the target, with a single function call. something like (uncomplied example)..
pointyobject.transform.LookAt(targetObject.transform);
Would it be possible to get the rotation that LookAt() would result in so that I could lerp it to that over multiple frames ins$$anonymous$$d of in one call? I'm trying to get the projectile to make an arc which would end up with it facing the enemy. I don't just want it to do an about face if it's facing away from the enemy, but rather turn (at an arbitrarily specified rate) towards the enemy.
I tried using transform.LookAt(). I'm not sure it was meant to be used with 2D games. It makes the sprite stand straight up in relation to the Z axis, which is not what I'm going for.
Ah, to compute the final orientation, so you can lerp, use the static Quaternion Class version of this function: Quaternion.LookRotation() (http://docs.unity3d.com/ScriptReference/Quaternion.LookRotation.html) This returns a quaternion (which is what the rotation component of the transform is). You can them use the Quaternion Lerp function (http://docs.unity3d.com/ScriptReference/Quaternion.Lerp.html)
Regarding the fact that it is not pointing in the plane that you want: that's what the second parameter in the LookAt functions are for. In you case, you probably want to specify a Vector3 that points upwards into the Z axis (Vector3.forward)