Unity编程——通过射线实现物体追随鼠标位置

Source

记录个人对游戏编程的学习。

思路:

①获取屏幕位置鼠标发射的射线

②进行射线检测,获取碰撞信息

③通过碰撞信息更新物体速度和方向

最后将脚本挂在小球上即可。

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

public class rayTest : MonoBehaviour
{
    Vector3 dir;

    private void Update()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        //射线碰撞信息类
        RaycastHit hit;
        bool res = Physics.Raycast(ray, out hit);
        if(res)
        {
            dir = hit.point - transform.position;
            dir.y = 0;
        }


        transform.position = transform.position + dir * 2 * Time.deltaTime;
    }
}