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

2017/5/17

Actor won't disappear when it hits the edge of the screen

WhiteRoseAshes WhiteRoseAshes

2017/5/17

#
I'm trying to make an actor disappear when it hits the right edge of the screen. I wrote the code to do so but for some reason it is not disappearing when it hits the edge. Here's the code:
    public void act() 
    {
        int xpos=getX();
        if(xpos<600)
        {
            xpos = xpos +5;
            setLocation(xpos,getY());
            Actor rock = getOneIntersectingObject(Astroid.class);
            if(rock != null)
            {
                hit();
                getWorld().removeObject(rock);
                getWorld().removeObject(this);
            }
        }
        else if(xpos> 600)
        {
            getWorld().removeObject(this);
        }
    }    

    public void hit()
    {
        AstroidWorld World = (AstroidWorld) getWorld();
        Counter counter = World.getCounter();
        counter.increaseScore(10);
    }
Yehuda Yehuda

2017/5/18

#
Try changing line 16 to:
else if (getX() > getWorld().getWidth() - 1) // you can probably use 'xpos' instead of getX(), I think they'll return the same thing
danpost danpost

2017/5/18

#
The problem is the highest x-coordinate value that can be achieved in a world of width 600 is 599. So, your line 16 should be:
if (getX() == 599)
// or
if (getX() > 598)
@Yehuda, your suggestion still suffers the same issue.
Yehuda Yehuda

2017/5/18

#
danpost wrote...
your suggestion still suffers the same issue.
I didn't test it, and I haven't had to do this before (you can see by my scenarios that I have a different style of programs). I just thought that's what I remembered seeing other people do (I did assume that you can't actually have an x of the World width, but I didn't know how many pixels away from the border the actor stops).
WhiteRoseAshes WhiteRoseAshes

2017/5/18

#
If i do
if (getX() == 599)
I get an error whenever the shot hits an asteroid now. It states that the actor no longer exists in the world and if I do
else if(getX()==599)
the shot still will not disappear at the edge of the screen.
danpost danpost

2017/5/18

#
WhiteRoseAshes wrote...
I get an error whenever the shot hits an asteroid now.
Then try:
if (getWorld() != null && getX() == 599)
Yehuda Yehuda

2017/5/19

#
The problem is that the X is always less than 600 so doing 'else' will make that 'if' not run. The 'if' statements should not both be checking for the same area (599). You can use 'else' if you lower the value in the first 'if' statement.
You need to login to post a reply.