gpt4 book ai didi

java - 为什么我的 move() 方法不能将球保持在界内?

转载 作者:行者123 更新时间:2023-12-01 22:31:12 26 4
gpt4 key购买 nike

问题:所以我创建了一个带有 Window 类的程序,该程序创建一个 JFrame 并将我的 DrawStuff 类中的 JPanel 添加到其上。 DrawStuff 类创建一个球(应该)在屏幕上弹跳,当它碰到 JFrame 边界时,改变方向。球移动,但由于某种原因,我的移动方法的检查边界部分不起作用。任何帮助将不胜感激。我的目标是让球保持在界内。

DrawStuff 类的代码:

public class Drawstuff extends JPanel {
private int x = 0;
private int y = 0;
private int dx, dy=0;

public Drawstuff(){
x = 300;
y = 250;
dx = 0;
dy = 0;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
this.setBackground(Color.BLACK);
g2d.setColor(Color.RED);
g2d.fillOval(x,y,50,50);
}
public void move(){

if (x < 600){
dx = 1;
}
if (y < 500){
dy = 1;
}
if (x > 600){
dx = -1;
}
if (y >500){
dy = -1;
}
x += dx;
y += dy;
}

}

窗口类中的简单“GameLoop”(如果需要)

 while (true){
stuff.repaint();
stuff.move();
try {
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

最佳答案

你的移动是错误的。它的逻辑是错误的。您希望球弹起,因此当它撞到墙壁时使其运动反向。你所做的是:如果它在外面,就把它拿到里面,当在里面时,试着把它拿到外面!更改为:

   public void move(){
if (x < 0) { // left bound
dx = 1; // now move right
}
if (y < 0){ // upper bound
dy = 1; // now move down
}
if (x > 600){// right bound
dx = -1; // now move left
}
if (y >500){ // lower bound
dy = -1; // now move up
}
x += dx;
y += dy;
}

为了将来的使用,我建议您按照以下方式进行操作:

   public void move(){
if (x < 0) { // left bound
dx = -dx; // now move right, same speed
x=-x; // bounce inside
}
if (y < 0){ // upper bound
dy = -dy; // now move down, same speed
y=-y; // bounce inside
}
if (x > 600){ // right bound
dx = -dy; // now move left, same speed
x=600-(x-600); // bounce inside
}
if (y >500){ // lower bound
dy = -dy; // now move up, same speed
y=500-(y-500); // bounce inside
}
x += dx;
y += dy;
}

所以你现在可以使用任何你想要的 vector 速度(至少是合理的)。 vector 坐标根据击球而反转,并且球重新定位在边界内。

关于java - 为什么我的 move() 方法不能将球保持在界内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27709538/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com