- Home /
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!
Alright so I've got it to where it's on the correct side, but it doesn't follow the mouse directly, it will only take it's speed in that direction and keep moving unless I change the mouse position.
What I was trying to do was have the platform ease into the mouse's location (both acceleration and deceleration) until it's exactly where the mouse is.
Here is what I have now:
acceleration = mouseDelta.x * 0.4f;
platformVelocity += acceleration;
platform.velocity = new Vector2(platformVelocity, 0) * speed;
That code is in-place of the "if (platform)" statements.
Any ideas? I'm quite stuck.
Answer by Rob2309 · Mar 23, 2016 at 01:37 PM
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...