//射线检测讲解
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ZDScript : MonoBehaviour
{
//注意:如果movespeed物体移动速度过快(一般大于200以上),碰撞检测方法(OnTriggerEnter、OnCollisionEnter)将失效
//解决方案:游戏开始时,使用射线检测
public float movespeed = 300;
//射线检测的目标物体信息
RaycastHit hit;
public LayerMask make; //层级物体类型,要public类型,方便在unity面板选择
bool rayPdl;
//最远距离
private int MaxDistance = 100;
//目标位置
Vector3 tagD;
private void Start()
{
//物理类的Raycast方法讲解
//Raycast 方法的重载15 讲解
//Physics.Raycast(起点坐标,方向(正前方:this.transform.forward),返回的射线受击物体信息,射线发射最大距离,检测哪个层级物体?)
//如敌人在NPC层,其他层的物体射线就不再检测,只检测NPC层中的物体!!--重点
//Physics.Raycast 返回bool值,意味射线检测到了吗
rayPdl = Physics.Raycast(this.transform.position, this.transform.forward, out hit, MaxDistance, make);
if (rayPdl == true)
{//射线检测到物体
//检测到物体时,子弹目标位置前进至目标物体点即可
tagD = hit.point; //击中的位置
print(hit.point);
}
else
{//射线没有检测到物体
//如果没有检测到物体时,子弹就向前前进至子弹前方100米
tagD = this.transform.position + this.transform.forward * MaxDistance;
print("没有检测到目标");
}
}
private void Update()
{
//Time.frameCount 属性是查看当前过了多少帧帧
print(Time.frameCount + "--" + this.transform.position);
//子弹每帧匀速移动(Vector3.MoveTowards)
this.transform.position = Vector3.MoveTowards(this.transform.position, tagD, Time.deltaTime * movespeed);
if ((this.transform.position- tagD).sqrMagnitude < 0.1f)
{
print("接触目标点");
Object.Destroy(this.gameObject);//接触之后销毁子弹
}
}
}
|