Java Pong球在桨上滑行 [英] Java Pong ball glides on paddle

查看:174
本文介绍了Java Pong球在桨上滑行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用Java制作了一个Pong游戏,我遇到了一个问题。

im making a pong game in java, i've run into a problem.

错误是,当乒乓球与AI或玩家的球拍相交时,该球有时会碰撞多次。基本上看起来像是球在桨上滑动。有时,球甚至会无限次地卡在球拍后面。

The bug is that when the pong ball intersects with either the AI or player paddles, the ball will sometimes collide multiple times. It basically looks like like the ball is gliding on the paddle. Sometimes, the ball will even get stuck behind the paddle infinitely.

有人遇到过此错误或类似错误吗?我对这种多重碰撞感到困惑:(

Had anyone ever encountered this error or something similar? I am confused with this multiple collision stuff :(

我的球类如下:

package ponggame;

import java.awt.*;

public class Ball{
int x;
int y;
int sentinel;

int width = 15;
int height = 15;

int defaultXSpeed = 1;
int defaultYSpeed = 1;

public Ball(int xCo, int yCo){
    x = xCo;
    y = yCo; 
}

public void tick(PongGame someGame) {
    x += defaultXSpeed;
    y+= defaultYSpeed;

    if(PongGame.ball.getBounds().intersects(PongGame.paddle.getBounds()) == true){
            defaultXSpeed *= -1;
    }
    if(PongGame.ball.getBounds().intersects(PongGame.ai.getBounds()) == true){
            defaultXSpeed *= -1;
    }
    if(PongGame.ball.y > 300){
        defaultYSpeed *= -1;
    }
    if(PongGame.ball.y < 0){
        defaultYSpeed *= -1;
    }
    if(PongGame.ball.x > 400){
        defaultXSpeed *= -1;
        PongGame.playerScore++;
        System.out.println("Player score: " + PongGame.playerScore);
    }
    if(PongGame.ball.x < 0){
        defaultXSpeed *= -1;
        PongGame.aiScore++;
        System.out.println("AI score: " + PongGame.aiScore);
    }

}

public void render(Graphics g ){
    g.setColor(Color.WHITE);
    g.fillOval(x, y, width, height);
}

public Rectangle getBounds(){
    return new Rectangle(PongGame.ball.x, PongGame.ball.y, PongGame.ball.width, PongGame.ball.height);
}

}

推荐答案

问题是,当球与球拍相交时,您没有改变球的位置,只是在反转x速度。

The problem is you're not changing the ball's position when it intersects the paddle, you're just reversing the x velocity.

因此,如果球与桨深相交,则x速度在正负之间无限地翻转。

So, if the ball intersects with a paddle deeply, x velocity is infinitely flipped between positive and negative.

尝试跟踪每个刻度线上球的先前位置。发生碰撞时,将球的位置设置为最后一个位置,然后反转x速度。

Try tracking the ball's previous position on each tick. Upon collision, set the ball's position to its last position, and reverse x velocity.

这是快速解决您的问题的方法。一个更现实的物理系统可以更精确地计算出碰撞后的新位置,但这对于低速已经足够了,尤其是当您没有按时间缩放时。

This is a quick fix for your problems. A more realistic physics system would calculate the new position after collision more precisely, but this is good enough for low velocities, especially as you're not scaling by time.

这篇关于Java Pong球在桨上滑行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆