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

2018/1/5

Actor is out of world when Bullet hits, can somebody help?

Dimako21 Dimako21

2018/1/5

#
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Asteroid1 here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Asteroid1 extends Actor
{
    World MyWorld = getWorld();
    private int rotation = 0;
    private int speed = 0;
    public Asteroid1()
    {
        rotation = (int) (Math.random() * 359);
        speed = (int) (1+ Math.random() * 2);
        setRotation(rotation);
    }
    public void act() 
    {
        if(getWorld() == null) {return;}
        hitDetection() ;
        move(speed);
        wrapEdge();
    }
    public String currentEdge()
    {
        int y = getY();
        int x = getX();
        World myWorld = getWorld();
        if (y == 0 )
        {
            return "top";
        }
        else if ( x==0 )
        {
            return "left";
        }
        else if (y == myWorld.getHeight() - 1)  //   -1 because it would not find it otherwise
        {
            return "bottom";
        }
        else if ( x == myWorld.getWidth() - 1)   //   -1 because it would not find it otherwise
        {
            return "right";
        }
        else 
        {
            return null;
        }
    }

    public void wrapEdge()
    {
        String currentEdge = currentEdge();
        int x = getX();
        int y = getY();
        World myWorld = getWorld();
        if(currentEdge == "top")
        {
            setLocation(x, myWorld.getHeight() - 1);
        }
        else if(currentEdge == "left")
        {
            setLocation(myWorld.getWidth() - 1,y);
        }
        else if(currentEdge == "bottom")
        {
            setLocation(x, 0);
        }
        else if(currentEdge == "right")
        {
            setLocation(0, y);
        }
    }

    public void hitDetection() 
    {

        Actor b = getOneIntersectingObject(Bullet.class);  

        if(b != null)  
        {  
            getWorld().removeObject(this);   
        }  
    }

    
}
danpost danpost

2018/1/5

#
Remove line 22 and move line 23 down two lines. The act method is only called when the actor is in the active world and you should check collision detection after moving (also, because it may remove the actor from the world, you cannot do things like moving or wrapping within the world after)
Dimako21 Dimako21

2018/1/5

#
Thank you very much! It works flawlessly now.
You need to login to post a reply.