Body In midp1.0, we cannot use collision functions as easily as the sprite class in midp2.0. We can only write code for implementation by ourselves. The common collision detection method is rectangle-based collision, because our images are rectangular. One way to detect rectangular collision is to check whether the four corners of a rectangle are inside the other. Assume that we have an actor class, which is a custom kind similar to the genie class. Then we can define a method like this:
-
- /**
- * Checks whether a specific vertex enters an actor.
- * @ Param px x coordinate of a specific point.
- * @ Param py y coordinate of a specific point
- * @ Return if a specific vertex is in the actor range, true is returned; otherwise, false is returned;
- */
- Public BooleanIscolsponingwith (IntPx,IntPY)
- {
- If(PX> = getx () & PX <= (getx () + getactorwidth ())&&
- PY> = Gety () & py <= (Gety () + getactorheight ()))
- Return True;
- Return False;
- }
-
- /**
- * Checks whether an actor object meets the current actor object.
- * @ Param another actor object
- * @ Return if another is in conflict with the current object, true is returned; otherwise, false is returned.
- */
- Public BooleanIscolpolicingwith (actor another)
- {
- // Check if any of our corners lie inside the other actor's
- // Bounding rectangle
- If(Iscollidingwith (another. getx (), another. Gety () |
- Iscolsponingwith (another. getx () + another. getactorwidth (), another. Gety () |
- Iscolsponingwith (another. getx (), another. Gety () + another. getactorheight () |
- Iscolsponingwith (another. getx () + another. getactorwidth (),
- Another. Gety () + another. getactorheight ()))
- Return True;
- Else
- Return False;
- }
-
For rectangular collision detection, another easier way is to determine whether the four sides of a rectangle are out of the four sides of the other rectangle. Therefore, we can write a more general and fast simple collision method:
-
- /**
- * More common rectangular Collision Detection Methods
- * @ Param ax a coordinate X in the upper left corner of the rectangle
- * @ Param ay y coordinate in the upper left corner of the rectangle
- * @ Param aw a rectangle width
- * @ Param ah a rectangular height
- * @ Param BX B x coordinate in the upper left corner of the rectangle
- * @ Param by B y coordinate in the upper left corner of the rectangle
- * @ Param bw B rectangle width
- * @ Param bh B rectangular height
- * @ Return
- */
- Public Static Final BooleanIsintersectingrect (IntAx,IntAy,IntAw,
- IntAh,IntBX,IntBy,IntBW,IntBH ){
- If(By + bH <ay |// Is the bottom of B abve the top of?
- By> Ay + Ah |// Is the top of B below bottom of?
- BX + BW <ax |// Is the right of B to the left of?
- BX> AX + aw)// Is the left of B to the right of?
- Return False;
-
- Return True;
- }
-
-
This is much faster. For images with a transparent background, we can set up multiple Rectangular areas around the non-transparent part for collision detection. |