Look at an angle

Hello,

I have an angle var and a turret. I would like the turret to look at that angle which is an input from the user.

GameObject :

I have a turret model which is rigged and capable of rotating. I have an angle in another script which is static and is used in another script attached to the turret. The angle is varied using a sidescroller GUI.

Code :

var lockPos =0;

function Update ()
{

	transform.LookAt(Vector3(Projectile.angle,lockPos,lockPos), Vector3.right);
}  

Code Explanation:

I am trying the turret to look at angle which is “Projectile.angle” along the x-axis. I have defined Vector3.right as it is the x-axis(world). Moreover I made an attempt to lock the rotation in the y and z axis by defining it at zero.

Problem:

The turret for some reason rotates to the Z axis and lifts it’s cannon hand upwards, with respect to the x axis. Beyond that I even tried to adjust the “angle” which had no effect on the angle of the cannon.

Request:

I humbly request for the shot on the problem on the code or the code I should change. I am just trying to create Projectile motion in a 2D plane(x-y plane) using the LookAt() function. Apart from this, (not a main concern) if you guys know any good turret/cannon models to import - please do let me know.

Thank YOU

125SCREENSHOT125

That’s not the way Transform.LookAt works - it can look at some transform or world point, not to an specific direction or angle. If you want to aim to some angle, you can create a vector with this elevation angle and add it to transform.position - this will create a world point in the desired direction, to which you can aim using LookAt:

function Update (){
    var angle = Projectile.angle * Mathf.Deg2Rad; // convert the angle to rads
    // create a vector with the desired angle:
    var targetDir = Vector3(0, Mathf.Sin(angle), Mathf.Cos(angle));
    // make transform look at a point in the desired direction:
    transform.LookAt(transform.position + targetDir);
}

Notice that this code will generate an angle that rotates around X, what means in the YZ plane. Something is telling me that what you really want is an elevation angle from the X axis - supposing Y is the vertical direction, what is needed in this case is an angle around Z, or in the XY plane. If this is true, the targetDir calculation should be the following:

var targetDir = Vector3(Mathf.Cos(angle), Mathf.Sin(angle), 0);

This will generate a vector with an elevation of Projectile.angle degrees from the X axis, supposing Y is the vertical direction.