- Home /
Drag-and-drop gameObject inversely proportional to mouse speed?
I was trying to move an object by dragging the mouse. I can do it properly but I realize that if I drag the mouse so fast, it also makes the object move so fast and the objects collider does not work properly.
In that case, I have wondered how to make an object move with a speed which is inversely proportional to mouse speed. I mean, if I drag very fast, object moves toward the mouse point BUT SLOWLY.
As an example, you can check the Picker 3D player mechanic.
The Code I was using:
private void FixedUpdate()
{
if (Input.GetMouseButtonDown(0))
{
playerZPosition = Camera.main.WorldToScreenPoint(gameObject.transform.position).z;
offSet = gameObject.transform.position - GetMouseAsWorldPoint();
}
if (Input.GetMouseButton(0))
{
float mouseSpeed = Mathf.Abs(Input.GetAxis("Mouse X"));
playerZPosition = (Camera.main.WorldToScreenPoint(gameObject.transform.position).z) / (mouseSpeed + 1f);
Debug.Log(playerZPosition);
float x = Mathf.Clamp(GetMouseAsWorldPoint().x + offSet.x, -BORDER_ON_X, BORDER_ON_X);
transform.position = new Vector3(x, transform.position.y, transform.position.z);
}
}
Vector3 GetMouseAsWorldPoint()
{
// Pixel coordinates of mouse (x,y,z)
Vector3 mousePos = Input.mousePosition;
// z coordinate of game object on screen
mousePos.z = playerZPosition;
// Convert it to world points
return Camera.main.ScreenToWorldPoint(mousePos);
}
Not an answer to your question, but a solution to your problem.
@joshuapeacock has a very nice solution to get the collisions without slowing down. You simply cast a ray from your current position to the mouse position. If the ray hits a collider, we stop at the collider, otherwise, we move to the mouse position.
https://answers.unity.com/questions/960427/rigidbodymoveposition-skips-collisions.html
Your answer
Follow this Question
Related Questions
How to align x-axis movements with mouse x movement. 0 Answers
2d mouseposition in a 3d world 3 Answers
Cannot limit velocity when using tilt acceleration 1 Answer
Drag and Drop lagging behind mouse 0 Answers
How to make player's projectiles move to the mouse click position in a 3D top down shooter game? 0 Answers