Laser Collision Checking
(NOTE: This tutorial builds upon a previous tutorial "Game Gun", which in turn builds upon the previous tutorial "Detect Mouse Angle". To understand how it all works, you have to do the tutorials in order. In this tutorial I will only cover how to detect if our laser shot is hitting the user's ship. 
(This is all part of a soon-to-be-released game I am working on.)

Move your mouse around the black window below:



Actual Flash code is in green.

This is all the new code for detecting the Laser hitting the user's ship:
It lives in its own frame inside the "laser shot" object. 

Comment: ----------------------------------------------
Comment: Did I hit something yet?
Comment: ----------------------------------------------
Comment: SIMPLE collision detection: is the laser inside the rectangle defined by the ship's size?
Comment: NOTE: shipx and shipy are the center point of the ship. If your ship's center point (the little "plus sign" that exists in every movie clip) is not at the center of the ship, this calculation will not work!

Everything we can find out about the user's ship:

Set Variable: "shipx" = GetProperty("../ship",_x)
Set Variable: "shipy" = GetProperty("../ship",_y)
Set Variable: "shipwidth" = GetProperty("../ship",_width)
Set Variable: "shipheight" = GetProperty("../ship",_height)
Set Variable: "shiptop" = shipy-(shipheight/2)
Set Variable: "shipbottom" = shipy+(shipheight/2)
Set Variable: "shipleft" = shipx-(shipwidth/2)
Set Variable: "shipright" = shipx+(shipwidth/2)
Comment: NOTE: I went overkill on the variable definition -- you'll probably be able to reduce the amount of definitions in your error checking. I just did this to make it obvious for this tutorial.

OK that was easy, right? We can find out the exact numbers of the ship's left, right, top, and bottom sides using some simple algebra. Using them, we see if the laser shot's (x/y) values are inside that area. NOTE: this refers to the object center point. THE PLUS SIGN. You will notice on the laser the center point is NOT in the middle of it, but on the front edge. So the code checks if the front edge of this laser is inside the ship's boundaries. (NOTE ALSO: the Game Gun rotates the laser shot so that the "plus" sign travels first.) You could easily ignore these finer details and your laser detection would make no noticeable difference anyway. I just like to be precise.

Comment: ----------------------------------------------
Comment: now check if we hit anything
Comment: ----------------------------------------------
If (my_x>(shipleft) and my_x<(shipright)) and (my_y>(shiptop) and my_y<(shipbottom))

That's it. We must have hit something if the laser is in between the ship's boundaries.

Begin Tell Target ("../ship/hitdisplay")
Play
End Tell Target
End If

Just for show, I made a little movie clip that displays the word "HIT". It lives inside the ship object. It is called "hitdisplay".

by: