您的位置:首页 > 移动开发 > Android开发

Android 冲撞检测

2013-11-29 23:20 134 查看
虽然应该不是最优的,但是是逻辑较简单的那种

逻辑是:检查物体的4个点是否有至少一个在另外一个物体里,有就相撞了。

//冲撞检测

public boolean collidesWith(Layer otherSprite) {

if (otherSprite == null) {

throw new NullPointerException();

}

// 可见物体才需要相撞

if (otherSprite.isVisible() && this.isVisible()){

float otherX = otherSprite.getX();

float otherY = otherSprite.getY();

float otherWidth = otherSprite.getWidth();

float otherHeight = otherSprite.getHeight();

float thisX = getX();

float thisY = getY();

float thisWidth = getWidth();

float thisHeight = getHeight();

//判断this物体的4个顶点坐标是否在Other里面,就为碰撞

boolean f1 = (thisX + thisWidth) > otherX && (thisX + thisWidth) < (otherX + otherWidth) && (thisY + thisHeight) > otherY && (thisY + thisHeight) < (otherY + otherHeight) ;

boolean f2 = thisX > otherX && thisX < (otherX + otherWidth) && (thisY + thisHeight) > otherY && (thisY + thisHeight) < (otherY + otherHeight);

boolean f3 = (thisX + thisWidth) > otherX && (thisX + thisWidth) < (otherX + otherWidth) && thisY > otherY && thisY < (otherY + otherHeight);

boolean f4 = thisX > otherX && thisX < (otherX + otherWidth) && thisY > otherY && thisY < (otherY + otherHeight);

if(f1||f2||f3||f4){

return true;

}

}

return false;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: