Unity object position moves with the mouse position

After the mouse is clicked, the screen position where the mouse clicked is
obtained, and the position pos where the ray clicked in the 3D space is obtained by ray click,
Ray ray = Camera.main.ScreenPointToRay(mousePos);
Move the position of object A to point pos in real time.

Note: Ensure that there is a background with collision in the scene

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//物体位置跟随鼠标移动
public class MoveToMousePos : MonoBehaviour {
    
    

    public Transform obj;
    public Vector3 targetPos;
    public float speed;

	// Use this for initialization
	void Start () {
    
    
        //obj = this.transform;
        targetPos = obj.position;

	}

    void MoveTo()
    {
    
    
        if (Input.GetMouseButtonDown(0))
        {
    
    
            //获取鼠标位置
            Vector3 mousePos = Input.mousePosition;
            //将屏幕位置转为射线
            Ray ray = Camera.main.ScreenPointToRay(mousePos);
            //用来记录射线碰撞记录
            RaycastHit hitInfo;
            //产生射线
            bool isCast = Physics.Raycast(ray, out hitInfo);
            if (isCast)
            {
    
    
                //记录碰撞位置
                targetPos = hitInfo.point;
            }
        }

        //朝目标方向移动位置
        Vector3 pos = Vector3.MoveTowards(obj.position,targetPos,speed*Time.deltaTime);
        //更新当前位置
        obj.position = pos;
    }
	// Update is called once per frame
	void Update ()
    {
    
    
        MoveTo();	
	}
}

Guess you like

Origin blog.csdn.net/qq_22975451/article/details/113259580