- Home /
Move an object to a specific distance
I'm trying to move an object towards another object based on the distance of my mouse from a specific point.
First I get the distance of the mouse from the final point
float distance = Vector3.Distance(Input.mousePosition , Camera.main.WorldToScreenPoint(finalLocation));
Then I try to move the object using:
DragObject.position = Vector3.MoveTowards(DragObject.position, finalLocation, Time.deltaTime/50);
The code above moves the object based on the time passed. Can I move the object based on how close the mouse is to the final location?
It depends what you mean. Do you want to move the object the same distance from the target as the mouse click is from the target? If the distance the mouse is from the target can be represented as a percentage (compared to a reference max distance) then you can use Vector3.Lerp with the 3rd argument representing the percentage towards the target.
Thanks! Post that as an answer. What I ended up doing is the same thing but with Vector3.$$anonymous$$oveTowards.
float distance = Vector3.Distance(DragObject.position, finalLocation) - Vector3.Distance(Input.mousePosition, Camera.main.WorldToScreenPoint(finalLocation)) / 100;
DragObject.position = Vector3.$$anonymous$$oveTowards(DragObject.position, finalLocation, (Time.deltaTime) * distance);
What would be the benefits of using Lerp ?