2014-11-25 55 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子句同样存在问题。