This site requires JavaScript, please enable it in your browser!
Greenfoot back
OxiClean
OxiClean wrote ...

2013/4/17

How to move on the y-axis

OxiClean OxiClean

2013/4/17

#
How do I move the object Square2 along the y-axis continually? What I mean is when it touches the top of the world, it goes down. Then, when it hits the bottom, it moves back up. Thanks in advance!
JetLennit JetLennit

2013/4/17

#
//add this variable 1st
private int moving;


//then in the constructor
moving = 10


//add this to act()
int groundLevel = getWorld().getHeight() - getImage().getHeight()/2;
if(getY() == 5) moving = 10;
if(getY == groundLevel) moving = 10;
setLocation(getX(), getY() + moving);
danpost danpost

2013/4/17

#
Just tell it to do just that in the act method of the Square2 class; you only need one field to track the direction of movement (up or down: '-1' or '1').
// first declare the field(s)
private int direction = 1;
// then the act method
public void act()
{
    int buffer = getImage().getHeight() / 2;
    if (getY() < buffer || getY() > getWorld().getHeight() - buffer)
    {
        direction = -direction;
    }
    setLocation(getX(), getY() + direction * speed); // see note below
}
The value of 'speed' in the last line can be hard-coded in place or declared as another field set to any positive value that is less than the value of 'buffer'.
danpost danpost

2013/4/17

#
Sorry, JetLennit -- I was working on this for a little while, debating adding the 'speed' variable or not. Forgot to refresh to see if anybody else posted before I posted.
JetLennit JetLennit

2013/4/17

#
It's fine, it is probably better that @OxiClean has more options to see which code he wants to use
OxiClean OxiClean

2013/4/18

#
True that, @JetLennit. Thanks a bunch guys!
JetLennit JetLennit

2013/4/18

#
Your welcome!
You need to login to post a reply.