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

2024/10/17

Respawn character

CowboyIggy CowboyIggy

2024/10/17

#
I want to make a character respawn after 5 seconds dead.
public boolean death()
    {
        if(isTouching(Trap.class))
        {
            World myWorld = getWorld();
            myWorld.removeObject(this);
            myWorld.addObject(this, myWorld.getWidth()/2,myWorld.getHeight()/5);
            
            return true;
        } 
        return false;
    }
I'm using this code, is there a way to make the character be added in the world 5 seconds after been removed? I've tried setLocation(-1000, -1000) + sleepFor(250), to send him away and make him wait but it didn't work as intended
danpost danpost

2024/10/17

#
CowboyIggy wrote...
I want to make a character respawn after 5 seconds dead. << Code Omitted >> I'm using this code, is there a way to make the character be added in the world 5 seconds after been removed?
One simple way to handle it is by creating a new type of Actor for the dead ones:
import greenfoot.*;

public class Coffin extends Actor
{
    private Actor deceased;
    int timer;
    
    public Coffin(Actor actor, int seconds) {
        World world = actor.getWorld();
        world.addObject(this, 0, 0);
        world.removeObject(actor);
        deceased = actor;
        timer = seconds*60;
        setImage((GreenfootImage)null);
    }
    
    public void act() {
        if (--timer == 0) {
            int w = getWorld().getWidth();
            int h = getWorld().getHeight();
            getWorld().addObject(deceased, w/2, h/2);
            getWorld().removeObject(this);
        }
    }
}
I've tried setLocation(-1000, -1000) + sleepFor(250), to send him away and make him wait but it didn't work as intended
Unless your world is unbounded (which, currently, it is not), you will not be able to place objects (totally) outside the world. See documentation of World class constructors. With the class above, your death method would be something like this:
public boolean death() {
    if (isTouching(Trap.class)) {
        new Coffin(this, 5);
        return true;
    }
    return false;
}
None of this was not tested, but should world. If not, it should lead you to a solution.
You need to login to post a reply.