gpt4 book ai didi

java - 为什么 getHeight() 不等于框架高度?

转载 作者:行者123 更新时间:2023-11-29 03:11:47 25 4
gpt4 key购买 nike

我正在制作一个围绕框架移动的弹跳立方体。为了检测框架的边界,我使用了 JFrame 中 JComponent 的 getHeight() 和 getWidth() 并计算可能的边界,以便立方体可以反弹。

它对 getWidth() 完全有效。但是,我无法让它在 getHeight() 的边界上反弹。

当立方体到达窗口顶部时,它会在反弹前继续移动大约 10 个像素。

这是这个问题的截图。

enter image description here

这是我的代码:

public class Cube {
final public static int DIMENSION = 100;
private final static int D_X = 20;
private final static int D_Y = -20;
private final static int SPEED = 1;
private int xVelBK;
private int yVelBK;
private int xVel;
private int yVel;
private CubePoint[] pts;

public Cube(int x, int y){
xVel = SPEED;
yVel = SPEED;

pts = new CubePoint[8];

pts[0] = new CubePoint(x,y);
pts[1] = new CubePoint(x,y - DIMENSION);
pts[2] = new CubePoint(x + DIMENSION,y - DIMENSION);
pts[3] = new CubePoint(x + DIMENSION,y);

pts[4] = new CubePoint(x + D_X,y + D_Y);
pts[5] = new CubePoint(x + D_X,y + D_Y - DIMENSION);
pts[6] = new CubePoint(x + D_X + DIMENSION,y + D_Y - DIMENSION);
pts[7] = new CubePoint(x + D_X + DIMENSION,y + D_Y);
}

public void move(int componentWidth, int componentHeight){
......

//bug in here
if (pts[0].getY() - DIMENSION - D_Y <= 0 ) {
yVel = SPEED;
}

.......
}
..........
}

这是组件:

public class CubeComponent extends JComponent {
...........

private Cube cube;
private Timer timer;
private CubePoint originMousePos;
private CubePoint closest;
private Font font;
private int mode;


private int delay = DEFAULT_DELAY ;

private int mouseToClosestX;
private int mouseToClosestY;

class CubeMoveListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e){
cube.move(getWidth(),getHeight());
repaint();
}

}



@Override
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D)g;

cube.draw(g2);
}

}

最佳答案

据我所知:

 if (pts[0].getY()  - DIMENSION - D_Y <= 0 ) {

应该用于确定立方体何时到达组件底部,因此您应该测试“>”

if ( pts[0].getY() >= componentHeight) {

应该在立方体到达顶部时用于测试。所以应该是:

if ( pts[0].getY() <= 0) {

重点在于:

  1. 其中一个垂直测试需要测试“<= 0”。
  2. 水平测试和垂直测试的结构应该是一样的,你只需要改变变量名。

关于java - 为什么 getHeight() 不等于框架高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28935000/

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