事情是这样的,今天我打算复原我的世界,做到摧毁方块的功能时,就想不到可以用什么办法来检测,一开始我想用射线检测,可射线检测我不会...于是我又想到了碰撞检测
Fire.cs,代码如下。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class Fire : MonoBehaviour {
GameObject obj;
void Start() {
//获取球类对象
obj = GameObject.Find("FirePoint");
}
void Update() {
if (Input.GetMouseButton(0)) {
obj = GameObject.Find ("FirePoint(Clone)");
if (obj) {
obj = GameObject.Find ("FirePoint(Clone)");
this.obj.transform.Translate(new Vector3(0, 0, 2 * Time.deltaTime));
obj = GameObject.Find("FirePoint");
} else {
obj = GameObject.Find("FirePoint");
GameObject clone = Instantiate(obj, obj.transform.position, obj.transform.rotation);
obj = GameObject.Find ("FirePoint(Clone)");
this.obj.transform.Translate(new Vector3(0, 0, 2 * Time.deltaTime));
Destroy(clone, 1.25f);
obj = GameObject.Find("FirePoint");
}
obj = GameObject.Find("FirePoint");
}
if (Input.GetMouseButton(1)) {
obj = GameObject.Find ("FirePoint(Clone)");
if (obj) {
obj = GameObject.Find ("FirePoint(Clone)");
this.obj.transform.Translate(new Vector3(0, 0, 2 * Time.deltaTime));
obj = GameObject.Find("FirePoint");
} else {
obj = GameObject.Find("FirePoint");
GameObject clone = Instantiate(obj, obj.transform.position, obj.transform.rotation);
obj = GameObject.Find ("FirePoint(Clone)");
this.obj.transform.Translate(new Vector3(0, 0, 2 * Time.deltaTime));
Destroy(clone, 1.25f);
obj = GameObject.Find("FirePoint");
}
obj = GameObject.Find("FirePoint");
}
}
}
把这个脚本附到摄像机身上。
下一个脚本是挂在要被挖掘的方块上的
Block.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Block : MonoBehaviour {
int Health = 1;
// Start is called before the first frame update
void Start() {
}
// Update is called once per frame
void Update() {
if (Health <= 0) {
Destroy(this.gameObject);
}
}
private void OnTriggerEnter(Collider other) {
if (other.tag == "Bullet") {
Health--;
}
}
}
下面的设置:
被挖掘方块的设置:
这里加两个碰撞体是因为角色也需要碰撞体,如果不打“Is Trigger”会检测不到,打上角色就会掉下去了,所以两个都得加。
由于用的是碰撞检测,所以我们需要附加碰撞体,添加“FirePoint”检测器。
子弹设置:
调试时一定要确保子弹轨迹要在游戏准心内。