gpt4 book ai didi

Java,来回移动矩形

转载 作者:行者123 更新时间:2023-12-01 17:05:54 25 4
gpt4 key购买 nike

我正在尝试为对象设置动画以在两个边界之间来回移动。例如,一旦对象的 x 坐标达到 500,它就会向 200 的相反方向移动,然后再次向后移动,直到达到 500,依此类推。但是,矩形只会移动到 500,然后停止。这是我的代码的简化版本:

public class Test
{

public static class Game extends JComponent implements ActionListener
{
int width=100;
int height=100;
int x=300;
int y=200;
Timer timer;
public Game()
{
timer = new Timer(20,this);
timer.start();
}
public void paint(Graphics g)
{
g.drawRect(x,y,width,height);
g.setColor(Color.red);
g.fillRect(x,y,width,height);
}
public void actionPerformed(ActionEvent e)
{
if(x>100)
{
x+=5;
}
if(x>500)
{
x-=5;
}

repaint();
}
}
public static void main(String[] args)
{
JFrame frame = new JFrame("Test");
frame.setPreferredSize(new Dimension(800,600));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Game());
frame.pack();
frame.setVisible(true);
}


}

最佳答案

这样看,根据你的逻辑,当x大于100时,添加5,当它大于500减去5...

因此,一旦达到超过 500,它既大于 100 又大于 500...所以您将加减5,这意味着它不会去任何地方。

您需要的是一个基本delta值,它描述了要应用的更改量。然后,您可以根据您的范围翻转该值...

public void actionPerformed(ActionEvent e) {

x += delta;
if (x > 500) {
delta *= -1;
x = 500;
} else if (x < 100) {
delta *= -1;
x = 100;
}

repaint();
}

您可能还想查看Performing Custom Painting (因为不建议覆盖 paint ,您应该调用 super.paint 以免破坏绘制链)和 Initial Threads

关于Java,来回移动矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25599616/

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