Activity 8: Collision Detection

Intent

Through completion of the tutorial students will be introduced to the code that detects the collision of objects. The hitTestPoint function tests a point location to see whether it is inside a display object. This function works best in games as the collision is detected when the shapes of the display objects intersect. The hitTestObject function function is related to the hitTestPoint function but it detects the collision when the bounding rectangles of the display objects intersect.

Students will also see the code needed to attach an instance to a mouse and two if-else statements.

Criteria

  • Completion of the tutorial.
  • Extension of the collision detection code to include the triggering of other events.

Task

  1. Open Flash. Choose ActionScript 3.0. The size and FPS may be set to the default.
  2. Select the text tool and make two text boxes. In Properties, name one messageText1 and the other messageTest2. Both instances should be set at Classic Text, Dynamic Text. The anti-alias should be set to “Use device fonts.”
  3. Make a crescent shape by making two circles that are the same size and overlapping them. With both shapes selected go Modify/Combine Objects/Punch.

  4. Convert the crescent to a symbol by  going to Modify/Convert to Symbol and naming it Crescent
  5. Name the instance crescent in the Properties bar.
  6. Make a star using the Polystar tool. Be sure to change the tool settings so that you create a star shape.
  7. Convert the star to a symbol by going to Modify/Convert to Symbol and naming it Star.
  8. Name the instance starin the Properties bar.
  9. In the first keyframe add the following code in actions.
    addEventListener(Event.ENTER_FRAME, checkCollision);
    function checkCollision(event:Event) {

    // check the cursor location against the crescent
    if (crescent.hitTestPoint(mouseX, mouseY, true)) {
    messageText1.text = “hitTestPoint: YES”;
    } else {
    messageText1.text = “hitTestPoint: NO”;
    }

    // move star with mouse
    star.x = mouseX;
    star.y = mouseY;

    // test star versus crescent
    if (star.hitTestObject(crescent)) {
    messageText2.text = “hitTestObject: YES”;
    } else {
    messageText2.text = “hitTestObject: NO”;
    }
    }

  10. Test the program. Note the difference between the hitTestPoint and hitTestObject functions.
  11. Alter the code so that the star moves with the mouse but the arrow mouse icon is nearer the centre.
  12. Alter the code so that when there is a collision occurs another event is triggered such as a sound playing or the colour of an object changing.
  13. Post your completed tutorial to your website for grading.