Large games often have this scene, click on the screen location, the characters will move toward the mouse click position, the following we will achieve this effect.
First, we add a plane to the scene and set its tag to plane, then, add a cube to the plane, set the position, just put it on top of the plane, and finally, add a script to the cube with the following script:
using unityengine;using System.collections;public class RayCastTest: Monobehaviour {//cube move speed public float = 3f; Private Vector3 offsetvec;//update is called once per framevoid update () {Raycasthit hitinfo; Ray Ray = Camera.main.ScreenPointToRay (input.mouseposition); if (Physics.raycast (ray, out Hitinfo, 100)) {//When the ray collides to plane and the left mouse button is pressed if (hitInfo.transform.tag = = "Plane" && input.getmousebuttondown (0)) {//Let cube direction toward click Position TRANSFORM.L Ookat (Hitinfo.point); Offsetvec = hitinfo.point-transform.position; }}//The magnitude of the vector indicates the length of the vector, which stops moving when the cube is less than 1 from the point where we clicked, this value can be adjusted if (Offsetvec.magnitude > 1f) {transform. Translate (Vector3.forward * speed * time.deltatime); Update the value of Offsetvec Offsetvec = hitinfo.point-transform.position; }}}
When running, there may be some bugs, such as when the cube moves forward, the coordinates will gradually shift downward, this phenomenon is because the coordinates of the click position is lower than the cube coordinates, get to click Position coordinates to modify the y-axis size can eliminate this bug.
Unity gets mouse Click position, object moves toward mouse click