- Home /
MouseLook script 90 degrees off
I'm using a standard mouselook script to point a cannon object at the mouse cursor. However, the cannon seems to always point 90 degrees to the right or left (depending upon which reference plane I build in the script). I can't figure out why it would do this, so any help would be appreciated.
Here is what I'm seeing from the cannon (red diamond represents the mouse cursor):
I've taken a standard script from here and lightly adapted it. However, there is one key difference between the classic example of this and mine: the plane upon which my items rest is that my plane is on XY, rather than XZ. This is illustrated below:
Finally, here is the code:
void Update ()
{
Plane playerPlane = new Plane(Vector3.forward, transform.position);
Ray hitRay = Camera.main.ScreenPointToRay(Input.mousePosition);
float hitDist = 0.0f;
if(playerPlane.Raycast(hitRay,out hitDist))
{
Vector3 targetPoint = hitRay.GetPoint(hitDist);
Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation,targetRotation, 1);
}
}
Any help would be much appreciated.
Answer by sparkzbarca · Dec 10, 2012 at 07:29 PM
the normal for the plane shouldnt be forward if your game lies on the forward plane.
what this code does is create a plane. That plane contains a point and has a normal that define it.
look at rotates from the objects current forward to a new rotation which have the forward pointing towards a point in space.
however since forward is the normal of the plane its going to be wanky.
I THINK you need to change it to vector3.up perhaps to get the right plane.
Appears so.
I've really hesitated to change the scene to be oriented on the up plane, since I'll have a bunch of changes to make and the idea kinda scares me.
However, if that would simplify this problem, I guess I should suck it up and refactor. Thoughts?
Edit: Just changed it to be Vector3.up, and the object doesn't react at all. It might bear mentioning that I'm using an orthographic camera, so my assumption is that according to my camera, the generated ray is parallel to Vector3.up . I might be wrong, but that's my reading.
Answer by ScottW · Dec 10, 2012 at 09:31 PM
Is your canon initially aligned to face the z direction (forward)? the blue gizmo arrow should run through the barrel of the cannon towards the barrel mouth.
Unfortunately, since the orientation of the cannon is completely set by the script, unless I'm misunderstanding you, its orientation in the editor is moot. Again, I'm new to Unity, so if I'm misunderstanding something, my apologies.
Your answer
Follow this Question
Related Questions
Rotating a 2D sprite to face a target on a single axis. 3 Answers
More specific Quaternion.LookRotation 1 Answer
Slowly rotating an object while pointing at mouse 0 Answers
SmoothDamp from 360 to 1 1 Answer
LookRotation Between 2 Points 1 Answer