Object wont detect edge of world in greenfoot

566 Views Asked by At

This is a greenfoot project I'm working on. It is supposed to make the object bounce when it nears the edge

I was hoping someone would realize why this isn't working, it just falls from the top

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

There are 2 best solutions below

0
On

This code is the problem:

 if(direction=true)

This will assign true to direction; you need double-equals there to check for equality:

 if (direction == true)

It's annoying that Java allows this. Same problem for the else clause on the if.

0
On

You need to change your direction at boundaries. Instead of storing it as boolean (true,false), store it as (1,-1) and change it at boundaries.

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