Welcome to WebmasterWorld Guest from 188.8.131.52
Forum Moderators: not2easy
Imagine a Lander type game - what would be the best way to do such collision detection?
By having the 'landscape' as a Movie Clip with transparent background you can use landscape.hitTest(object._x, object._y, true). This takes an explicit x-y coord and returns true if it falls on a part of the landscape that isn't transparent. Ideal for Lander;)
If you want to try the effect it's pretty easy to set it up.
- Create a movie clip and draw some abstract shape leaving the background 'empty' (transparent). Place this on the root timeline. Name the instance of this movie clip something eg: 'landscape'.
- If you were making a game you'd probably have some sprite that you wanted to test for collisions with the background, but for brevity we'll just use the mouse. Principle's the same.
- To add some output (so you can see when there is a collision) add a dynamic textbox called 'outputField' to the root timeline.
- In the ActionScript Panel for your landscape movie clip instance insert the following script:
if (this.hitTest(_root._xmouse, _root._ymouse, true))
_root.outputField = 'hit';
_root.outputField = '';
- Test your movie - you should see that when the mouse pointer is over a populated part of your movie clip your dynamic text box shows 'hit' and when it's not it should be blank.
A useful effect for anyone wanting to create 2D games etc
- To use this type of collision detection you have to specify an exact x-y coord in the hitTest function. However this throws up a question... What if my 'sprite' is bigger than a single pixel (which it's likely to be). Easy - in your if (hitTest statement here) test you need to add more hitTests as part of the if statement (OR) where each x-y coord represents a different corner of your 'sprite'. You'd use the getBounds(_root) method to let flash work this out for you - check the ActionScript dictionary for a full explanation of that method.
- also, if there's an error in the above let me know as I'm writing from memory - my copy of Flash is at home!