MIDP1.0中的碰撞检测

来源:互联网 发布:最短路径 算法 c# 编辑:程序博客网 时间:2024/05/10 08:25
 

正文



在MIDP1.0中,我们不能像MIDP2.0中的Sprite类一样有很方便的碰撞函数可以使用,我们只能自己来写代码实现。常见的碰撞检测的方式是基于矩形的碰撞,因为我们的图片都是矩形的。检测矩形碰撞的一种方式是看一个矩形的4个角是否进入另一个矩形内。假如我们有一个Actor类,也就是我们的一个自定义的类似于精灵类吧,那么我们可以给他定义一个这样的方法:
  1.  
  2. /**
  3. * 检测一个特定点是否进入一个Actor内
  4. * @param px 特定点的x坐标.
  5. * @param py 特定点的y坐标
  6. * @return  如果特定点进入Actor范围内,那么返回true,否则为false;
  7. */
  8. public boolean isCollidingWith(int px, int py)
  9. {
  10.   if (px >= getX() && px <= (getX() + getActorWidth()) &&
  11.        py >= getY() && py <= (getY() + getActorHeight()) )
  12.        return true;
  13.   return false;
  14.  
  15. /**
  16. * 检测一个Actor对象是否碰上了当前的Actor对象。
  17. * @param another 另一个Actor对象
  18. * @return 如果another和当前对象发生碰撞,则返回true,否则为false.
  19. */
  20. public boolean isCollidingWith(Actor another)
  21. {
  22.   // check if any of our corners lie inside the other actor's
  23.   // bounding rectangle
  24.   if (isCollidingWith(another.getX(), another.getY()) ||
  25.         isCollidingWith(another.getX() + another.getActorWidth(), another.getY()) ||
  26.         isCollidingWith(another.getX(), another.getY() + another.getActorHeight()) ||
  27.         isCollidingWith(another.getX() + another.getActorWidth(),
  28.                                   another.getY()+ another.getActorHeight()))
  29.         return true;
  30.   else
  31.         return false;
  32. }
  33.  


关于矩形碰撞检测,还有一个更简单的方式就是判断一个矩形的4条边是否在另一个矩形的4条边之外。因此我们可以写一个更加通用快速的简单的碰撞方法:


  1.  
  2. /**
  3.      * 较为通用的矩形碰撞检测方法
  4.      * @param ax a矩形左上角x坐标
  5.      * @param ay a矩形左上角y坐标
  6.      * @param aw a矩形宽度
  7.      * @param ah a矩形高度
  8.      * @param bx b矩形左上角x坐标
  9.      * @param by b矩形左上角y坐标
  10.      * @param bw b矩形宽度
  11.      * @param bh b矩形高度
  12.      * @return
  13.      */
  14.     public static final boolean isIntersectingRect(int ax, int ay, int aw,
  15.             int ah, int bx, int by, int bw, int bh) {
  16.         if (by + bh < ay || // is the bottom of b above the top of a?
  17.                 by > ay + ah || // is the top of b below bottom of a?
  18.                 bx + bw < ax || // is the right of b to the left of a?
  19.                 bx > ax + aw) // is the left of b to the right of a?
  20.             return false;
  21.  
  22.         return true;
  23.     }
  24.  
  25.  


这样速度会快很多。对于有透明背景的图片,我们可以围绕非透明部分多设立几个矩形区进行碰撞检测。