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

2016/2/8

Get enemy to follow player

Jadwaga111 Jadwaga111

2016/2/8

#
I want to have it so the player can move freely and the enemy follows by getting the x position and y position. I know i need to use turnTowards however whenever i try and set the position of the player in the enemy class i get a null pointer player code
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Tank here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Tank extends Actor
{
    /**
     * Act - do whatever the Tank wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        if(Greenfoot.isKeyDown("up"))
        {
            move(5);
        }
        if(Greenfoot.isKeyDown("down"))
        {
            move(-2);
        }
        if(Greenfoot.isKeyDown("right"))
        {
            turn(3);
        }
        if(Greenfoot.isKeyDown("left"))
        {
            turn(-3);
        }
    }    
}
enemy code
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class enemy here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class enemy extends Actor
{
    private Tank myTank;
    /**
     * Act - do whatever the enemy wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        move(2);
        turnTowards(myTank.getX(), myTank.getY());
    }    
}
danpost danpost

2016/2/8

#
Nowhere are you using the assignment operator on the 'myTank' field in the enemy class; and being the field is declared 'private', it cannot have been assigned any value elsewhere. So, of course, the object reference 'myTank' will contain a 'null' value. I do not even think you need to have the 'myTank' field in the enemy class. You could just use thi as our enemy class (change name of class from 'enemy' to 'Enemy', as it is conventional to start class names will a capital letter:
import greenfoot.*;

public class Enemy extends Actor
{
    public void act()
    {
        move(2);
        if (getWorld().getObjects(Tank.class).isEmpty()) return; // skips following if the tank is not in world
        Actor tank = (Actor)getWorld().getObjects(Tank.class).get(0); // gets reference to tank
        turnTowards(tank.getX(), tank.getY()); // turn toward tank
    }
}
You need to login to post a reply.