gpt4 book ai didi

java - 小程序 "pong"游戏 : ball goes right through paddle if paddle is moving towards the ball

转载 作者:行者123 更新时间:2023-11-30 06:11:45 27 4
gpt4 key购买 nike

通常此类游戏中只有 Y 轴移动可用,但我决定以同样允许 X 轴桨移动的方式进行制作。如果我在球击中桨时不在 X 轴上移动桨(在这种情况下它会直接穿过),则游戏工作得很好。如果我在球击中桨之前停止 X 轴移动,球每次都会从球上弹开。 p>

起初我认为这与像素有关,但我也尝试以多种方式改变桨碰撞,但没有取得积极的结果。无论我尝试多少次,球都不会从 Racket 上弹开。

代码非常简单,我一次只将所有内容移动 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){
}
}
}

我再次尝试以这样的方式创建 Racket 碰撞,即它不是特定于像素的“如果(球<比p1 Racket )然后改变球方向”,但没有成功。我想我在这里遗漏了一些重要的东西,但我似乎无法找出它是什么。

感谢您提前提供的任何帮助,非常感谢。

最佳答案

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

例如,您有以下代码:

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

但是如果 Sprite 超出了边缘,就有可能被困住。也许更好的做法是这样做:

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 方向也是如此

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

关于java - 小程序 "pong"游戏 : ball goes right through paddle if paddle is moving towards the ball,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50081836/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com