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

2020/11/17

Move multiple Objects simultaneously

Mousekip Mousekip

2020/11/17

#
Below are two classes, which just move to the right. They don´t move simultaneously though, but rather move one, wait until the other one has moved and then move again. Is there a way to have them both move at once? I have heard there´s something called hyperthreading, which enables this. Is that true and if it is how do I implement it? First class:
import greenfoot.*;
public class First extends Actor
{
    public void act() 
    {
        move(5);
        Greenfoot.delay(1);
    }    
}
Second class:
import greenfoot.*;
public class Second extends Actor
{
    public void act() 
    {
        move(5);
        Greenfoot.delay(1);
    }    
}
danpost danpost

2020/11/17

#
Remove the "delay"s. If you want them to only move every other act frame, then add an int timer (to be an act counter) to both classes. The act methods can then control them. The code would look like this:
private int timer;

public void act()
{
    timer = (timer+1)%2;
    if (timer == 0) move(5);
}
danpost danpost

2020/11/17

#
To ensure they move at the same time, apply the same timer to all actors to be synched. The timer can be in your world class:
public static int timer;
run by the world:
public void act()
{
    timer = (timer+1)%2;
}
and used by the actors:
public void act()
{
    if (MyWorld.timer == 0) move(5);
}
Mousekip Mousekip

2020/11/18

#
Ok thank you. Seems to work perfectly
You need to login to post a reply.