2014-11-25 88 views
1

這是我正在研究的一個greenfoot項目。它應該使物體反彈,即越靠近邊緣對象不會在綠腳中檢測到世界的邊緣

我希望有人會明白爲什麼這是行不通的,它只是從頂部

import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) 

    public class Asteroid extends Actor 
    { 
     /** 
     * Act - do whatever the Asteroid wants to do. This method is called whenever 
     * the 'Act' or 'Run' button gets pressed in the environment. 
     */ 
     boolean direction=true; //assigns the fall direction (true is down false is up) 
     int acceleration =0; 
     public void act() 
     { 
      if(getY()>(getWorld().getHeight())-50 && direction== true ) 
      //checks if it is near the bottom of the world (Y is reversed so at the top of the world Y is high)  
      { 
       direction= false; 
       acceleration = 0; //Resets speed 
      } 
      if(getY()<50 && direction== false) 
      { 
       direction= true; 
       acceleration = 0; 
      } 
      if(direction=true) 
      { 
       setLocation(getX(), getY()+(int)(Greenfoot.getRandomNumber(25)+acceleration)); 
      } 
      else if(direction=false) 
      { 
       setLocation(getX(), getY()-(int)(Greenfoot.getRandomNumber(25)+acceleration)); 
      } 
      acceleration++; 
     }  
    } 

回答

0

你必須在改變你的方向下降邊界。而不是將其存儲爲布爾型(true,false),將其存儲爲(1,-1)並將其更改爲邊界。

import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) 


public class Asteroid extends Actor 
{ 
    int direction=1; 
    int acceleration=0; 

    public void changeDirection() 
    { 
     direction = direction * -1; 
    } 
    public void resetAcceleration() 
    { 
     acceleration=0; 
    } 

    public int getAcceleration() 
    { 
     int value = (Greenfoot.getRandomNumber(25) + acceleration)* direction; 
     return value; 
    } 

    public void act() 
    { 
     if(getY()>(getWorld().getHeight())-50 && direction > 0 ) 
     { 
      changeDirection(); 
      resetAcceleration(); 
     } 
     if(getY()<50 && direction < 0) 
     { 
      changeDirection(); 
      resetAcceleration(); 
     } 

     setLocation(getX(), getY()+getAcceleration()); 
     acceleration++; 
    }  
} 
0

此代碼的問題是:

if(direction=true) 

這將分配真實方向;你需要雙等於那裏檢查是否相等:

if (direction == true) 

這很煩人,Java允許這樣做。 if的else子句同樣存在問題。