L
L
Lev Kekish2016-08-03 19:46:33
Game development
Lev Kekish, 2016-08-03 19:46:33

How to organize movement towards the cursor in Unity3d?

There is a task: the object should move in the direction of the cursor.
There is a line in Update() that is responsible for rotating the object with the mouse:
float h = horizontalSpeed ​​* Input.GetAxis("Mouse X");
transform. Rotate(0, h, 0);
Question: how to direct the object at an angle that we get with the mouse?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Daniil Basmanov, 2016-08-05
@levik200

Use Camera.ScreenPointToRay to find the ray from the camera in the direction of the click. Then find a point on the ground using Physics.Raycast . Next, take the direction vector to this point:
To find the rotation you take Quaternion.LookRotation and pass toPoint to it. Keep in mind that this vector can extend beyond the XZ plane, so it needs to be projected onto the plane and normalized before being used.

toPoint.y = 0;
toPoint.Normalize();

If the vector was close in the direction of the Y axis, then after projection it may be equal to zero. Quaternion.LookRotation will complain about this, so it's better to insert a toPoint == Vector3.zero.

R
Roman Sakutin, 2016-08-03
@romaan27

transform.Translate(transform.forward);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question