Unity realizes mouse following (itween)


In this paper, we share the specific code of unity to achieve mouse following for your reference. The specific content is as follows

Demand:When the mouse is placed on the cube and then moved away, the cube will follow the mouse.

Implementation process:

First, create a new plane (white) and cube (black) in the scene. This cube is the object used to follow the mouse, and label the cube tile.

Then drag the following mobile code onto the camera.

The code is as follows:

using UnityEngine;
using System.Collections;
//Mouse following 
public class linearmove : MonoBehaviour
 public GameObject target;
 void Update()
  Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
  RaycastHit hit;
  if (Physics.Raycast(ray, out hit))
   if (hit.transform.gameObject.tag == "tile")
    iTween.MoveUpdate(target, new Vector3(hit.point.x, 0.1f, hit.point.z), .1f);

Code explanation:

Note that tile here is the label of the cube, which is to find the location of the mouse moving on the cube.

*The target here is plane,

*We want to make the plane follow the mouse,
*Drag the target in the panel and drag it to the plane.
*And the new vector3 in the code( hit.point .x, 0.1f, hit.point Hit means that the position of the mouse has XYZ axis position, and only x and Z axes move, so y is written as 0.1f.
*There is also a. 1F at the end, which shows the time that plane follows the mouse. The longer the time is, the slower the plane will go. When the mouse reaches the target location, the plane will continue to walk

Finally, drag the cube to the target location in the script, as shown in the following figure:

That’s OK. Look:

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.