Skip to main content
August 21, 2009
Question

Help with simple collision/hitTest

  • August 21, 2009
  • 2 replies
  • 665 views

Hi there,


Im currently making a simple car game. I want to constrain my car within the boundaries of the track, but cannot find the right code for a simple collision detection / hit test that will stop the car from going outside the track object.

The track is made up of two layers - the top layer is purely for aesthetics and the underlying layer is basically a solid block which has had a track carved out of it using the eraser tool, then converted into a symbol with the name "groundMC".

The car is named "carMC" and has also been converted into a symbol and exported for action script 2.0

Does anyone know the correct code to keep the car inside the block (groundMC)?

Many thanks

This topic has been closed for replies.

2 replies

k_bitgood
Inspiring
August 21, 2009

Try this code:

if(groundMC.hitTest(carMC._x, carMC._y, true){

     trace("Car is outside track");

}

You might need to put it in an onEnterFrame function so that it continually checks.

The "true" at the end is the value for the shapeFlag boolean parameter.

Check out this page for details on how this works:  http://www.adobe.com/support/flash/action_scripts/actionscript_dictionary/actionscript_dictionary534.html

Hope this helps

kglad
Community Expert
Community Expert
August 21, 2009

you'll need to use a shape-based hittest if you want to use a hittest for that.  check gskinner's hitdetection.

August 24, 2009

Hi,

This was a very helpful reply as i believe this is the sort of hit test i was looking for.

However, do you know how i could make the game jump to the 'game over - start again?' screen once the car has touched the side of the track and blown up? Im guessing i will need to use the 'gotoAndPlay' function. But what would i have to do to make it realize it needs to go to that screen after the hit test has replied true?

kglad
Community Expert
Community Expert
August 24, 2009

his method returns null if there's no hit and returns a rectangle if there is one.  so apply the hitdetection between the car and track:

if(CollisionDetection.checkForCollision(carMC, trackMC, 120)){

//restart

}