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

2012/5/23

getObjectsInRange help?

PiercingGoblin PiercingGoblin

2012/5/23

#
I want to have it so when the object (redportal_ball) gets within 10 pixels of a wall that it will create a portal (redportal). Whenever I use the following code, no matter how small I make the radius for getObjectsInRange() it always creates the portal right away (as soon as it is shot even though it is not within range of a wall).
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.lang.*;

/**
 * Write a description of class redportal_ball here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class redportal_ball extends Actor
{
    /**
     * Act - do whatever the redportal_ball wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    
    public GameWorld board = (GameWorld) getWorld();
    public boolean created = false;
    public MouseInfo mouse = Greenfoot.getMouseInfo();
    
    public void act() 
    { 
        GameWorld board = (GameWorld) getWorld();
        move(20);
        Actor wall;
        
        if (!created)   
        {
            setRotation(findangle()); //Rotates the ball ONLY ONCE after it's been created.
        }

        if ((getObjectsInRange(5, wall.class) != null))
        {
            if (getObjectsInRange(1000, redportal.class).size() > 0)
            {
                board.removeObjects(board.getObjects(redportal.class));
            }
            redportal portal = new redportal();
            board.addObject(portal, this.getX(), this.getY());
            board.removeObject(this);
        }
        
        created = true;
    }
           
    public int findangle()
    {
        int mouseX = mouse.getX();
        int mouseY = mouse.getY();
        double deltaX = (mouseX  - this.getX());    //Change in X
        double deltaY = (mouseY - this.getY());     //Change in Y
        double angle = Math.atan2(deltaY, deltaX);    //Finds angle with deltaX and deltaY
        angle = Math.toDegrees(angle);
        int angle_return = (int)(angle);
        System.out.println(angle_return + " " + angle + " " + mouseX + " " + mouseY);
        return angle_return;
    }
}
Builderboy2005 Builderboy2005

2012/5/23

#
The command getObjectsInRange() returns a List object that is never null, but might have a size of zero. Therefore, instead of checking to see if the list is null, you should check to see if it has a size of zero, using the .size() method :)
You need to login to post a reply.