Unity-实现打方块(射线检测和碰撞检测)
2022-12-18 本文已影响0人
ssttIsme
基本部分
创建3个立方体,添加上刚体



创建一个球体,改名为Bullet,并添加刚体

拖成预设体

删除场景上的Bullet


创建一个空对象,并添加如下脚本

using UnityEngine;
using System.Collections;
public class BulletManager : MonoBehaviour {
//炮弹预设体
public GameObject bulletPrefab;
//炮弹的飞行速度
public float moveSpeed=30f;
//射线
private Ray ray;
//射线碰撞检测器
private RaycastHit hit;
// Update is called once per frame
void Update () {
//将鼠标坐标转换成射线
ray=Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast (ray, out hit)) {
if (Input.GetMouseButton (0)) {
//生成炮弹
GameObject blt=(GameObject)Instantiate(bulletPrefab,Camera.main.transform.position,Quaternion.identity);
//给炮弹一个速度(normalized转换为单位向量)*moveSpeed保证速度一致
blt.GetComponent<Rigidbody>().velocity=(hit.point-Camera.main.transform.position).normalized*moveSpeed;
//延时销毁炮弹,4秒
Destroy(blt,4);
}
}
}
}

高级部分
如果出现穿模,调整所有方块碰撞检测为连续

可以给需要被击打消失的方块设置标签,比如为
Enemy

给Bullet预设体添加脚本

using UnityEngine;
using System.Collections;
public class HitDetect : MonoBehaviour {
private void OnCollisionEnter(Collision other){
if (other.gameObject.tag == "Enemy") {
//改变方块颜色
other.collider.GetComponent<MeshRenderer> ().material.color = Color.red;
//销毁方块
Destroy (other.gameObject,0.2f);
}
}
}