我正在尝试用Java创建一个简单的乒乓球游戏进行处理。我还没有完成,一切都很顺利,除了我不能让球从乒乓球拍上弹起。我已经成功地做到了,如果球低于球拍,它会反弹回来,但由于某种原因,球将通过,如果它高于球拍。
这是我的当前代码,我当前的问题是在void animatePaddles函数的paddleFunctions选项卡中:
main选项卡:
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
}Ball类:
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;
}
}Paddle类:
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;
}发布于 2019-12-18 21:47:29
你的建议是错误的。传递给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;
}https://stackoverflow.com/questions/59389695
复制相似问题