java在屏幕上移动对象
我试图在屏幕上同时移动两个球体。然而,它们并不是相互独立移动的。相反,一个依赖于另一个的运动。请帮帮我。代码如下:-
Draw
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Draw extends JPanel implements ActionListener
{
Timer timer[] = new Timer[2];
int velX = 2, velY = 2;
Sphere sphere[] = new Sphere[2];
public Draw()
{
for(int i=0;i<2;i++)
{
sphere[i] = new Sphere();
timer[i] = new Timer(5,this);
}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
for(int i=0;i<2;i++)
drawing(g,sphere[i].color,sphere[i].radius);
}
public void drawing(Graphics g,Color color, int radius)
{
for(int i=0;i<2;i++){
g.setColor(color);
g.fillOval(sphere[i].x,sphere[i].y,radius*2,radius*2);
timer[i].start();
}
}
public void actionPerformed(ActionEvent evt)
{
for(int i=0;i<2;i++){
if(sphere[i].x<0 || sphere[i].x>970)
{
velX = -velX;
}
if(sphere[i].y<0 || sphere[i].y>650)
{
velY = -velY;
}
sphere[i].x += velX;
sphere[i].y += velY;
repaint();
}
}
public static void main(String args[])
{
JFrame jf = new JFrame("Renderer");
jf.getContentPane().add(new Draw(),BorderLayout.CENTER);
jf.setBounds(0,0,1024,720);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}
}
Sphere
import java.awt.Color;
class Sphere
{
public int x;
public int y;
public int radius;
Color color;
public Sphere()
{
this.x = (int)(Math.random()*800);
this.y = (int)(Math.random()*600);
this.radius = (int)(Math.random()*50);
this.color = new Color((int)(Math.random()*255),
(int)(Math.random()*255),(int)(Math.random()*255));
}
public Sphere(int x,int y,int radius, Color color)
{
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
}
}
# 1 楼答案
两个球体的速度相同,所以它们的运动会相似
如果在球体创建过程中,为每个球体设置一个随机速度,则运动将不同
# 2 楼答案
两个对象的x/y增量相同,例如,需要在
Sphere
对象中包含这些值然后,在
actionPerformed
方法中,只需调用update此外,您不需要两个
Timer
,只需要一个,每次勾选时都可以使用它来更新两个球体此外,你不应该在“画画”关卡中启动计时器,它们应该提前启动
# 3 楼答案
将
velX
和velY
移动到Sphere
类中。所以每个Sphere
都会保持自己的速度。然后这些球体将独立移动不需要两个
Timer
,我已经把它清理干净了。 我还清理了paintComponent
方法。在两个地方不需要循环以下是我尝试过的,似乎对我有用:
希望这有帮助