Question

So, I have this code:

public function hitTest1(e:Event) : void
    {
        if (hitTestObject(target.hit)){
        gotoAndStop(2,"Scene 1");
        removeEventListener(Event.ENTER_FRAME, hitTest1);

        }
    }

In which target is the object that is going to be hit, and hit is a symbol in a layer over said object. When I run the code I get this error over an over again.

TypeError: Error #1009: Cannot access a property or method of a null object reference.
at com.Mass.basics1::Asteroid/hitTest1()

NOTE: Asteroid is the .as file that contains all of this code.

Here is the rest of the code for reference :

package com.Mass.basics1
{

import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;

public class Asteroid extends MovieClip
{
    public var target:Cosmo;
    private var stageRef:Stage;
    private var speed:Number;
    // public var ourAsteroid:Asteroid = new Asteroid(stage);


    public function Asteroid(stageRef:Stage)
    {


        this.stageRef = stageRef;
        setupAsteroid(true);

        addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
        addEventListener(Event.ENTER_FRAME, hitTest1);

    }

    public function hitTest1(e:Event):void
    {
        if (hitTestObject(target.hit))
        {
            gotoAndStop(2,"Scene 1");
            removeEventListener(Event.ENTER_FRAME, hitTest1);

        }
    }


    public function setupAsteroid(randomizeY:Boolean = false):void
    {
        //inline conditional, looks complicated but it's not.
        y = randomizeY ? Math.random() * stageRef.stageHeight:0;
        x = Math.random() * stageRef.stageWidth;

        rotation = Math.random() * 360;
        scaleX = Math.random();
        scaleY = scaleX;

        speed = 20 + Math.random() * 10;
    }

    public function loop(e:Event):void
    {
        y +=  speed;

        if (y > stageRef.stageHeight)
        {
            setupAsteroid();

        }


    }

}
}
Was it helpful?

Solution

So, where is the "target" object? You're just declaring a variable, but not creating the object or setting a reference. It's a public variable, so maybe you are setting a reference somewhere else? In that case, make sure you assign a reference before you are calling hitTest1 function...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top