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

2016/12/29

Moving dude

Hondrok Hondrok

2016/12/29

#
I want an actor to move between the X's 250 and 500 and it doesn't work.
import greenfoot.*;  

public class Goomba_1 extends Goomba
{
    public void act() 
    {
        if(getX()==250)
        {
            move(4);
        }
        if(getX()==500)
        {
            move(-4);
        }
    }
}    
Super_Hippo Super_Hippo

2016/12/29

#
Your Goomba is only moving if getX is equal to 250 or 500. If it is not, it won't move at all. Try this:
private int direction = 1;

public void act()
{
    move(direction * 4);
    if (getX() == 250 || getX() == 500) direction *= -1;
}
danpost danpost

2016/12/29

#
Super_Hippo wrote...
Your Goomba is only moving if getX is equal to 250 or 500. If it is not, it won't move at all. Try this: < Code Omitted >
That will not work either. If the location becomes one of the two, '250' or '500', then it will never be the other one as the difference between the two is not divisible by 4 (the speed). Try this:
private int direction = 1;

public void act()
{
    move(direction*4);
    if ((getX() <= 250 && direction == -1) || (getX() >= 500 && direction == 1)) direction *= -1;
}
Nosson1459 Nosson1459

2016/12/29

#
danpost wrote...
Try this: <Code Omitted>
That is shorter than what Hondrok has but with his code he just needs to change the "==" in the first "if" to "<=" and in the second "if" to ">=".
Hondrok Hondrok

2016/12/30

#
Nosson1459 wrote...
danpost wrote...
Try this: <Code Omitted>
That is shorter than what Hondrok has but with his code he just needs to change the "==" in the first "if" to "<=" and in the second "if" to ">=".
danpost wrote...
Super_Hippo wrote...
Your Goomba is only moving if getX is equal to 250 or 500. If it is not, it won't move at all. Try this: < Code Omitted >
That will not work either. If the location becomes one of the two, '250' or '500', then it will never be the other one as the difference between the two is not divisible by 4 (the speed). Try this:
private int direction = 1;

public void act()
{
    move(direction*4);
    if ((getX() <= 250 && direction == -1) || (getX() >= 500 && direction == 1)) direction *= -1;
}
Super_Hippo wrote...
Your Goomba is only moving if getX is equal to 250 or 500. If it is not, it won't move at all. Try this:
private int direction = 1;

public void act()
{
    move(direction * 4);
    if (getX() == 250 || getX() == 500) direction *= -1;
}
Thank youu
You need to login to post a reply.