下面的脚本是通用脚本,所以可以作为一个部件加载在任何可以产生毁伤的物体上。DamageReceiver脚本代码如下:
var hitPoints = 100.0;
var detonationDelay = 0.0;
var explosion : Transform;
var deadReplacement : Rigidbody;
function ApplyDamage (damage : float)
{
// We already have less than 0 hitpoints, maybe we got killed already?
if (hitPoints <= 0.0)
return;
hitPoints -= damage;
if (hitPoints <= 0.0)
{
// Start emitting particles
var emitter : ParticleEmitter = GetComponentInChildren(ParticleEmitter);
if (emitter)
emitter.emit = ***e;
Invoke("DelayedDetonate", detonationDelay);
}
}
函数对被击中或被爆炸影响的物体应用毁伤效果。如果物体生命值已经是0或者更少,不会有任何效果,否则生命数值会根据毁伤效果不断减小。当生命值比零还小的时候就会调用DelayedDetonate函数(延迟只是为了爆炸效果更酷,没别的原因)。
function DelayedDetonate ()
{
BroadcastMessage ("Detonate");
}
这就是引爆游戏物体和其子物体的方法
function Detonate ()
{
// Destroy ourselves
Destroy(gameObject);
// Create the explosion
if (explosion)
Instantiate (explosion, transform.position, transform.rotation);
如果桶子上加载了爆炸预制,那么生命值为0是就会显示这个爆炸预制。
// If we have a dead barrel then replace ourselves with it!
if (deadReplacement)
{
var dead : Rigidbody = Instantiate(deadReplacement, transform.position,
transform.rotation);
// For better effect we assign the same velocity to the exploded barrel
dead.rigidbody.velocity = rigidbody.velocity;
dead.angularVelocity = rigidbody.angularVelocity;
}
如果游戏物体还有一个死亡状态,那么桶子爆炸,然后用这种死亡状态代替这个游戏物体。同时要注意方向的一致性。
// If there is a particle emitter stop emitting and detach so it doesnt get destroyed
// right away
var emitter : ParticleEmitter = GetComponentInChildren(ParticleEmitter);
if (emitter)
{
emitter.emit = false;
emitter.transform.parent = null;
}
}
// We require the barrel to be a rigidbody, so that it can do nice physics