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

王朝java/jsp·作者佚名  2008-05-31
宽屏版  字体: |||超大  

在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;

}

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

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有