- Home /
Look Rotation flipping object rotation after 180 degrees
Hey guys, so I'm working on a canon that rotates in the opposite direction of the mouse position. To try to make a drag system to shoot stuff (like catapaults). I've tried using transform.LookAt and Quaternion.LookRotation but they keep rotating the canon in it's local z axis when i get to half of a full rotation (180 degrees). I even tried using a gameobject as a target but it still does the same thing alt text Vector3 targPos = new Vector3(test.transform.position.x, test.transform.position.y, canon.transform.position.z); canon.transform.LookAt(targPos);
Here is it with the mouse position as target void Update() { mousePos = Input.mousePosition; mousePos.z = zDis - cam.transform.position.z; mouseLookAt = PosInvert(canon.transform.position,cam.ScreenToWorldPoint(mousePos)); canon.transform.LookAt(mouseLookAt); } Vector3 PosInvert(Vector3 origin, Vector3 pos) { float oX = origin.x; float oY = origin.y;
float pX = pos.x;
float pY = pos.y;
float x = pX - oX;
x = oX - x;
float y = pY - oY;
y = oY - y;
return new Vector3(x, y, pos.z);
}
If someone could help me with the code using the mouse position, as a target i would be very grateful
Answer by Pangamini · Oct 24, 2019 at 08:23 AM
I guess that your goal is for the cannon NOT to flip around the Y axis then One thing, the LookAt method simply calculates a new rotation quaternion. It does not take the transform's current state into consideration in any way. It also has a second, optional parameter called 'upwards'. It's a vector that helps the function determine where's the local 'up' direction (which ends up being the axis of your mentioned flipping). Now, what you want to achieve cannot be done by this 'stateless' evaluation, because the cannon can end up pointing in the same direction in two different rotations - one is upside-down. This means, logically, that your new rotation evaluation must consider the previous state, and the result rotation must be a result of moving from one state to the new one, not just getting new values each time.
Important question here: Does your cannon rotate only in one axis (eg. like in a 2D game) or does it have to aim anywhere in 3D space? Because you mentioned 'rotating at mouse position' and mouse position is not really a point in 3D space. Also, making this work in 2D is trivial; All you have to do is, calculate the rotation of the single axis, such as
transform.rotation = Quaternion.Euler(0, 0, Mathf.Atan2( mousePosition - transform.position ));
Your answer
Follow this Question
Related Questions
Bullet not moving towards player 3 Answers
Flip over an object (smooth transition) 3 Answers
Rotation via iTween.LookTo not working (or using it wrong) 1 Answer
How to set a single-axis rotation and not change the others axes 1 Answer
Quaternion Equivalent of restricting an axes rotation to zero 3 Answers