一、子彈移動
游戲物體移動最主要的是獲取一個剛體組件,再對這個剛體組件添加一個向前的力;
具體代碼:
public class BulletCtrl : MonoBehaviour { public int damage = 20; public float speed = 1000.0F; void Start() { GetComponent<Rigidbody>().AddForce(transform.forward * speed); } }
二、設置物理引擎屬性
Edit--->Project Settings--->Physics--->Physics Manager。
三、Collider組件
Box Collider、Sphere Collider、Capsule Collider、Mesh Collider、Wheel Collider、Terrain Collider。
四、碰撞感知條件
1)兩個碰撞物體必須都有Collider組件
2)其中移動物體還必須有Rigidboby組件
最后補充一點:觸發器是碰撞體的一個屬性,如果進行觸發檢測,就可以實現穿透。
五、Tag應用
Add Tag
具體代碼:
public class WallCtrl : MonoBehaviour { void OnCollisionEnter(Collision coll) { if (coll.collider.tag == "BULLET") { Destroy(coll.gameObject); } } }
如果檢查到標簽為bullet,則銷毀游戲對象。
六、獲取子彈位置
public class MyGizmo : MonoBehaviour { public Color _color = Color.yellow; public float _radius = 0.1F; void OnDrawGizmos() { Gizmos.color = _color; Gizmos.DrawSphere(transform.position, _radius); } }
七、子彈發射
public class FireCtrl : MonoBehaviour { public GameObject bullet; public Transform firePos; void Update() { if (Input.GetMouseButtonDown(0)) { Fire(); } } void Fire() { CreateBullet(); } void CreateBullet() { Instantiate(bullet, firePos.position, firePos.rotation); } }
