站内搜索: 请输入搜索关键词

当前页面: 开发资料首页J2ME 专题关于J2ME――MIDP1.0中的碰撞检测

关于J2ME――MIDP1.0中的碰撞检测

摘要: 关于J2ME――MIDP1.0中的碰撞检测
<td style="width:130px;height:130px;padding-bottom:10px;"> ad </td></tr> </table
  在MIDP1.0中,我们不能像MIDP2.0中的Sprite类一样有很方便的碰撞函数可以使用,我们只能自己来写代码实现。常见的碰撞检测的方式是基于矩形的碰撞,因为我们的图片都是矩形的。检测矩形碰撞的一种方式是看一个矩形的4个角是否进入另一个矩形内。假如我们有一个Actor类,也就是我们的一个自定义的类似于精灵类吧,那么我们可以给他定义一个这样的方法:
  
  /**
  * 检测一个特定点是否进入一个Actor内
  * @param px 特定点的x坐标.
  * @param py 特定点的y坐标
  * @return 如果特定点进入Actor范围内,那么返回true,否则为false;
  */
  public boolean isCollidingWith(int px, int py)
  {
  if (px >= getX() && px <= (getX() + getActorWidth()) &&
  py >= getY() && py <= (getY() + getActorHeight()) )
  return true;
  return false;
  }
  
  /**
  * 检测一个Actor对象是否碰上了当前的Actor对象。
  * @param another 另一个Actor对象
  * @return 如果another和当前对象发生碰撞,则返回true,否则为false.
  */
  public boolean isCollidingWith(Actor another)
  {
  // check if any of our corners lie inside the other actor's
  // bounding rectangle
  if (isCollidingWith(another.getX(), another.getY()) ||
  isCollidingWith(another.getX() + another.getActorWidth(), another.getY()) ||
  isCollidingWith(another.getX(), another.getY() + another.getActorHeight()) ||
  isCollidingWith(another.getX() + another.getActorWidth(),
  another.getY()+ another.getActorHeight()))
  return true;
  else
  return false;
  }
  
  关于矩形碰撞检测,还有一个更简单的方式就是判断一个矩形的4条边是否在另一个矩形的4条边之外。因此我们可以写一个更加通用快速的简单的碰撞方法:
  
  /**
  * 较为通用的矩形碰撞检测方法
  * @param ax a矩形左上角x坐标
  * @param ay a矩形左上角y坐标
  * @param aw a矩形宽度
  * @param ah a矩形高度
  * @param bx b矩形左上角x坐标
  * @param by b矩形左上角y坐标
  * @param bw b矩形宽度
  * @param bh b矩形高度
  * @return
  */
  public static final boolean isIntersectingRect(int ax, int ay, int aw,
  int ah, int bx, int by, int bw, int bh) {
  if (by + bh < ay || // is the bottom of b above the top of a?
  by > ay + ah || // is the top of b below bottom of a?
  bx + bw < ax || // is the right of b to the left of a?
  bx > ax + aw) // is the left of b to the right of a?
  return false;
  
  return true;
  }
  
  这样速度会快很多。对于有透明背景的图片,我们可以围绕非透明部分多设立几个矩形区进行碰撞检测。

↑返回目录
前一篇: J2ME综合:如何在MIDP中实现图片放缩
后一篇: 用NetBeans平台开发J2ME游戏实例讲解3