Skip to main content
Participating Frequently
October 30, 2015
Answered

Collision detect not working

  • October 30, 2015
  • 2 replies
  • 527 views

I have created a Class in code called Battery and am adding it inside a function named 'Clone'. Battery is derived from a base class with a filename of Components.as. Here's where I am adding battery inside a function named 'clone':

var ComponentRef:Class = getDefinitionByName("Battery") as Class;

  var instance:object = new ComponentRef();

  addChild(DisplayObject(instance));

  instance.x = 500;

  instance.y = 300;

  instance.compName = "Battery";

  instance.amperage = 20;

  instance.partNumber = "BA12345";

I also have a movie clip with an instance name of 'negativeProbe' that I add an event listener to:

negativeProbe.addEventListener(Event.ENTER_FRAME, detectedColl);

this brings me to the detectedColl function where I am trying to do the collision detection:

var battery:Battery = new Battery();

  if (battery.hitTestObject(negativeProbe)) {

  trace("Collision!!!");

Trace never registers a hit. I don't get an error, but no hit is ever registered. What am I doing wrong here?

This topic has been closed for replies.
Correct answer nezarov

Here you've added the object "instance" to the stage

  addChild(DisplayObject(instance));

but this object not added!

var battery:Battery = new Battery();

so you have an object in name "battery" but it's not on the stage and it'll never hit another object unless you add it.

2 replies

nezarovCorrect answer
Inspiring
October 30, 2015

Here you've added the object "instance" to the stage

  addChild(DisplayObject(instance));

but this object not added!

var battery:Battery = new Battery();

so you have an object in name "battery" but it's not on the stage and it'll never hit another object unless you add it.

Participating Frequently
October 30, 2015

Ohhhh I think I see... I need to do an addChild on battery... I'll try that now.

Participating Frequently
October 30, 2015

That did work. Thank you again!

Inspiring
October 30, 2015

Try to change the variable name "instance" make it "battery"

or change the "battery" in if statement to "instance":

if (instance.hitTestObject(negativeProbe)) {

  trace("Collision!!!");

}

Participating Frequently
October 30, 2015

If I change instance to Battery I get this error:

Access of possibly undefined property x through a reference with static type Class.


If I change battery in the if statement to instance I get an error saying instance wasn't found or referenced, so I added 'instance' to the previous line:


var instance:Battery = new Battery();

  if (instance.hitTestObject(negativeProbe)) {


No error but still doesn't detect a collision. I'm stumped on this one. :\