# Setting Velocity of Rigidbody to Mouse Speed

Hello all,

I’m having some trouble working out what’s wrong with my code. To me it looks fine but obviously that’s not the case or I wouldn’t be having problems.

Basically I have a 2D sprite that I need to move with the mouse’s x position, I need it to move physics objects so I’m setting it’s rigidbody.velocity. What I need is to have the speed of the sprite match the speed of the users mouse.

Right now it half works, it will follow the mouse if it’s on the right side of it, but very slowly (so I tested multiplying the value I have by a float called ‘speed’, but I’ve removed that for the code to show how it looked before).

Anyway, the issue is that on the right side, it will move left and right correctly. If on the left side, it will move in opposite directions to the mouse. It’s hard to explain so hopefully you can see the problem in my code.

``````        float distance_to_screen = Camera.main.WorldToScreenPoint(gameObject.transform.position).z;

Vector3 pos_move = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance_to_screen));

mouseDelta = pos_move - lastMousePosition;

//if (Mathf.Abs(transform.position.x - pos_move.x) >= 1)
//{

if (platform.position.x < pos_move.x)
{
platform.velocity = Vector2.right * mouseDelta.x;
}

else //(platform.position.x > pos_move.x)
{
platform.velocity = Vector2.left * mouseDelta.x;
}

lastMousePosition = pos_move;

}
``````

All help is highly appreciated thank you!

As far as I can see I would try dividing your mouseDelta by Time.deltaTime, as this should technically give you the real velocity then…