【问题标题】:Java Collision Detection Before You Move移动前的 Java 碰撞检测
【发布时间】:2016-12-05 01:29:28
【问题描述】:

我终于通过在 2 个矩形之间使用 intersects() 来进行碰撞检测,它似乎正在工作。然而,玩家只是卡在矩形中而无法移动。所以我现在试图在玩家移动之前检查碰撞。

这是我尝试过的:

    if(up == true){
        Rectangle futurerect = new Rectangle(px,py-=5,81,150);
        if(!futurerect.intersects(wallexample)){
            py-=5;
            repaint();
        }
    }
    if(down == true){
        Rectangle futurerect = new Rectangle(px,py+=5,81,150);
        if(!futurerect.intersects(wallexample)){
            py+=5;
            repaint();
        }
    }
    if(left == true){
        Rectangle futurerect = new Rectangle(px-=5,py,81,150);
        if(!futurerect.intersects(wallexample)){
            px-=5;
            repaint();
        }
    }
    if(right == true){
        Rectangle futurerect = new Rectangle(px+=5,py,81,150);
        if(!futurerect.intersects(wallexample)){
            px+=5;
            repaint();
        }
    }

我只是创建了一个新的矩形,但如果玩家移动了它会在哪里,并检查它是否发生碰撞。如果是,请不要移动。

问题是,当玩家移动到矩形中时,它只会放慢速度。它仍然穿过墙壁,但出于某种原因只是以较慢的速度移动。

是什么导致了这个问题?

【问题讨论】:

    标签: java collision-detection paint


    【解决方案1】:

    看起来您没有检查正确的区域,因为您对新 Rectangle 的实例化正在递增/递减 py 或 px 并在 Rectangle 的构造函数中为其分配该值。

    因此,如果您的笛卡尔坐标为 0,0,并且您想知道他们是否向上移动,他们是否会撞墙。

    if (up == true) {
    
        Rectangle futurerect = new Rectangle(px,py-=5,81,150);
    
        if(!futurerect.intersects(wallexample)){
            py-=5;
            repaint();
        }
    }
    

    py 现在在实例化 Rectangle 后设置为 -5。

    Rectangle futurerect = new Rectangle(px,py-=5,81,150);
    

    因为第二个参数中有py-=5。

    当您执行相交检查时,它正在查看 0、-5。一旦说“是的,这里没有墙”,您将 py 再减 5。现在我们有一个玩家坐标 px,py 为 0,-10,您没有检查该位置是否有墙。

    尝试在此处修复逻辑,使其不会将新值分配给 px / py:

    Rectangle futureRect = new Rectangle(px, py - 5, 81, 150);
    

    【讨论】:

      猜你喜欢
      • 2013-01-31
      • 2011-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多