一、子弹移动
游戏物体移动最主要的是获取一个刚体组件,再对这个刚体组件添加一个向前的力;
具体代码:
1public class BulletCtrl : MonoBehaviour 2{ 3 public int damage = 20; 4 public float speed = 1000.0F; 5 6 void Start() 7 { 8 GetComponent<Rigidbody>().AddForce(transform.forward * speed); 9 } 10}
二、设置物理引擎属性
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
具体代码:
1public class WallCtrl : MonoBehaviour 2{ 3 void OnCollisionEnter(Collision coll) 4 { 5 if (coll.collider.tag == "BULLET") 6 { 7 Destroy(coll.gameObject); 8 } 9 } 10}
如果检查到标签为bullet,则销毁游戏对象。
六、获取子弹位置
1public class MyGizmo : MonoBehaviour 2{ 3 public Color _color = Color.yellow; 4 public float _radius = 0.1F; 5 6 void OnDrawGizmos() 7 { 8 Gizmos.color = _color; 9 Gizmos.DrawSphere(transform.position, _radius); 10 } 11}
七、子弹发射
1public class FireCtrl : MonoBehaviour 2{ 3 public GameObject bullet; 4 public Transform firePos; 5 6 void Update() 7 { 8 if (Input.GetMouseButtonDown(0)) 9 { 10 Fire(); 11 } 12 } 13 14 void Fire() 15 { 16 CreateBullet(); 17 } 18 19 void CreateBullet() 20 { 21 Instantiate(bullet, firePos.position, firePos.rotation); 22 } 23}