How to move an object with either the keyboard or the mouse?

In my pong game, the user can move the paddle with the following code:

void FixedUpdate()
    float horizontal = Input.GetAxisRaw("Horizontal");

   _rb.velocity = Vector2.right * (horizontal * _speed);

Is there a way to allow the user to also move the paddle with the mouse? They should be able to freely alternate between the two during runtime.

The easiest way would be to sum the horizontal axis with the mouse x axis:

float horizontal = Input.GetAxisRaw("Horizontal") + Input.GetAxisRaw("Mouse X");

You might want to set your mouse sensitivity for that - check in the menu: Edit → Project Settings → Input.


Oh, and you might want to limit your horizontal value using Mathf.Clamp, otherwise it will be possible to move your paddle twice as fast by using both the mouse and the keyboard. :slight_smile: