2013-04-24 97 views
0

在遊戲中,我正在創造我只想讓殭屍能夠每分鐘擊中玩家2次,而不是帶走洞穴健康欄,因爲它會損害玩家的速度。爲玩家設置無敵框架

public void checkCollision(){ 
    Rectangle r3 = player.getBounds(); 
    for(int i = 0; i < zombie.size(); i++){ 
     Zombie z = (Zombie) zombie.get(i); 
     Rectangle r2 = z.getBounds(); 
     if(r3.intersects(r2)){ 
      if(!player.getInvincibility()){ 
       player.setHealth(player.getHealth() - 10); 
       player.setInvincibility(true); 
      } 
     } 
    } 
} 

這是檢查玩家和殭屍的碰撞的代碼。我已經做到這樣,玩家只會受到10點傷害,但是玩家永遠不會再受到傷害。我曾嘗試使用if語句來檢查玩家是否無敵,並且在if語句中有一個for循環,當int達到30 000時會使玩家死亡,但殭屍仍然會對玩家造成如此之快的傷害健康酒吧的蓋茨被帶走。

回答

0

有一個被稱爲每幀的方法 - 稱之爲updateTimers或其他。該方法應該使玩家的invincibilityTimer減少一定數量。然後,如果玩傢俱有非零不敗定時器,他們很容易受到checkCollission中的傷害,這也會將invincibilityTimer設置爲一個設定的數字。

1

對殭屍使用攻擊冷卻時間。

在我的遊戲我有類似

public boolean isReadyToAttack() { 
    boolean ret; 
    long delta = System.currentTimeMillis() - t0; 
    timer += delta; 
    if (timer > attackCooldown) { 
     timer = 0; 
     ret = true; 
    } else { 
     ret = false; 
    } 
    t0 = System.currentTimeMillis(); 
    return ret; 
} 

然後你只需在你的循環檢查這一點,如果殭屍還沒有準備好,他不會,即使他是接近攻擊(其實這是更好檢查碰撞前的冷卻時間,它便宜)ø

0

我喜歡做一個報警類來處理諸如「等10幀,然後打印'Hello world!到控制檯「:

public class Alarm { 
    //'timer' holds the frames left until the alarm goes off. 
    int timer; 
    //'is_started' is true if the alarm has ben set, false if not. 
    boolean is_started; 
    public Alarm() { 
     timer = 0; 
     is_started = false; 
    } 
    public void set(int frames) { 
     //sets the alarm to go off after the number of frames specified. 
     timer = frames; 
     is_started = true; 
    } 
    public void tick() { 
     //CALL THIS EVERY FRAME OR ELSE THE ALARM WILL NOT WORK! Decrements the timer by one if the alarm has started. 
     if (is_started) { 
      timer -= 1; 
     } 
    } 
    public void cancel() { 
     //Resets the frames until the alarm goes off to zero and turns is_started off 
     timer = 0; 
     is_started = false; 
    } 
    public boolean isGoingOff() { 
     //Call this to check if the alarm is going off. 
     if (timer == 0 && is_started == true) { 
      return true; 
     } 
     else { 
      return false; 
     } 
    } 
} 

你可以讓一個無敵框架本身(假設玩家有一個報警叫invincibility_alarm並且它被設置爲當一個殭屍擊中玩家30幀):

//Pretend this is your gameloop: 
while (true) { 
    if (player.invincibility_alarm.isGoingOff()) { 
     player.setInvincibility(false); 
     player.invincibility_alarm.cancel(); 
    } 
    player.invincibility_alarm.tick(); 
    Thread.sleep(10); 
}