# Algo for rotating tower towards enemy - Unity

I have made a grid and placed towers and moving a enemy on it. Now i want to rotate towers face towards enemy when enemy comes in the range of tower.

I have a solution that whenever enemy comes to its range ( 2 grids far ) it starts do something, lets say when tower finds enemy is on left side it starts firing like that when enemy moves up/down ( when it finds there is a tower on very next tile) tower starts rotating with enemy position uniti enemy's range that is 2 grids far. So its mean tower has to rotate whenever enemy comes to its range and moves up/down.

What would you people suggest me a optimized way or any helpful scripting function ?..thnx

• Possibly related: gamedev.stackexchange.com/questions/1885/… Commented Oct 14, 2011 at 12:26
• You didn't mention if you want the towers to snap to their target or smoothly rotate. My answer is for the latter, while tili's answer is for the former, so you should specify that. Commented Oct 15, 2011 at 13:31

http://unity3d.com/support/documentation/ScriptReference/Transform.LookAt.html

It might help to offset the target world position to have the same height as the tower, otherwise the tower will look down/up. But that might be valid if the tower has a seperate turret model.

Unity provides functions for LERP/SLERP and those would probably work well. Basically create a target point at the same position as the enemy except moved to the tower's height, and then slerp the tower to that location.

For an example, look for the command Vector3.Lerp() in this code:

http://www.unifycommunity.com/wiki/index.php?title=SeekSteer

BONUS: You can say "I'm slerping the towers!"

Don't know about the specific functions to use in Unity, but if you want to get the actual angle of the entity relative to the tower's turning point I suggest you look at polar coordinates: http://en.wikipedia.org/wiki/Polar_coordinate_system

When you store the angle the tower currently has and calculate the one it needs to be in achieving the rotation becomes a fairly simple process, I'm sure.

It might help you to look at the problem in terms of 2D instead of 3D. Taking out the height/altitude component in your angle calculations reduces the problem to simple trigonometry.

So the basic algorithm becomes this (pseudocode):

// Assume Up is <0,1,0>
Vector2 target_position( target.X, target.Z ),
tower_position( tower.X, tower.Z );
// Quaternion construction using axis and angle.
double angle = tower_position.angle( target_position );
Quaternion tower_yaw( Vector(0,1,0), angle );
// Then concantonate the current rotation with the rotation you calculated, or you can interpolate with a slerp function if you wish.