新闻正文

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

来源:JAVA天堂  JAVA学习者  2007-5-14 02:39:27 网友评论 0 条 字体:[ ] ~我要投稿!

  在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;
  }
  
  这样速度会快很多。对于有透明背景的图片,我们可以围绕非透明部分多设立几个矩形区进行碰撞检测。

收藏到ViVi   收藏此页到365Key
上一篇:J2ME综合:如何在MIDP中实现图片放缩
下一篇:用NetBeans平台开发J2ME游戏实例讲解3
用户名:新注册) 密码: 匿名评论 [所有评论]
评论内容:不能超过250字,需审核后才会公布,请自觉遵守互联网相关政策法规。
本栏搜索
  • Google
   网站首页 -  网站地图 -  技术学习 -  网站投稿 -  帮助中心
Copyright 2003-2008 www.javah.net All Rights Reserved
2008 如果你喜欢本站 请收藏本站 并推荐给你的朋友一起分享