首页 文章

Applet“pong”游戏:如果球拍向球移动,球会直接穿过球拍

提问于
浏览
1

通常在这样的游戏中只有Y轴运动可用,但我决定以允许X轴桨运动的方式进行 . 游戏工作完全正常如果我不在X轴上移动桨球当球击中球拍时(在这种情况下它会直接穿过 . )如果我在击球之前停止X轴移动球拍每次都会反弹 .

起初我虽然这与像素有关,但我也尝试以多种方式改变桨冲突而没有正面结果 . 无论我尝试多少次,球都不会从桨上反弹 .

代码非常简单,我一次只移动1px:

public void drawBall(Graphics g) { //ball speed, movement and collision
    b.set(b.getX()+VX,b.getY()+VY); //velocity X and velocity Y both at 1px
    g.setColor(Color.black);
    b.draw(g);

    if(b.getY()<0 || b.getY()>sizeY-b.getRadius()){ //top & bottom collision
        VY = -VY;
    }

    if(b.getX()<0 || b.getX()>sizeX-b.getRadius()){ //left & right detection
        b.center();
        VX = -VX;
        x = (int) (Math.random()*2+0);
        if(x == 0)
            VY = -VY;
    }

    if(b.getX() == p1.getX()+p1.width && b.getY()>p1.getY() && b.getY()<p1.getY()+p1.height){ // p1 paddle detection
        VX = -VX;
    }

    if(b.getX()+b.getRadius()==p2.getX() && b.getY()>p2.getY() && b.getY()<p2.getY()+p2.height){ // p2 paddle detection
        VX = -VX;
    }
}

为了移动桨,我使用简单的标志,在按键上将“移动”设置为“打开”,在按键释放时设置“关闭” . 我在不定式循环中运行它,所以它不断被执行 .

这就是“run()”方法的样子:

public void run() {
    while(true){
        repaint();
        try {
            Thread.sleep(5);
            playerMovement(); //moves players paddle on X and/or Y axis
            playerLimits(); //limits movment of players to specific area
        } catch (InterruptedException e){
        }
    }
}

我再一次试图以这样一种方式创建桨式碰撞,即它不是像素特定的“if(球<比p1桨)然后改变球方向”但没有成功 . 我想我错过了一些重要的东西,但我似乎无法找出它是什么 .

感谢您提前提供任何帮助,我非常感谢 .

1 回答

  • 1

    不要将游戏引擎代码与图形代码混合 - 两者必须分开 . 任何解决方案的关键是确保游戏引擎识别出“碰撞”并正确且明确地处理它 . 不要切换速度方向,而应考虑根据碰撞发生的位置设置这些速度的绝对值 .

    例如,你有这个代码:

    if(b.getY() < 0 || b.getY() > sizeY-b.getRadius()){ //top & bottom collision
        VY = -VY;
    }
    

    但如果超过一个保证金,这可能会导致精灵陷入困境 . 也许更好的做法是:

    if (b.getY() < 0) {
        // note that variables should start with lower-case letters
        vy = Math.abs(vy); // make sure that it is going in a positive direction
    }
    
    if (b.getY() > sizeY - b.getRadius()) {
        vy = -Math.abs(vy);
    }
    

    同样适用于x方向

    另请注意,如果将图形与游戏引擎分开,您的引擎将变得可单独测试并且更易于调试 .

相关问题