java 中飞机大战碰撞检测_飞机大战3--碰撞检测

碰撞检测

目标

了解碰撞检测方法碰撞实现

01. 了解碰撞检测方法

pygame 提供了 两个非常方便 的方法可以实现碰撞检测:

pygame.sprite.groupcollide()

两个精灵组 中 所有的精灵 的碰撞检测

groupcollide(group1, group2, dokill1, dokill2, collided = None) -> Sprite_dict

如果将 dokill 设置为 True,则 发生碰撞的精灵将被自动移除collided 参数是用于 计算碰撞的回调函数

如果没有指定,则每个精灵必须有一个 rect 属性

pygame.sprite.spritecollide()

判断 某个精灵 和 指定精灵组 中的精灵的碰撞

spritecollide(sprite, group, dokill, collided = None) -> Sprite_list

如果将 dokill 设置为 True,则 指定精灵组 中 发生碰撞的精灵将被自动移除collided 参数是用于 计算碰撞的回调函数

如果没有指定,则每个精灵必须有一个 rect 属性 返回 精灵组 中跟 精灵 发生碰撞的 精灵列表

02. 碰撞实现

def __check_collide(self):

# 1. 子弹摧毁敌机

pygame.sprite.groupcollide(self.hero.bullets, self.enemy_group, True, True)

# 2. 敌机撞毁英雄

enemies = pygame.sprite.spritecollide(self.hero, self.enemy_group, True)

# 判断列表时候有内容

if len(enemies) > 0:

# 让英雄牺牲

self.hero.kill()

# 结束游戏

PlaneGame.__game_over()

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
public abstract class FlyingObject { public static final int LIFE = 0; //活着呢 public static final int DEAD = 1; //死了的(先爆破) public static final int REMOVE = 2; //删除了(爆破后删除) protected int state = LIFE; //当前状态(默认活着) protected int width; //宽 protected int height; //高 protected int x; //x坐标 protected int y; //y坐标 /** 无参构造方法 */ public FlyingObject(){ } /**专门给小敌机、大敌机、小蜜蜂提供的构造方法 */ public FlyingObject(int width,int height){ this.width = width; this.height = height; Random rand = new Random(); x = rand.nextInt(World.WIDTH-width); //x:0到(窗口-小敌机的宽)之间的随机数 y = -height; //y:负的小敌机的高 } /** 专门给英雄机、子弹、天空提供的构造方法 */ public FlyingObject(int width,int height,int x,int y){ this.width = width; this.height = height; this.x = x; this.y = y; } /** 读取图片 */ public static BufferedImage loadImage(String fileName){ try{ BufferedImage img = ImageIO.read(FlyingObject.class.getResource(fileName)); return img; }catch(Exception e){ e.printStackTrace(); throw new RuntimeException(); } } /** 飞行物移动了 */ public abstract void step(); public abstract BufferedImage getImage(); /** 判断是否活着 */ public boolean isLife(){ return state==LIFE; } /** 判断是否死了的 */ public boolean isDead(){ return state==DEAD; } /** 判断是否删除的 */ public boolean isRemove(){ return state==REMOVE; } /** 画对象 g:画笔 */ public void paintObject(Graphics g){ g.drawImage(getImage(), x, y, null); } /** 检测飞行物是否越界 */ public abstract boolean outOfBounds(); /** 敌人与子弹/英雄机的碰撞 this:敌人 other:子弹或英雄机 */ public boolean hit(FlyingObject other){ int x1 = this.x-other.width; //x1:敌人的x int x2 = this.x+this.width; //x2:敌人的x int y1 = this.y-other.height; //y1:敌人的y int y2 = this.y+this.height; //y2:敌人的y int x = other.x; //x:子弹的x int y = other.y; //y:子弹的y return x>=x1 && x=y1 && y<=y2; } public void goDead(){ state = DEAD; //修改当前状态为死了的 } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值