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

2014/5/7

Help request: Trying to get two objects to move at the same time using 1 control.

BingoWasHisNamo BingoWasHisNamo

2014/5/7

#
Hi, I'm really new to coding, and I need some help from someone. I'm trying to get two objects to move at the same time, however, when I try to make them move at the same time, one moves, and then the other moves. My current coding is
while (Greenfoot.isKeyDown("right"))
        {
            setImage(image1);
            setLocation(getX() + moveInt, getY());
            Greenfoot.delay(2);
            setImage(image2);
            setLocation(getX() + moveInt, getY());
            Greenfoot.delay(2);
            setImage(image3);
            setLocation(getX() + moveInt, getY());
            Greenfoot.delay(2);
            setImage(image4);
            setLocation(getX() + moveInt, getY());
            Greenfoot.delay(2);
            setImage(image5);
            setLocation(getX() + moveInt, getY());
            Greenfoot.delay(2);
            setImage(image0);
            setLocation(getX() + moveInt, getY());
            Greenfoot.delay(2);
        }
It's the same for the second object, just without the setImage. Thanks for the help
Jonche Jonche

2014/5/7

#
Try to replace the "while" loop with an "if" condition, these are more current for the keyPressing checks.
Jonche Jonche

2014/5/7

#
Oh and the Greenfoot.delay stops the whole greenfoot programm, I guess, so you may also put a timer field (something like timer = 0 which increments every act().. ) instead of Greenfoot.delay.
BingoWasHisNamo BingoWasHisNamo

2014/5/7

#
I just changed the while to if, but now the first object moves, and then the second moves, and then the first, and so on. It's a lot closer to what I need, though. EDIT: What do you mean by the timer?
Jonche Jonche

2014/5/7

#
This is just a field you increment every act(). In code it looks like this :
private int timer = 0;

public void act()
{
timer ++;
}
there you already have your timer : every act, it is going to have +1. In your method, you can, instead of putting the delay which stops the whole programm put a condition that your timer must be equal to 2 and if it is so, it sets the timer to 0 again. In code it looks like something like this :
if (timer == 2)
{
/** Do whatever you want**/
timer = 0;
}
you can replace the "Greenfoot.delay(2)" by this condition
BingoWasHisNamo BingoWasHisNamo

2014/5/7

#
Alright, thank you for the help, I'm testing it out right now, but I'm pretty sure it should fix the problem.
You need to login to post a reply.