Unity gets mouse Click position, object moves toward mouse click

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.