I’ve been browsing as much as I can looking for this, but none of the threads I find gets the job done.
I need to rotate an object to look at my target with a smooth transition and rotate on just one of it’s axis (the Z axis). The turret should stop to shoot, shoot, then look at the target again by just rotating on the Z axis.
I already have the timer and stuff, but when I try rotating the turret, I haven’t been able to lock the rotation on X and Y.
I’ve tried some solutions, but maybe I’ve been looking at this for too long now. I’d appreciate any suggestions.
Vector3 point = target.position;
point = new Vector3(point.x, point.y, 0);
anchorHelper.transform.LookAt(point);
which is where I have the toggle to look and not loot while aiming (it’s just a timed condition)… The thing is, when my turret “looks”, it still rotates on X, and Y, not Z only. My helper rotates on Z only, but I don’t need it to look at the target all the time. So, not working yet
Don’t use LookAt, that’ll mess things up.
I’ve had the same problem a while ago while building a turret which has two different components - a socket which basically should only rotate on the Y axis to face the player’s XZ coordinate (Y is ignored at that step, or better: it’s the same as the actual transform has) and then the gun component which should only smootly rotate towards the player’s Y coordinate by rotating on the X axis.
It was hard to find a way for this, and understanding Quaternions is not exactly the easiest thing in the world.
So here’s the full script I used:
void LookAtPlayer() {
// get vector to player but take y coordinate from self to make sure we are not getting any rotation on the wrong axis
Vector3 socketLookAt = new Vector3(playerPosition.x, movingSocket.position.y, playerPosition.z);
// create rotations for socket and gun
Quaternion targetRotationSocket = Quaternion.LookRotation(socketLookAt - movingSocket.position);
Quaternion targetRotationGun = Quaternion.LookRotation(playerPosition - movingGun.position);
// slerp rotations and assign
movingSocket.rotation = Quaternion.Slerp(movingSocket.rotation, targetRotationSocket, Time.deltaTime * rotationSmoothingSocket);
movingGun.rotation = Quaternion.Slerp (movingGun.rotation, targetRotationGun, Time.deltaTime * rotationSmoothingGun);
// important: reset local euler angles rotation of gun to make sure that we are getting rotation only on one axis
movingGun.localEulerAngles = new Vector3(movingGun.localEulerAngles.x, 0,0);
}
Once you know what to do, it’s fairly easy and looks simple enough.
So actually you just need to get a Vector3 which you can calculate a rotation to, do your Lerp/Slerp stuff and afterwards make sure that the rotation - in this case the local Euler angle(!) is reset.
I’ve tried your solution, but haven’t been able to get it to work completely, my turret object turns 180 degrees only (like from 12 o’clock to 6 o’clock), I’m not sure if it could be related to the turret being attached to a parent GameObject.