【发布时间】:2017-03-19 12:06:01
【问题描述】:
在 Java swing 中有没有一种方法可以让 sprite 具有真实的效果?就像它围绕中心随机移动并产生波动效果一样?
我尝试了类似以下的方法(但结果很糟糕):
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Main extends JFrame {
private static final int W = 800;
private static final int H = 400;
private int last = -1;
public Main() {
super("JFrame");
this.add(new ImagePanel());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
setSize(W, H);
this.setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new Main();
}
});
}
class ImagePanel extends JPanel {
Timer movementTimer;
int x, y;
public ImagePanel() {
x = 58;
y = 58;
movementTimer = new Timer(12, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
moveImage();
repaint();
}
});
movementTimer.start();
}
public void moveImage() {
if (last < 0) {
last = random();
x += last;
y += last;
} else {
x -= last;
y -= last;
last = -1;
}
if (x > W) {
x = 0;
}
if (y > H) {
y = 0;
}
}
private int random() {
Random r = new Random();
int Low = 2;
int High = 14;
int Result = r.nextInt(High - Low) + Low;
return Result;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
long start = System.nanoTime();
g.setColor(Color.RED);
g.fillRect(0, 0, W, H);
g.setColor(Color.BLUE);
g.fillRect(x, y, 50, 50);
}
}
}
结果一点都不顺利,你有什么建议吗?
【问题讨论】:
-
简短的回答是肯定的,但是您需要做一些工作。 Graphics2D API 有许多类和功能,可以很容易地实现这一点
-
谢谢,但简短的回答太短了... :) 是否有一些您可以提供的示例或一些互联网资源可供我开始?请告诉我。
-
是的,有成千上万的例子,不,我不应该为你搜索它们;)
-
只是提示,如果您正在寻找逼真的运动,例如家蝇的运动如何以流畅的方式波动,您可能需要查看 perlin noise 而不是使用原始 RNG