通常只有Y轴运动在这样的游戏中可用,但我决定让它以这样的方式,X轴划桨运动也是允许的。当球击中桨时,如果我不移动X轴上的桨,游戏就会非常好(在这种情况下,它会直接通过)。如果我停止X轴运动之前,球击中,桨球将弹出它每一次。
起初,我认为这与像素有关,但我也尝试以多种方式改变桨的碰撞,但没有任何积极的结果。不管我试过多少次,球永远不会从桨上跳下来。
代码非常简单,每次只移动1 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(ball < p1 paddle)然后改变球的方向“,但没有成功。我想我错过了一些重要的东西,但我似乎找不到它是什么。
谢谢你提前提供帮助,我非常感激。
发布于 2018-04-28 23:16:19
不要把你的游戏引擎代码和你的图形代码混在一起--两者必须分开。任何解决方案的关键是确保游戏引擎识别“冲突”,并正确和明确地处理它。与其切换速度方向,不如考虑根据碰撞发生的地点设置这些速度的绝对值。
例如,您有以下代码:
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方向也是如此
还请注意,如果您将图形从游戏引擎中分离出来,那么您的引擎就会变得可单独测试,并且更容易调试。
https://stackoverflow.com/questions/50081836
复制相似问题