利用射线检测,检测两帧子弹位置连线是否碰撞敌人,并改变敌人状态。
控制敌人射出的子弹的类如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SoliderAmmoController : MonoBehaviour
{
public float velocity = 50f;
public float dis;
public Vector3 posRecord;
public Ray ray;
public RaycastHit hit;
public int damage = 10;
float flyTime = 0f;
Vector3 gravity;
// Start is called before the first frame update
void Start()
{
Destroy(gameObject, 2.5f);
gravity = new Vector3(0f, 4.9f, 0f);
}
// Update is called once per frame
void Update()
{
ammoMovement();
}
void ammoMovement()
{
flyTime += Time.deltaTime;
posRecord = transform.position;
transform.position += (transform.forward * velocity * Time.deltaTime-0*gravity*flyTime*flyTime);
dis = (posRecord - transform.position).magnitude;
if (dis > 0)
{
if (Physics.Raycast(posRecord, transform.forward, out hit,dis))
{
if (hit.transform.tag == "Player")
{
hit.transform.GetComponent<CarController>().currentHealth -= 10;
hit.transform.GetComponent<AudioSource>().clip = hit.transform.GetComponent<CarController>().metalShooted;
hit.transform.GetComponent<AudioSource>().Play();
}
Destroy(gameObject);
}
}
}
}
代码说明:
首先要声明射线类Ray和射线击中返回信息类RaycastHit的实例
public Ray ray;
public RaycastHit hit;
之后调用射线检测的函数,其中Physics.Raycast的输入数据类型为Physics.Raycast(Vector3,Vector3,RaycastHit,float),第一个是发射点,第二个是射线方向,第三个是碰撞物信息,第四个是射线长度,输出为bool型。
下面是检查玩家子弹是否打中敌人的程序逻辑,分为打中身体和爆头两种情况。
if (Physics.Raycast(posRecord, transform.forward, out hit, dis))
{
if (hit.transform.tag == "SoliderBody")
{
Transform solider = hit.transform.parent;
solider.GetComponent<SoliderController>().currentBlood -= 10;
solider.GetComponent<SoliderController>().nowState = 4;
solider.GetComponent<Animator>().SetInteger("soliderState", 4);
solider.GetComponent<Animator>().SetInteger("damageState", (int)Random.Range(1f, 3.99f));
solider.GetComponent<SoliderController>().waitTime = 0.667f;
solider.GetComponent<SoliderController>().nevrousTime = 10f;
solider.GetComponent<AudioSource>().clip = solider.GetComponent<SoliderController>().bodyShooted;
solider.GetComponent<AudioSource>().Play();
}
if (hit.transform.tag == "SoliderHead")
{
Transform solider = hit.transform.parent;
solider.GetComponent<AudioSource>().clip = solider.GetComponent<SoliderController>().headShooted;
solider.GetComponent<AudioSource>().Play();
solider.GetComponent<SoliderController>().currentBlood -= 110;
}
Destroy(gameObject);
}
该代码示例展示了如何在Unity中利用射线检测判断子弹是否击中敌人,根据命中部位(身体或头部)改变敌人状态并播放相应音效。SoliderAmmoController类控制子弹运动,通过Physics.Raycast进行碰撞检测,根据hit.transform.tag区分击中类型,调整敌人的血量和动画状态。
1579

被折叠的 条评论
为什么被折叠?



