Reputation: 648
I have looked around at a few different threads and can't seem to find anything that works for me. I am fairly new to ActionScript, so this may be obvious. For practice, I am trying to make a simple game. In the game you can chop down trees to add to your 'wood' resource. Here is the tree class:
package
{
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.events.MouseEvent;
public class Tree extends Sprite
{
//Embed the gameObject image
[Embed(source="../images/tree.png")]
public var GameObjectImage:Class;
public var gameObjectImage:DisplayObject = new GameObjectImage();
public var gameObject:Sprite = new Sprite();
public function Tree()
{
gameObject.addChild(gameObjectImage);
this.addChild(gameObject);
}
}
}
Then, I create a function in the Main.as call 'createTree'
public function createTree (xPos:int, yPos:int):void
{
var treeName:Tree = new Tree();
treeName.x = xPos;
treeName.y = yPos;
treeName.addEventListener(MouseEvent.CLICK, chopWood);
stage.addChild(treeName);
}
And I have a function called 'chopWood' to remove the tree.
public function chopWood(e:MouseEvent):void
{
wood++;
stage.removeChild(e.relatedObject);
updateResources();
}
In the constructor, I add a tree.
createTree(100,100);
And it does add the tree at x:100 y:100. But the Click event doesn't work. If I manually add the tree (i.e. not through a function) and manually add the even listener, it works. I figure this is some sort of encapsulation issue, but I am not sure how to resolve it. Creating trees needs to be done through a function because the play will need to add trees at some point.
How can I get the click event to work on all of the trees that I add to the stage?
Upvotes: 1
Views: 78
Reputation: 10510
That seems like it should work. Does the chopWood method get called on click? Put a trace at the beginning of chopWood
to test that.
If chopWood
is being called, then I can see one strange thing. I am not too sure what e.relatedObject
is. I would think you would want e.currentTarget as Tree
. Also you can omit the "stage" in your stage.removeChild(e.relatedObject);
line. It should just add it to as a child of your Main class.
Upvotes: 2