I’ve been developing a video gamish thing in AS3. I have an array to draw a game field that contains road, fire, finish gate etc. Then, I add a MovieClip that is controled via mouse by player and try to check collisions with road MovieClip.
However, I does not work… It never traces “IN”. I couldn’t find any error in my code -But you never be sure…
Could you give a hand to solve this problem?
Thank y’all!
Here is the code:
Declarations:
public class Player extends MovieClip
{
public var player:MovieClip;
public var road:MovieClip;
public var finish:MovieClip;
public var fire:MovieClip;
public var sting:MovieClip;
public var map:Array = new Array();
Array initialization:
/* 1 ROAD
* 2 FINISH
* 3 FIRE
* 4 STRING
*/
public function Player():void
{
map = [ [ 1, 1, 3, 3, 3, 3, 3, 3, 1, 1 ],
[ 1, 1, 3, 4, 4, 4, 4, 3, 1, 1 ],
[ 1, 1, 3, 4, 4, 4, 4, 3, 1, 1 ],
[ 1, 1, 3, 3, 3, 3, 3, 3, 1, 1 ],
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 2 ],
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 2 ],
[ 1, 1, 3, 3, 3, 3, 3, 3, 1, 1 ],
[ 1, 1, 3, 4, 4, 4, 4, 3, 1, 1 ],
[ 1, 1, 3, 4, 4, 4, 4, 3, 1, 1 ],
[ 1, 1, 3, 3, 3, 3, 3, 3, 1, 1 ]
];
// 10 x 10 array
Adding hitTest function:
addEventListener( Event.ENTER_FRAME, playerHitTest );
And hitTest function:
public function playerHitTest( e:Event ):void
{
if ( player.hitTestObject( road ) )
{
trace("IN");
}
}
PS: If I make the condition !player.hitTestObject( road ), it always traces “IN”.
Thanks again!
There’s not enough code here to see exactly what’s going on but it’s obvious that the hitTest will fail because you are only checking against one road object, but according to your map array there should be many road objects.
You will need an array to store the road objects:
Wherever you create the road objects you should also be inserting them into this array:
Then when you perform the hitTest you must loop through the entire array and check each road object for a collision: