Dannyvegas1701
Dannyvegas1701

Reputation: 23

AS3: Cannot access a property or method of a null object reference (Despite removing the event listener)

I am programming a 2D side scrolling platformer in AS3. I have a camera which scrolls with the player, though remains at a fixed height.

import flash.events.Event;
import flash.geom.Rectangle;
stage.addEventListener(Event.ENTER_FRAME, camera);
function camera(evt:Event){
 root.scrollRect = new Rectangle(player.x - stage.stageWidth/2, camera1.y - stage.stageHeight/2, stage.stageWidth, stage.stageHeight);}

I have programmed a pit which, if the player falls in, will take the player to a game over screen on a separate frame. This function removes all of the event listeners from the frame.

stage.addEventListener(Event.ENTER_FRAME, walls);

function walls(e:Event){
if (player.hitTestObject(Pit1)){
    stage.removeEventListener(KeyboardEvent.KEY_DOWN, keydown);
    stage.removeEventListener(KeyboardEvent.KEY_UP, keyup);
    stage.removeEventListener(Event.ENTER_FRAME, movement);
    stage.removeEventListener(Event.ENTER_FRAME, walls);
    stage.removeEventListener(Event.ENTER_FRAME, camera);
    gotoAndPlay("GameOver");
    }
}

However I still receive TypeError #1009 for the camera when I am taken to the game over screen.

Upvotes: 0

Views: 131

Answers (1)

Jon Lucas
Jon Lucas

Reputation: 101

You should make a unique function that handles your enterframe events. You refresh your view and test your collisions within that unique function:

/**
 * Init function, called at the end.
 */
function init()
{
    stage.addEventListener(Event.ENTER_FRAME, enterFrameEventHandler);
}

/**
 * Function that updates your camera
 */
function updateCamera()
{
    root.scrollRect = new Rectangle(player.x - stage.stageWidth/2, camera1.y - stage.stageHeight/2, stage.stageWidth, stage.stageHeight);
}

/**
 * Function that test your collisions.
 */
function testCollision()
{
    if (player.hitTestObject(Pit1))
    {
        stage.removeEventListener(KeyboardEvent.KEY_DOWN, keydown);
        stage.removeEventListener(KeyboardEvent.KEY_UP, keyup);
        stage.removeEventListener(Event.ENTER_FRAME, enterFrameEventHandler);
        gotoAndPlay("GameOver");
    }
}

/**
 * Unique function that manages enterframe events
 */
function enterFrameEventHandler(e:Event)
{
    // update camera position 
    updateCamera();        

    // test collision
    testCollision();

    // etc.
}

init();

Upvotes: 1

Related Questions