Unity3d get Mouse Input Axis

2.7k views Asked by At

I want to rotate a GameObject through mouse movement between -20° and +20°.

I know that there's a possibility to grab the smoothed Input through Input.GetAxis("Horizontal"); and Input.GetAxis("Vertical"); which returns float values between -1 and 1

It would be nice if there would exist something like Input.GetMouseAxis("Horizontal"); or Input.GetMouseAxis("Horizontal");.

But I the output shouldn't be influenced by keyboard. I'm sorry that I don't have much experience with Unity and its API.

1

There are 1 answers

0
maraaaaaaaa On BEST ANSWER

is the mouse in unity "captured" in screen resolution or how should I scale the mouse Position to a value between -1 and 1 ?

In this case the "normalizedSpeed" will be your target

public float mouseDistance;
public Vector2 mouseDown = -Vector2.one;

public float normalizedSpeed;

public void Update()
{
   if(Input.GetMouseButtonDown(0))
      mouseDown = Input.MousePosition();

   if(Input.GetMouseButtonUp(0))
      mouseDown = -Vector2.one;

   if(Input.GetMouseButton(0))
      normalizedSpeed = mouseDown != -Vector2.one ?
      Mathf.Clamp((mouseDown - Input.MousePosition()).sqrMagnitude, 0, (mouseDistance * mouseDistance)) / (mouseDistance * mouseDistance)
      : 0;
}

i use sqrMagnitude instead of distance because the sqr root call in distance() takes alot of memory, so it is faster to compare the squared distances vs each other

Also keep in mind im wirting this as a pseudo-code so the overall idea is what im going for, im leaving you syntactically responsible for the implementation ;)