# How do you use Quaternions to stop an objects rotation once the mouse leaves the area in front of it

New to unity & programming and have been trying to get the barrel of a cannon to rotate towards the mouse unless the mouse leaves a certain area in front of it.

Have gone through all kinds of tutorials, answer posts, and the unity script wikish thing dozens of times, can’t really figure it out. Made a post here a few days ago when I didn’t even know quaternions existed.

Closest I’ve gotten by myself is this crude thing, which converts the values in a bad manner, taking suggestions on that too; which causes the x-axis to invert and y-axis rotation to freak out. z-axis works just fine for some reason. I assume this is because of how the LookRotation function works, but I don’t know what to use instead or apply.

``````    void Update()
{
Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
Quaternion startTarget = Quaternion.LookRotation(ray.direction);

float endtargetx = startTarget.x * 360;
float endtargety = startTarget.y * 360;
float endtargetz = startTarget.z * 360;

float endx = Mathf.Clamp(endtargetx, -360, 360);
float endy = Mathf.Clamp(endtargety, -360, 360);
float endz = Mathf.Clamp(endtargetz, -360, 360);

Quaternion targetRotation = Quaternion.Euler(endx, endy, endz);

transform.rotation = targetRotation;
}
``````

Having a hard time visualizing what you’re doing here. Is it 2D? 3D? First person? Side view?

3d usually tested it by seating the main camera just behind the object. The point is so that the barrel or the object will rotate and point towards where the mouse is pointing, while not rotating the object outside of a certain area. if the cursor is pointing in front of it within like a -30 to 30 range then it’ll rotate and point towards it. otherwise it won’t, and if the cursor re-enters the range it will continue pointing towards it.

You gotta break all those problems apart: input, clamping, driving.

For this you probably want to track the lateral traverse and the vertical elevation separately with float variables.

Let’s say for argument your traverse goes from -45 to +45 and your elevation goes from +30 to 0 (horizontal).

Then have two transforms parented to each other to drive independently.

``````BaseGunTurret
--TraverseTransformRotateOnY
----ElevationTransformRotateOnX
------ActualGunBarrel
``````

When you receive input, drive only those two floats, clamping them to the limits above, and then drive the two transforms above.

As for input, define in screenspace what constitutes “close enough” to the barrel, ignore everything outside of that, and then calculate the lateral and vertical difference to produce the inputs to drive traverse and elevation.