unity3d-射线

✨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;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SYFStrive

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值