I want to rotate my canon barel on the ground towards my player in the air.
i found a tutorial
this code:
public Transform target;
void Update()
{
Vector2 direction = target.position - transform.position;
Quaternion rotation =
Quaternion.LookRotation(direction);
transform.rotation = rotation;
}
does work, but not the way i would like, seems to be rotating the barel on the wrong axis. the barels, there are 2, seem to spin around each other instead of left to right. Would also be nice to put in some contraints so the gun can only shoot (or rotate) its barells up to a certain height.
Here’s a missile turning minigame… check out the use of Mathf.Atan2() and Mathf.Rad2Deg… it will get you an angle that you can then reason about, clamping it, etc.
As for getting the axes correct, this one should be more proper for your 2D view organization, IIRC…
If you are trying to make a sprite rotate towards target on XY-plane, you can do it most likely like @Kurt-Dekker said, but you could also use lookRotation for sprites.
But you will have to sort of repurpose it; instead of using your target direction as ‘forward’ parameter, set ‘forward’ as Vector3.forward (depth axis), and use your direction as ‘upwards’ parameter of LookRotation.
Wow thanks for that great example kurt. Its funny how you dont think about things ultimately having the same functionality. i had a missile created but didnt think it as the same thing, just without forward momentum. silly billy me.
got it working great, thanks.
Are the constraints as simple as transform.position.z if less than an amount, and same for if more than an amount, dont rotate, or is there a better way to do it. How you guys enjoying the elections so far?