I  am trying to turn the enemy turret towards player object using the Armory 3D game engine with Blender. The script is written using Haxe. I am using the following code with both the player object and enemy object. Both have their Z values set to be the same (in this case zero):

public function turnTowardsPlayer()
var A:Transform = enemyObj.transform;
var B:Transform = player.transform;

var A1:Vec2 = new Vec2(A.loc.x,A.loc.y);
var B1:Vec2 = new Vec2(B.loc.x,B.loc.y);

// Finds the Direction Vector.
var res:Vec2 = B1.sub(A1);
// Calculates the angle to turn the turret.
var rot_Z = PI + atan2(res.x,res.y);
rot_Z = -rot_Z;
trace("  --------  ");
trace("rot_Z  in radians "+rot_Z);
trace( "Rot.Z in degrees " + (rot_Z * 180/PI));
trace("  --------  ");

The above code works well if there is no change in Z value. Made following changes to take in to account of change in Z value.

var A2:Vec2 = new Vec2(A.loc.y,A.loc.z);
var B2:Vec2 = new Vec2(B.loc.y,B.loc.z);

var res_1:Vec2 = B2.sub(A2);
trace("res_1.Z   " + res_1.y);
var rot_X =  atan(res_1.y/res_1.x);
//rot_X = rot_X;
trace("rot_X  in radians "+rot_X);
trace( "Rot.X in degrees " + (rot_X * 180/PI));

The above addition works only for a certain degree of accuracy. When the player moves either far right or far left from the initial position, the enemy bullet misses the player object. In the initial position the player is directly opposite to the enemy and the bullets from enemy hit the player correctly, with Z = 2m (in Blender units).


While i am unfamiliar with the language you are using, i suggest using quaternions to solve this quite easily.

If the forward vector of the turret is pointed in the same direction as the barrel, then what you need to find is the quaternion which rotates your current forward vector, to the desired direction.

The desired direction is simply the target point minus the position of the turret. Now that you have your two vectors, use the functionality described in this article to determine the quaternion which rotates your vector to the desired direction.

What you choose to do from here is up to you. You can simply apply the quaternion if your math library allows it, or you can convert it to euler angles and/or apply the resulting rotation matrix.

Personally, if i wanted the turret to look cool, i would use slerp to make the barrel look like it is turning, rather than immediately point at the target.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.