views:

175

answers:

2

I'm using Adobe Flash CS4. The language is Action Script 3

In my library I have 2 items:

  • player
  • wall

the player object is already functioning correctly with moving him around. Now when I place multiple wall objects into the stage (wall = 32x32 px) I want to prevent the player from moving when he walks into a wall.

I've tried giving all the walls the same instance name and just check for a collision with that object but when I do that the collision only works for 1 of the walls.

I could give all the instances of wall a different collision script but this is way to time consuming, is there another way to globally define the wall as solid for the player?

Thanks in advance!

A: 

Remember that any movieclip is an instance of a MovieClip class. By giving all the instances the same name you are effectivly doing this:

var myClip:MovieClip = new MovieClip();
myClip = new MovieClip();

myClip <-- will always refer to the later movieclip since thats what it is now referenced to.

To solve your problem you would most likely create a class which contains a collection (most likely an Array). You will add a reference to each MovieClip into this Array (simply by pushing in the MovieClips). Then you would have a function that is called either each frame or each time the character moves that loops through this array checking to see if the wall hits the player and if it does returns true that this has occured or false if it has not.

Allan
+1  A: 

Your best bet would be to put all the wall instances in one parent movie clip and check the player instance for collision with it.

Or you can loop through all the wall instances and check separately. Might sound wasteful to you but that way you can add some optimizations to your collision detection routine. For example, why check for collision with the left wall if the player is in the right part of the screen.

Or you can use math to check for collisions and avoid Flash's built-in routine whatsoever. Might sound like even more work but seeing how flawed it is (limited by frame-rate, etc.), I would go that way -- if the game dynamics allows it, of course.

kaloyan
Your first solution would not work, hit testing on a Sprite is not per pixel but rather bounding box so you would end up hit testing on a box that's maximum boundary comprises all the sub movie clips. Therefore it will pretty much always return true. You could however raster the movieclip to a bitmap and then examine the alpha values of the pixels relative to the coordinate of the player.
Allan
There are solutions to this: http://www.tink.ws/blog/as-30-hittest/
kaloyan