我正在尝试使用Java创建一个简单的pong游戏进行处理。我还没有结束,一切都进行得很好,除了我不能使球从乒乓球拍上弹起。我成功地做到了这一点,因此,如果球低于球拍,球会弹回,但由于某种原因,如果球高于球拍,球会通过。
这是我当前的代码,我当前的问题在void animatePaddles
函数的paddleFunctions选项卡中:
主标签:
Ball ball;
Paddle primary, secondary;
void setup()
{
size(1000, 500);
background(0);
smooth();
frameRate(150);
ball = new Ball();
initializePaddles(); // enters x values into primary and secondary paddles
}
void draw()
{
ball.animateBall(); //uses vectors to add movements to ball, also checks if hitting walls
animatePaddles(); //adds movements to paddles
}
球类:
class Ball
{
PVector location, direction;
final int diameter = height/20;
Ball()
{
location = new PVector(width/2, height/2);
direction = new PVector(0.5, 0.5);
}
void animateBall() //movement to balls and checking if hitting walls
{
background(0);
fill(255);
circle(location.x, location.y, diameter);
location.add(direction);
if (location.y+diameter/2>= height|| location.y<=diameter/2)
direction.y*=-1;
}
}
桨类:
class Paddle //class for paddles
{
PVector location;
PVector direction = new PVector(0, 0);
final int paddleLength = height/5;
final int paddleWidth = width/150;
}
paddleFunctions选项卡:
void initializePaddles() //enters x values into paddles relative screen size
{
primary = new Paddle();
primary.location= new PVector(width*.987, height/2);
secondary = new Paddle();
secondary.location = new PVector(width*.007, height/2);
}
void animatePaddles() //creates the paddles and adds movement
{
fill(255);
rect(primary.location.x, primary.location.y, primary.paddleWidth, primary.paddleLength);
rect(secondary.location.x, secondary.location.y, secondary.paddleWidth, secondary.paddleLength);
primary.location.add(primary.direction);
secondary.location.add(secondary.direction);
if (ball.location.x+ball.diameter/2==primary.location.x-primary.paddleWidth/2 && ball.location.y>=primary.location.y-primary.paddleLength/2 && ball.location.y<=primary.location.y+primary.paddleLength/2) //THE PROBLEM
ball.direction.x*=-1; //^^ **PROBLEM**
}
void keyPressed() //controls primary paddle
{
if (key == CODED)
if (keyCode == UP)
primary.direction.y=-2;
else if (keyCode == DOWN)
primary.direction.y=2;
}
void keyReleased()
{
primary.direction.y=0;
}
答案 0 :(得分:0)
您的建议是错误的。传递给rect()
的坐标不是矩形的中心,默认情况下是左上角。但是您可以通过rectMode()
更改模式:
rectMode(CENTER);
rect(primary.location.x, primary.location.y, primary.paddleWidth, primary.paddleLength);
rect(secondary.location.x, secondary.location.y, secondary.paddleWidth, secondary.paddleLength);
由于您使用浮点数进行操作,因此球永远不会精确地碰到桨。您必须评估球的右侧是否大于桨的左侧:
if (ball.location.x+ball.diameter/2 >= primary.location.x-+primary.paddleWidth/2 &&
ball.location.y >= primary.location.y-primary.paddleLength/2 &&
ball.location.y <= primary.location.y+primary.paddleLength/2) {
ball.direction.x *= -1;
}