I have a scenario where I want to rotate a cannon towards a point, for example at the mouse cursor or at an object. The script for rotating was pretty simple to setup but it’s lacking a major step, and that is that it’s rotating it’s global rotation not it’s local.
When changing the transform.rotation while the cannon is on a slope, it rotates not as expected.

This is the code currently:
public void RotateTurretTowards(float angle) {
Vector3 euler = tankTurret.transform.eulerAngles;
euler.y = Mathf.MoveTowardsAngle (euler.y, angle + turretAngleOffset, turretSpeed * Time.deltaTime);
tankTurret.transform.eulerAngles = euler;
}
public void RotateTurretTowards(Vector3 target) {
// Calculate angle towards target
Vector3 delta = target - transform.position;
//RotateTurretTowards (Mathf.Atan2(delta.x,delta.z) * Mathf.Rad2Deg);
RotateTurretTowards (Quaternion.LookRotation (delta, tankBase.transform.up).eulerAngles.y);
}
I would like a script that gives the angle towards a certain point, and I’ve failed a bit trying to make it myself.
Help?
1 Like
There are a couple of notes in this sort of situation. Ideally you want to structure your tank and turret object so that the tank has a child GameObject placed precisely at the top center where you want the turrret to pivot, and you would then put the turret itself below this pivot object.
Then when you are rotating the pivot object, keep track of a notional “heading” that the turret is facing, and from that angle, synthesize the new rotation of that pivot, using only that angle of rotation.
float angle;
angle = Mathf.Atan2( deltaX, deltaZ) * Mathf.Rad2Deg;
pivot.transform.rotation = Quaternion.Euler( 0, angle, 0);
That should get you going as long as Z+ is forward in your pictures above, and X+ is to the right, which makes Y+ be upwards.
deltaX/Z are the difference between the center of the pivot and the posiion of the cursor, calculated independently.
1 Like
The problem occurs (as shown in the gif, might not be that clear… sry for that) when the tank stands on a hill, i.e. where the transform.up isn’t necessarily just Y+…
My current solution is to just change transform.localEulerAngles instead of transform.eulerAngles. And then subtract the transform.eulerAngles to make it looking the right direction when the parent is turned.
Vector3 euler = tankTurret.transform.localEulerAngles;
euler.y = Mathf.MoveTowardsAngle (euler.y, angle - rbody.rotation.eulerAngles.y, turretSpeed * Time.deltaTime);
tankTurret.transform.localEulerAngles = euler;
This works for now, but I’m looking for a correct(?) way to do it. Or is this a good (enough) way of doing it?
1 Like