- Home /
Vector3.SignedAngle angle not changing when object rotates
I'm trying to rotate towards an object whilst applying some roll on the Z axis. I'm doing something wrong because the Angle never changes even when my object is rotated to face the target. If I move the target object it does change but if I move the object I am rotating it doesn't change.. I'm wanting anything on the left of forward Z to be -degrees and anything on the right of it to be +degrees.. So I'm expecting the angle to change as the object turns to face the target.. Update method below..
Vector3 direction = target.position - transform.position;
Vector3 dirTo = transform.up;
float angle = Vector3.SignedAngle(direction, dirTo, transform.forward);
float angleOffsetZ = angle * -0.2f;
Quaternion rot = Quaternion.LookRotation(target.position);
Quaternion rotZ = Quaternion.Euler(1,1, angleOffsetZ);
Quaternion combinedAngle = rot * rotZ;
transform.rotation = Quaternion.Slerp(transform.rotation, combinedAngle, 0.7f * Time.deltaTime);
Answer by TazmanNZL · Nov 19, 2021 at 09:08 PM
So I figured out that angles in Unity are not so straight forward. Vector3.right is zero degrees and anything in a circle from that is always positive. So I ended up using Vector3.angle instead and using the object forward. I'm not using Physics or a NavAgent and am moving a spaceship to a target. When the ship turns to face the target I am applying some rotation on the Z axis to make it look like the ship is banking in the turn. Problem I have is getting it to roll in the right direction when turning. Sometimes it banks left when making a right turn which looks weird. Here is what I now have. Any advice or correction in my logic would be appreciated.. Here is my new Update method..
Vector3 direction = target.position - transform.position;
float angle = Vector3.Angle(direction , transform.forward);
Quaternion rot = Quaternion.LookRotation(direction);
Quaternion angleAxis = new Quaternion();
float angle2 = transform.localEulerAngles;
if (transform.position.x > oldXPos && angle2.y > 100f) {
angleAxis = Quaternion.AngleAxis(angle * -0.35f, Vector3.forward);
}
else if (transform.position.x < oldXPos) {
angleAxis = Quaternion.AngleAxis(angle * 0.35f, Vector3.forward);
}
Quaternion combined = rot * angleAxis;
transform.rotation = Quaternion.Slerp(transform.rotation, combined, Time.deltaTime);
transform.position += transform.forward * speed * Time.deltaTime;
So turns out I was trying to do things the hard way and what I have figured out is that I can use: Vector3 shipRelative = transform.InverseTransformPoint(target.position);
This will tell me if the target is left of my ship or right of my ship.. Only took me several hours to figure this out.. sheesh..