✨unity射线用法,如果觉得对你有用,请点赞收藏关注一波,谢谢支持😘
射线
struct in UnityEngine
1、描述
射线表示形式。
射线是从 origin 开始并按照某个 direction 行进的无限长的线。
2、变量
direction 射线的方向。
origin 射线的原点。
2.1、构造函数
Ray 沿着 direction 创建从 origin 开始的射线。
2.2、使用
- 代码
声名 RaycastHit 、Ray;//
RaycastHit hit;
Ray ray;
Ray((起点)(方向))//
ray = new Ray(Vector3.up,Vector3.forward);
如果有监测到就返回true否者返回false;//
if (Physics.Raycast(ray, out hit)){
打印碰到的信息//
Debug.DrawRay(ray.origin, ray.direction * 20, Color.red);
Debug.DrawLine(ray.origin,ray.direction*20,Color.yellow);
Debug.Log(hit.collider.gameObject);
Debug.Log(hit.collider.tag);
Debug.Log(hit.point);
Debug.Log(hit.collider.transform.position);
Debug.Log(hit.collider.name);
}
3、小案例
- 案例说明
- 通过鼠标点击实现发射球去打东西
//声名
RaycastHit hit;
Ray ray;
public GameObject attack;
public float speed = 5;
//监测判断
if (Input.GetMouseButtonDown(0))
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray,out hit))
{
画线测试//
Debug.DrawLine(transform.position, hit.point, Color.red);
创建小球
GameObject a=Instantiate(attack, transform.position, Quaternion.identity);
a.GetComponent<Rigidbody>().velocity = (hit.point - transform.position) * speed;
}
}