我试图让敌方首领船出现在屏幕上并攻击我的船,有时也会躲避我的攻击。到目前为止,我已经让他攻击我的船,但他仍停留在屏幕边缘。
这是我的代码:
#pragma strict
// here are public variables for the enemy ship that can be accessed in the inspector
var health:int = 2;
var explosion:GameObject;
var expOrb:GameObject;
var enemyBullet:GameObject;
var expDrop:int = 3;
var hitSound:AudioClip;
var fireRate:float = 2.0;
//heres the private variable counter to keep track of time for fire rate.
private var counter:float = 0.0;
function Update () {
//here we make counter count based on time for the fire rate
counter += Time.deltaTime;
//if the ship goes too far left, we destroy it.
if(transform.position.x < -12){
Destroy(gameObject);
}
//here we shoot 4 bullets if the counter counts higher than the fire rate.
if(counter > fireRate){
var custom1 = Instantiate(enemyBullet, transform.position - Vector3(0.5,0.1,0), Quaternion.Euler(-90,0,0));
var custom2 = Instantiate(enemyBullet, transform.position - Vector3(0.5,0.1,0), Quaternion.Euler(-90,0,0));
var custom3 = Instantiate(enemyBullet, transform.position- Vector3(0.5,0.1,0), Quaternion.Euler(-90,0,0));
var custom4 = Instantiate(enemyBullet, transform.position- Vector3(0.5,0.1,0), Quaternion.Euler(-90,0,0));
//to make the bullets spread, we add extra z velocity to each one to they all move on their own path.
custom1.rigidbody.velocity.z = 3;
custom2.rigidbody.velocity.z = 1;
custom3.rigidbody.velocity.z = -1;
custom4.rigidbody.velocity.z = -3;
counter = 0.0;
}
//end of function update
}
//if a bullet hits the ship, the bullets sends us the hit message to trigger this function to bring down the ships health
function hit () {
health -= 1;
if(health != 0){
if(audio.enabled == true){
audio.PlayOneShot(hitSound);
}
}
if(health <= 0){
onDeath();
}
}
//if health is 0, then this function is triggered to spawn some orbs, spawn the explosion animation object, and destroy itself
function onDeath () {
Instantiate(expOrb,transform.position,Quaternion.Euler(-90,0,0));
expDrop -= 1;
if(expDrop <= 0){
Instantiate(explosion,transform.position,Quaternion.Euler(-90,Random.Range(-180,180),0));
Destroy(gameObject);
}
if(expDrop > 0){
onDeath();
}
}
如何为其添加运动方面?
移动物体的方法有很多种,你可以尝试:
Transform.translate
(http://docs.unity3d.com/ScriptReference/Transform.Translate.html)修改
transform.position
(http://answers.unity3d.com/questions/188998/transformposition.html)为其添加力量 (http://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html)
还有许多我可能还不知道的其他方式。
对于此类游戏中的 Boss,您可能想要的移动要么是随机移动,要么是跟随玩家。两者都不难实现。
Random.Range(-1, 1) * bossSpeed *
time.deltaTime
并将其应用到老板的x位置。那么如何让boss有时候躲避玩家的子弹呢?您可以通过在玩家的子弹前面添加一个对撞机来让 Boss 检测到玩家的子弹是否射来。如果玩家的子弹与之碰撞,则随机生成另一个数字(例如从 0 到 1)。之后,如果随机数为1,则只需将boss移开即可,而当随机数为0时,则不要移动boss。