我正在创建一个移动的球程序,其中一个球移动并从矩形的墙壁反弹,底部有停止按钮。
我遇到的问题是我希望球在程序运行时开始移动并从矩形内部的线条反弹,这是我的主要问题。以下是我的代码:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
//Does the drawing
class MyDrawing extends JPanel {
private int xpos;
private int ypos;
public void setXPos(final int x) {
this.xpos = x;
}
public void setYPos(final int y) {
this.ypos = y;
}
public int getXpos() {
return xpos;
}
public int getYpos() {
return ypos;
}
@Override
public void paintComponent(final Graphics g) {
super.paintComponent(g);
final Graphics2D g2 = (Graphics2D) g;
g.setColor(Color.red);
final Ellipse2D.Double circle = new Ellipse2D.Double(xpos, ypos, 50, 50);
g2.draw(circle);
g2.fill(circle);
final Rectangle box1 = new Rectangle(10, 10, 380, 300);
g.setColor(Color.BLACK);
g2.draw(box1);
}
}
public class ControlledBall extends JFrame {
private final JButton flash = new JButton("Go");
private final JButton steady = new JButton("Stop");
private final JPanel panel = new JPanel(new GridBagLayout());
private final MyDrawing drawing = new MyDrawing();
private final Timer timer;
//direction
private int dx = 3;
private int dy = 2;
public ControlledBall() {
panel.add(flash);
panel.add(steady);
this.add(panel, BorderLayout.SOUTH);
this.add(drawing, BorderLayout.CENTER);
drawing.setXPos(300);
drawing.setYPos(150);
steady.addActionListener(new SteadyListener());
final MoveListener ml = new MoveListener();
flash.addActionListener(ml);
timer = new Timer(15, ml);
}
class MoveListener implements ActionListener {
@Override
public void actionPerformed(final ActionEvent event) {
if (!timer.isRunning()){
timer.start();
}
move();
}
}
class SteadyListener implements ActionListener {
@Override
public void actionPerformed(final ActionEvent event) {
if (timer.isRunning()){
timer.stop();
}
}
}
private void move() {
int x = drawing.getXpos();
int y = drawing.getYpos();
final int dia = 30;
if (x + dx < 0 || x + dia + dx > getWidth()) {
dx *= -1;
}
if (y + dy < 0 || y + dia + dy > getHeight()) {
dy *= -1;
}
x += dx;
y += dy;
drawing.setXPos(x);
drawing.setYPos(y);
repaint();
}
public static void main(final String[] args) {
final JFrame window = new ControlledBall();
window.setSize(400, 400);
window.setTitle("Controlled Ball");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
}
答案 0 :(得分:0)
问题是您检查的边界。如果你想检查矩形,你必须将大小作为变量实现并在“bounce” - 检查中输入它们,或者手动添加它(从代码中取出矩形的大小):
if (x + dx < 10 || x + dia + dx > 380) {
dx *= -1;
}
if (y + dy < 10 || y + dia + dy > 300) {
dy *= -1;
}
如果您想使用真正的distanz,请使用球的hallf大小的偏移量并将其添加到此代码中。我认为这比速度矢量dx
和dy
更好。