Issue with moving rigidbody using mouse in Unity

Viewed 838

I have a rigidbody that I want to move with a mouse using Input.GetAxisRaw.
I know that Input.GetAxis is framerate independent but in my case it starts to move a lot faster at lower framerates. I have a suspicion that it is so because of the Rigidbody.MovePosition because it doesn't occur when I set the position directly. Dividing the mouse input by Time.DeltaTime does fix it but I'm not sure whether that's a good solution. Also I'm not sure whether that's related the input starts to get really jerky when the framerate is very high (~1000) and input sensitivity can get drastically different on different pc's.
My game is 2d with top down view.
Here's my code:

private void Update()
{
    mouse_movement = GetMouseMovement();
}

private void FixedUpdate()
{
    Vector3 new_position = transform.position + mouse_movement;
    rigidbody.MovePosition(new_position);
}

public Vector3 GetMouseMovement()
{
    Vector3 mouse_movement = new Vector3(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
    return mouse_movement * MouseSensitivity;
}

Thanks in advance.

1 Answers
  1. If you struggling from too high FPS, you can set target framerate

  2. you get your input in update, and apply it in fixed update. It means, mouse position sampled once per frame, but then applied several times between frames - on FixedUpdate. So you ARE framerate dependant. To be really framerate independant, do input check in FixedUpdate too. Or move your object in Update, multiplying value by Time.deltaTime. Just do not mix Update and FixedUpdate.

  3. You get mouse position on screen. It means, you are also resolution-dependant. There are two ways to fix: convert mouse position into world space, or calculate mouse movement as a percentage from screen size:

    movementX = Input.GetAxisRaw("Mouse X") / Screent.width;

Related