- Home /
Question by
Nicklett4 · Jun 12, 2018 at 11:16 AM ·
gameobjecttransformmouseposition
Moving Objects to mouse position!
Looked for an answer online but cant find one. Why is this not working? http://prntscr.com/ju05l0 working on a 3d game and the Human object just flies away to a random location when i click on it. Iam trying to make it move to mouse position.
Comment
Best Answer
Answer by bakir-omarov · Jun 12, 2018 at 12:25 PM
Just use Ray. So if you hit something, just MoveTowards it.
First code will smoothly move to the mouse point:
public float movementSpeed = 10f;
private void Update()
{
if (Input.GetMouseButton(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 100.0f))
{
transform.position = Vector3.MoveTowards(transform.position, hit.point, movementSpeed * Time.deltaTime);
}
}
}
Second code will instantly move to the mouse point:
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 100.0f))
{
transform.position = hit.point;
}
}
}
So I need some help again I cant seem to figure out how to make it so it moves to where i click and not follow the mouse forever
Your answer
![](https://koobas.hobune.stream/wayback/20220612164616im_/https://answers.unity.com/themes/thub/images/avi.jpg)