2016-01-27 2 views
0

Хорошо, поэтому в моем классе разработки игр мы используем GreenFoot для создания игры. Она попросила нас сделать самую сложную игру Астероидов, которую мы могли бы сделать, честно говоря. Поэтому я решил добавить множество ракетных жизней. я получил все это, и он работает, он просто никогда не уменьшает жизнь ракеты, так как я могу это сделать?Почему моя ракета не уменьшится при столкновении?

Вот мой код:

import greenfoot.*; // (World, Actor, GreenfootImage, and Greenfoot) 
import java.util.List; 

/** 
* A rocket that can be controlled by the arrowkeys: up, left, right. 
* The gun is fired by hitting the 'space' key. 
* 
* @author Poul Henriksen 
* @author Michael Kölling 
* 
* @version 2.0 
*/ 
public class Rocket extends Mover 
{ 
    private int gunReloadTime;    // The minimum delay between firing the gun. 
    private int reloadDelayCount;   // How long ago we fired the gun the last time. 
    private Vector acceleration;   // A vector used to accelerate when using booster. 
    private Vector deacceleration; 
    private int shotsFired;     // Number of shots fired. 
    private int rocketLives; 
    private int collisionDamage = 999; 

    private GreenfootImage rocket = new GreenfootImage("rocket.png"); 
    private GreenfootImage rocketWithThrust = new GreenfootImage("rocketWithThrust.png"); 

    /** 
    * Initialise this rocket. 
    */ 
    public Rocket() 
    { 
     gunReloadTime = 10; 
     reloadDelayCount = 0; 
     acceleration = new Vector(0, 0.035); // used to accelerate when thrust is on 
     deacceleration = new Vector(0, -0.035); 
     increaseSpeed(new Vector(13, 0.3)); // initially slowly drifting 
     shotsFired = 0; 
     rocketLives = 3; 
    } 

    /** 
    * Do what a rocket's gotta do. (Which is: mostly flying about, and turning, 
    * accelerating and shooting when the right keys are pressed.) 
    */ 
    public void act() 
    { 
     if (rocketLives == 0) 
     { 
      getWorld().removeObjects(getWorld().getObjects(null)); 
      Greenfoot.stop(); 
     } 
     else 
     { 
      move(); 
      checkKeys(); 
      checkCollision(); 
      reloadDelayCount++; 
     } 
    } 

    /** 
    * Return the number of shots fired from this rocket. 
    */ 
    public int getShotsFired() 
    { 
     return shotsFired; 
    } 

    /** 
    * Set the time needed for re-loading the rocket's gun. The shorter this time is, 
    * the faster the rocket can fire. The (initial) standard time is 20. 
    */ 
    public void setGunReloadTime(int reloadTime) 
    { 
     gunReloadTime = reloadTime; 
    } 

    /** 
    * Check whether we are colliding with an asteroid. 
    */ 
    private void checkCollision() 
    { 
     Asteroid asteroid = (Asteroid) getOneIntersectingObject(Asteroid.class); 
     if (asteroid != null) 
     { 
      getWorld().addObject(new Explosion(), getX(), getY()); 
      getWorld().addObject(new Rocket(), (1350/2)-20, 1000/2); 
      if(isTouching(Asteroid.class)) { 
       asteroid.hit(999); 
      } 
      getWorld().removeObject(this); 
      rocketLives--; 
     } 
    } 

    /** 
    * Check whether there are any key pressed and react to them. 
    */ 
    private void checkKeys() 
    { 
     ignite(Greenfoot.isKeyDown("w")); 

     if(Greenfoot.isKeyDown("s")) { 
      deignite(Greenfoot.isKeyDown("s")); 
     } 
     if(Greenfoot.isKeyDown("a")) { 
      turn(-5); 
     }   
     if(Greenfoot.isKeyDown("d")) { 
      turn(5); 
     } 
     if(Greenfoot.isKeyDown("space")) { 
      fire(); 
     } 
     if(Greenfoot.isKeyDown("shift")) { 
      int ran1 = (int)(Math.random()*1350); 
      int ran2 = (int)(Math.random()*1000); 
      getWorld().addObject(new Asteroid(), ran1, ran2); 
     } 
    } 

    /** 
    * Should the rocket be ignited? 
    */ 
    private void ignite(boolean boosterOn) 
    { 
     if (boosterOn) { 
      setImage(rocketWithThrust); 
      acceleration.setDirection(getRotation()); 
      increaseSpeed(acceleration); 
     } 
     else { 
      setImage(rocket);   
     } 
    } 

    private void deignite(boolean boosterOn) 
    { 
     if (boosterOn) { 
      setImage(rocketWithThrust); 
      deacceleration.setDirection(getRotation()); 
      increaseSpeed(deacceleration); 
     } 
     else { 
      setImage(rocket);   
     } 
    } 

    /** 
    * Fire a bullet if the gun is ready. 
    */ 
    private void fire() 
    { 
     if (reloadDelayCount >= gunReloadTime) { 
      Bullet b = new Bullet(getMovement().copy(), getRotation()); 
      getWorld().addObject(b, getX(), getY()); 
      b.move(); 
      shotsFired++; 
      reloadDelayCount = 0; // time since last shot fired 
     } 
    } 
} 
+0

Вы отлаживали его? – Thomas

+1

Я вижу только «rocketLives», уменьшенный в 'checkCollision()', поэтому проверьте, вызвано ли это, и ракета в конечном итоге пересекает астероид. Btw, 'isTouching (Asteroid.class)' выглядит как очень нечетный синтаксис, то есть для меня этот блок читается как «если он прикасается к _any_ астероиду, тогда ударяйте его с той силой (или что-то в этом роде) 999». – Thomas

ответ

2

Я думаю, что я видел, ваша ошибка (отладка должна показать это, а):

Это следующая часть в checkCollision():

getWorld().addObject(new Rocket(), (1350/2)-20, 1000/2); //here 
if(isTouching(Asteroid.class)) { 
    asteroid.hit(999); 
} 
getWorld().removeObject(this); //and here 

При столкновении вы добавляете в мир новую ракету (которая инициализируется 3 жизни) и удалить текущий. Таким образом, у вас всегда есть ракета с тремя жизнями. Просто повторите использование текущей ракеты, пока она не умрет.

+0

Ах, я вижу свою ошибку, как бы я переместил положение ракеты, когда он вступает в контакт с Астероидом? –

+0

@JonCole Я не знаю фреймворк, который вы используете, но не можете ли вы просто установить положение на все, что вам нужно? – Thomas

+0

Я понял это, я использовал 'this.setLocation (1350/2, 1000/2);' Установить его в середине –