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

2020/5/3

How to make an object hover directly over another.

OGTacl OGTacl

2020/5/3

#
In my current project i have an actor (called Runner) which cannot cannot move through walls. i want another actor that covers the whole screen except a circle (called Cover) to stay directly above the other. i used the same movement code so they will both move in sync. The only problem is when the Runner hits a wall the cover continues to move. How do i get the Runner's location and sync it with the Cover's location? my movement for the runner is:
public void slideAround()
    {
        int x = getX();
        int y = getY();
        if(Greenfoot.isKeyDown("right"))
        {
            setRotation(90);
            setLocation(x + speed, y);
            if(hitWalls())
            {
                setLocation(x - speed, y);
            }
        }
        if(Greenfoot.isKeyDown("left"))
        {
            setRotation(270);
            setLocation(x - speed, y);
            if(hitWalls())
            {
                setLocation(x + speed, y);
            }
        }
        if(Greenfoot.isKeyDown("up"))
        {
            setRotation(0);
            setLocation(x , y - speed);
            if(hitWalls())
            {
                setLocation(x , y + speed);
            }
        }
        if(Greenfoot.isKeyDown("down"))
        {
            setRotation(180);
            setLocation(x , y + speed);
            if(hitWalls())
            {
                setLocation(x , y - speed);
            }
        }
    }
OGTacl OGTacl

2020/5/3

#
Since the cover takes up the whole World screen i cant use the same "hitWalls" code. And i also have a speed boost which doesnt work with the Cover, so the location would be best.
danpost danpost

2020/5/3

#
OGTacl wrote...
Since the cover takes up the whole World screen i cant use the same "hitWalls" code. And i also have a speed boost which doesnt work with the Cover, so the location would be best.
If the movement of the cover is dependent on the player's movement, maybe the player should move the cover instead of it trying to move itself.
OGTacl OGTacl

2020/5/3

#
Okay, whats the best way to do that?
danpost danpost

2020/5/3

#
OGTacl wrote...
Okay, whats the best way to do that?
Maybe not the best, but the easiest might be:
java.util.List covers = getWorld().getObjects(Cover.class); // list of Cover objects in world
if ( ! covers.isEmpty()) // list contains at least one object
{
    Actor cover = (Actor)covers.get(0); // get object from list
    cover.setLocation(getX(), getY());
}
This can either be put at the end of the slideAround method or put in a separate method called immediately after calling the slideAround method in the act method.
OGTacl OGTacl

2020/5/3

#
Works great. Thanks.
You need to login to post a reply.