- Home /
Why is this rotation acting odd?
I have a player character that rotates towards a gameObject tied to mouse position, but only on the y axis. This behavior works great.
Childed to the player character are two lights that should only rotates towards the mouse position on the x axis. This behavior works great --half the time.
3.It seems that whenever the world rotation of the lights goes below -90 and above 90, it flips. I've tried to add a case for this, but it didn't seem to work.
Here's my code. I'm not a smart man, so if you see an obvious math issue or a better way of doing this, please let me know.
void Update() {
parentRotation = transform.rotation.y; Vector3 dir = target.position - transform.position;
dir.Normalize();
switch (constraint) {
case Constraint.None: gameObjectLocation = new Vector3(transform.position.x, transform.position.y, transform.position.z); targetLocation = new Vector3(target.position.x, target.position.y, target.position.z);
Vector3 direction = targetLocation - gameObjectLocation; Quaternion rotation = Quaternion.LookRotation(direction); transform.rotation = Quaternion.Lerp(rotation, rotation, speed * Time.deltaTime);
break;
case Constraint.X: rotationX = (Mathf.Atan2(-dir.y, dir.z) Mathf.Rad2Deg); rotationX = Mathf.Clamp(rotationX, -maxXRotation, maxXRotation); transform.localRotation = (Quaternion.RotateTowards(transform.localRotation, Quaternion.Euler(rotationX, 0f, 0f), Time.deltaTime speed));
break;
case Constraint.Y: rotationY = (Mathf.Atan2(dir.x, dir.z) Mathf.Rad2Deg); rotationY = Mathf.Clamp(rotationY, -maxYRotation, maxYRotation); transform.localRotation = (Quaternion.RotateTowards(transform.localRotation, Quaternion.Euler(0f, rotationY, 0f), Time.deltaTime speed)); break;
case Constraint.Z: rotationZ = (Mathf.Atan2(dir.y, -dir.x) Mathf.Rad2Deg); rotationZ = Mathf.Clamp(rotationZ, -maxZRotation, maxZRotation); transform.localRotation = (Quaternion.RotateTowards(transform.localRotation, Quaternion.Euler(0f, 0f, rotationZ), Time.deltaTime speed)); break;
} }