1

这是我正在从事的一个新手项目。它应该使物体在靠近边缘时反弹

我希望有人会意识到为什么这不起作用,它只是从顶部掉下来

    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++;
        }    
    }
4

2 回答 2

0

这段代码是问题所在:

 if(direction=true)

这将分配true 到方向;你需要双等号来检查是否相等:

 if (direction == true)

Java允许这样做很烦人。if 的 else 子句也有同样的问题。

于 2014-11-25T21:44:45.537 回答
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++;
    }    
}
于 2014-11-25T11:13:18.260 回答