2-20 Preventing Projectile Pass-Through
不知道大家有沒有發現,如果我們把Projectile的移動速度調整超高,如500。
這時就會發現,Projectile已經射穿玩家了,但是卻沒有損血!這是因為移動的距離太遙遠了才會這樣,所以我們要修正這個Bug,需要改用Ridigbody的Collision系統。
大家可以先去看Rigidbody介紹,了解一下Collision系統。
https://docs.unity3d.com/Manual/class-Rigidbody.html
官方說:
Collision Detection
|
Used to prevent fast moving objects from passing through other objects without detecting collisions.
|
- Discrete
|
Use Discrete collision detection against all other colliders in the scene. Other colliders will use Discrete collision detection when testing for collision against it. Used for normal collisions (This is the default value).
|
- Continuous
|
Use Discrete collision detection against dynamic colliders (with a rigidbody) and continuous collision detection against static MeshColliders (without a rigidbody). Rigidbodies set to Continuous Dynamic will use continuous collision detection when testing for collision against this rigidbody. Other rigidbodies will use Discrete Collision detection. Used for objects which the Continuous Dynamic detection needs to collide with. (This has a big impact on physics performance, leave it set to Discrete, if you don’t have issues with collisions of fast objects)
|
- Continuous Dynamic
|
Use continuous collision detection against objects set to Continuous and Continuous Dynamic Collision. It will also use continuous collision detection against static MeshColliders (without a rigidbody). For all other colliders it uses Discrete collision detection. Used for fast moving objects.
|
簡而言之,會快速移動的物體需要設定成Continuous Dynamic,而被偵測的物體設定成Continuous。所以,我們先選擇會快速移動的Projectile物件。
將Sphere Collider的Is Trigger關掉。
並將Rigidbody的Collision Detection設定成Continuous Dynamic,並將Mass設為0(否則人物角色被那顆球球打中以後會向後移動)。
Player的Rigidbody的Collision Detection設定成Continuous。
執行遊戲看看,就會發現球球射出後,撞到玩家會彈出去,每一發都會彈出去。
所以現在我們可以確保球球能夠擊中玩家了,接下來程式碼再改成當球球撞到玩家以後會損血,並且把球球消滅掉就可以了。接下來Projectile程式碼:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Projectile : MonoBehaviour { public float projectileSpeed; float damageCaused; public void SetDamage(float damage){ damageCaused = damage; } void OnCollisionEnter(Collision collision){ // 取得Component為IDamageable Component damageableComponent = collision.gameObject.GetComponent (typeof(IDamageable)); // 若IDamageable存在 if (damageableComponent) { // 呼叫damageableComponent的TakeDamage方法 (damageableComponent as IDamageable).TakeDamage (damageCaused); } // 自我消滅 Destroy(gameObject); } }
執行遊戲後,球球碰到玩家會損血,也會自動消失了。
留言
張貼留言