Android 冲撞检测

虽然应该不是最优的,但是是逻辑较简单的那种

 

逻辑是:检查物体的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;
 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值