unity raycasthit讲解

新建一个场景加三个方块,如图unity raycasthit讲解_第1张图片
在随便一个物体上加上脚本

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

public class Test : MonoBehaviour
{
     
    public Transform cube1, cube2;

    // Start is called before the first frame update
    void Start()
    {
     
        Debug.Log(LayerMask.GetMask("Shootable"));
    }

    // Update is called once per frame
    void Update()
    {
     
        Ray ray =  Camera.main.ScreenPointToRay(Input.mousePosition);
       // Ray ray = new Ray(Camera.main.transform.position, Input.mousePosition);
        RaycastHit hit;
        if( Physics.Raycast( ray , out hit ,100,LayerMask.GetMask("Shootable") ))
        {
     
            hit.transform.position   += new Vector3(1, 0, 0);  
        }
          
        
    }
}

大致意思是如果点击到某个方块,该方块就像右移动一个单位
其中ray是从相机发出的一条射线,终点位置为鼠标的位置,如果该射线碰撞到摸个物体,raycast就返回true,
其中,要定义一个raycasthit的变量,传入参数前的out类似c++的引用
100是指距离 在后面是物体的layer层属性

方块的layer设置为shootable,plan的layer层设置为floor(没有就add layer)
方块记得加上collider碰撞体
然后可以点击运行了,只要鼠标碰到方块,方块就会动
unity raycasthit讲解_第2张图片

你可能感兴趣的:(unity)