我尝试在Java中做我的第一个图形程序-弹跳球。实际上,根据教程,它应该是碎砖机。但是现在它正在反弹。球应从窗户的框架反弹。到目前为止,我已经对其进行了编程。问题是球不整齐,根本无法流畅地移动。如果我按住键盘键,球将流畅地移动。首先,虽然我的图形卡和Linux系统可能会出现问题(AMD Ryzen 5集成图形,Ubuntu 20.04)?但是为什么当我按住键盘按钮时它可以正常工作。有任何想法吗?

package com.company;

import javax.swing.JFrame;

public class Main {

    public static void main(String[] args) {
    JFrame obj=new JFrame();
    Gameplay gamePlay = new Gameplay();
    obj.setBounds(10,10,700,600);
    obj.setTitle("Breakout Ball");
    obj.setResizable(false);
    obj.setVisible(true);
    obj.setDefaultCloseOperation(obj.EXIT_ON_CLOSE);
    obj.add(gamePlay);
    }
}


package com.company;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


import javax.swing.*;


public class Gameplay extends JPanel implements ActionListener {
    private boolean play=false;


    private int totalBrics=21;

    private Timer timer;
    private int delay=8;

    private int playerX=310;

    private int ballposX=120;
    private int ballposY=350;
    private int ballXdir=-1;
    private int ballYdir=-2;

    public Gameplay(){
        setFocusable(true);
        setFocusTraversalKeysEnabled(false);
        timer=new Timer(delay, this);
        timer.start();
    }
    public void paint (Graphics g){
        //background
        g.setColor(Color.black);
        g.fillRect(1,1,692,592);

        //borders
        g.setColor(Color.yellow);
        g.fillRect(0,0,3,592);
        g.fillRect(0,0,692,3);
        g.fillRect(691,0,3,592);

        // paddle
        g.setColor(Color.green);
        g.fillRect(playerX, 550,100,8);

        //ball
        g.setColor(Color.yellow);
        g.fillOval(ballposX, ballposY,20,20);

        //g.dispose();

    }

    public void actionPerformed(ActionEvent f) {
        //timer.start();
        play=true;
        if (play){
            if(new Rectangle(ballposX, ballposY, 20,20).intersects(new Rectangle(playerX,550,100,8))){
                ballYdir=-ballYdir;
            }
            ballposX+=ballXdir;
            ballposY+=ballYdir;
            if(ballposX<0){
                ballXdir=-ballXdir;
            }
            if(ballposY<0){
                ballYdir=-ballYdir;
            }
            if(ballposY>570){
                ballYdir=-ballYdir;
            }
            if(ballposX>670){
                ballXdir=-ballXdir;
            }
        }
        repaint();

    }

}

最佳答案

我运行了您的确切代码,效果很好。按下按键时没有真正的滞后或更好的行为。因此,您的硬件可能有问题吗?

10-07 21:01