首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对象无法在greenfoot中检测到世界的边缘

对象无法在greenfoot中检测到世界的边缘
EN

Stack Overflow用户
提问于 2014-11-25 18:44:32
回答 2查看 511关注 0票数 1

这是我正在做的一个greenfoot项目。它的作用是使物体在接近边缘时反弹。

我希望有人能意识到为什么它不能工作,它只是从上面掉下来

代码语言:javascript
复制
    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++;
        }    
    }
EN

回答 2

Stack Overflow用户

发布于 2014-11-25 19:13:18

你需要改变你在边界的方向。不是将其存储为布尔值(true,false),而是将其存储为(1,-1)并在边界处更改它。

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2014-11-26 05:44:46

以下代码就是问题所在:

代码语言:javascript
复制
 if(direction=true)

这会将true赋值给方向;您需要在那里使用双等号来检查是否相等:

代码语言:javascript
复制
 if (direction == true)

令人恼火的是Java允许这样做。if上的else子句也存在同样的问题。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27124530

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档