为了账号安全,请及时绑定邮箱和手机立即绑定

使用矩形进行游戏冲突检测

使用矩形进行游戏冲突检测

收到一只叮咚 2022-09-01 16:37:22
我从我的第一款游戏开始,但无法弄清楚碰撞检测应该如何工作。目标是玩家不应该能够进入墙壁。我有以下类玩家(),墙(),级别()和游戏()玩家类是加载玩家并为玩家处理移动和碰撞。墙正在创建墙,我在这个类中有一个Arraylist,它正在为创建的每一面墙创建一个矩形。级别类正在加载创建和加载所有级别。游戏类是处理整个游戏循环等等。我试图将x和y位置与玩家和墙壁进行比较,现在我正在尝试使用尚未成功的.intersect类。玩家类的一部分:public void collision() {Rectangle r3 = getOffsetBounds();for (int i = 0; i < Wall.wallList.size(); i++) {    Rectangle w1 = Wall.wallList.get(i);    if (r3.intersects(w1)) {    }}}public int moveUp(int velY) {    collision();    y -= velY;    return y;}public int moveDown(int velY) {    collision();    y += velY;    return y;}public int moveLeft(int velX) {    collision();    x -= velX;      return x;}public int moveRight(int velX) {    collision();    x += velX;    return x;}public Rectangle getOffsetBounds() {    return new Rectangle(x + velX, y + velY, width, height);}public int getX() {    return x;}public void setX(int x) {    this.x = x;}public int getY() {    return y;}public void setY(int y) {    this.y = y;}public int getVelX() {    return velX;}public void setVelX(int velX) {    this.velX = velX;}public int getVelY() {    return velY;}public void setVelY(int velY) {    this.velY = velY;}}墙面类的一部分:static ArrayList<Rectangle> wallList = new ArrayList<Rectangle>();public int getX() {    return x;}public void setX(int x) {    this.x = x;}public int getY() {    return y;}public void setY(int y) {    this.y = y;}public void setVisisble(Boolean visible) {    this.visible = visible;}public Rectangle getBounds() {    return new Rectangle(x,y,width,height);}public Rectangle setBounds(int x,int y,int width,int height) {    this.x = x;    this.y = y;    this.width = width;    this.height = height;    return new Rectangle(x,y,width,height);}}设置墙列表的“级别”类的一部分                if(level1[i][j]==1) {                w = new Wall(j*25, i*25, width, height);                w.paint(g);                Wall.wallList.add(w.setBounds(j*25+10, i*25+10, width, height));                }
查看完整描述

1 回答

?
守着星空守着你

TA贡献1799条经验 获得超8个赞

这就是我总是如何处理任何碰撞

if (((x1<x2 && x1+w1>x2) || (x2<x1 && x2+w2>x1)) && 
    ((y1<y2 && y1+h1>y2) || (y2<y1 && y2+h2>y1)))


查看完整回答
反对 回复 2022-09-01
  • 1 回答
  • 0 关注
  • 60 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信