Reputation: 424
I have several balls each that are associated to a fruit. I want it so that when someone drags the ball onto the associated fruit it will call an action (In this case trace 'hit fruit') if not then do something else. At the moment it's not detecting this.
I've found that I can add an even listener to the stage to detect when this is done, but the problem is I have multiple balls, each with multiple fruits. Can anyone tell me how I go about doing this.
I am from a PHP/Javascript background and am just a beginner when it comes to AS3
ball1.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
ball1.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
function mouseUpHandler(e:MouseEvent):void {
var obj = e.target;
if (e.target.hitTestObject("fruit1")) {
trace('hit fruit1');
} else {
trace('Not hit fruit');
}
obj.stopDrag();
}
Upvotes: 0
Views: 2158
Reputation: 893
You can use an array to store all of the fruit and use a loop to test whichever ball is being dragged and dropped:
var fruitArray:Array = new Array();
fruitArray.push(fruit1);
fruitArray.push(fruit2);
fruitArray.push(fruit3);
function onMouseUp(e:MouseEvent) : void
{
for(var j=0; j<fruitArray.length; j++) { // Every piece of fruit is tested..
if(e.target.hitTestObject(fruitArray[j])) { // ..against the ball being dragged
trace("hit fruit:", fruitArray[j]);
}
}
}
You would need to use a similar for loop system to add the event listeners to the balls to begin with, and you can play with splitting the fruits into smaller arrays of different types, and only checking a ball against a particular fruit array.
Upvotes: 1