Accessing the x and y coordinates of another entity


(Simon Edström Kawaji) #1

Hello, I am very new to flashpunk and need some help. I am trying to access the x coordinates of my Player entity from my enemy entity so that it will be able to follow the player. But when I do as the “Accessing Entities” ( Accessing Entities ) tutorial, I get this error.

TypeError: Error #1009: Cannot access a property or method of a null object reference. at entities::Enemy_1() at GameWorld/loadMap() at GameWorld() at Main()

Anyone know how to fix this issue? Here is the part of the code that creates the error:

In the enemy class

var player:Player = world.getInstance(“player”) as Player;

and in the update() function of the enemy

if (player){ if (player.x> x) { if (_xspeed < _MAXmovespeed && (_xspeed + _moveAccel) < _MAXmovespeed ) { _xspeed += _moveAccel; } else { _xspeed = _MAXmovespeed; } }

			if (player.x < x)
			{
				if (Math.abs(_xspeed) < _MAXmovespeed && (Math.abs(_xspeed) + _moveAccel) < _MAXmovespeed  )
				{
					_xspeed -= _moveAccel;
				}
				else
				{
				_xspeed = -_MAXmovespeed;
				}
			}
		}

(Jacob Albano) #2

The issue is that the call to getInstance() is done in your Enemy’s constructor, before it’s been added to the world; therefore the world variable is null. You should call it in the added() function instead.


(Simon Edström Kawaji) #3

Thanks! I managed to fix it


(Ultima2876) #4

In general it is always better to use the added() function for basic initialization stuff like that. The constructor should only be used for stuff that allocates memory:

//avoid variable initialisers. Keep them null or undefined!
private var myImage: Image;
private var myArray: Array;

//constructor
public function Constructor()
{
  x = 50;  //initialisation. Bad! Put this in added() or a separate function instead!

  myImage = new Image(blahblah); //allocates memory. Keep it in the constructor!
  graphic = myImage;  //initialisation. Bad! Put this in added() instead!

  myArray = new Array; //allocates memory. Keep it in the constructor!
}

public override function added(): void
{
  x = 50; //initialisation. Good!

  myImage = new Image(blahblah); //allocates memory... should be in the constructor.
  graphic = myImage;  //initialisation. Good!
}

This is good coding style as there is a logical separation between memory allocation and initialisation; it will make your code more predictable and easier to understand. It also helps massively with entity recycling, especially if you’re not already taking advantage of it. Slipping it in later is easy if you’ve kept all your initialisation stuff in check like this; if not you’re in for a world of hurt and subtle bugs.


Create implicit coercion error