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

2015/4/11

Console not appearing?

h123n h123n

2015/4/11

#
Hi, I have a class that figures out the X and Y distance between itself and the target(Toby). I want it to print the distance overtime the followPlayer method is called. Problem is, the console will not come up with the distance. I think it is more a problem with my code because it came up on another class. Here is my code:
import greenfoot.*;

/**
 * Write a description of class NPCSensor here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class NPCSensor extends NPC
{
    private Toby toby;
    public int distancetargetx = 10;
    public int distancetargety = 10;
    /**
     * Act - do whatever the NPCSensor wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        if (toby != null)
        {
        followPlayer();
        System.out.println("x="+distancetargetx+" y="+distancetargety);
       }
    }
        public void followPlayer()
    {
        //find distance in X
        if (toby.getGlobalX() > this.getGlobalX())
        {
            distancetargetx = toby.getGlobalX() - this.getGlobalX();
        }
        else
        {
            distancetargetx = this.getGlobalX() - toby.getGlobalX();
        }
        //find distance in Y
        if (toby.getGlobalY() > this.getGlobalY())
        {
            distancetargety = toby.getGlobalY() - this.getGlobalY();
        }
        else
        {
            distancetargety = this.getGlobalY() - toby.getGlobalY();
        }        
    }
}
Help is very appreciated.
Super_Hippo Super_Hippo

2015/4/11

#
There is never a Toby object assigned to the 'toby' variable, so it is 'null' and the condition in the act method is false. Add the following at the end of the act method:
else toby = (Toby) getWorld().getObjects(Toby.class).get(0);
h123n h123n

2015/4/11

#
thanks! it works perfect now!
You need to login to post a reply.