我正在做一个关于将固定点与动画点链接起来的项目。 我正在使用这个,我想用随机分布的随机数量的点来做到这一点。源代码仅用于 2 个位置,我想对所有点执行此操作,例如从点 1 获取 x 和 y。例如,我希望它转到其他位置点 2 和点 3。
PS:我是法国人,不会说英语。很抱歉出现错误,我是 Java 新手。
Panneau.java
package animation;
/**
*
* @author ilies
*/
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Panneau extends JPanel {
private int posX = -50;
private int posY = -50;
public void paintComponent(Graphics g){
//On choisit une couleur de fond pour le rectangle
g.setColor(Color.white);
//On le dessine de sorte qu'il occupe toute la surface
g.fillRect(0, 0, this.getWidth(), this.getHeight());
//On redéfinit une couleur pour le rond
g.setColor(Color.red);
//On le dessine aux coordonnées souhaitées
g.fillOval(posX, posY, 50, 50);
}
public int getPosX() {
return posX;
}
public void setPosX(int posX) {
this.posX = posX;
}
public int getPosY() {
return posY;
}
public void setPosY(int posY) {
this.posY = posY;
}
}
Fenetre.java
package animation;
/**
*
* @author ilies
*/
import java.awt.Dimension;
import javax.swing.JFrame;
public class Fenetre extends JFrame{
private Panneau pan = new Panneau();
public Fenetre(){
this.setTitle("Animation");
this.setSize(300, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setContentPane(pan);
this.setVisible(true);
go();
}
private void go(){
for(int i = -50; i < pan.getWidth(); i++){
int x = pan.getPosX(), y = pan.getPosY();
x++;
y++;
pan.setPosX(x);
pan.setPosY(y);
pan.repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
动画.java
package animation;
/**
*
* @author ilies
*/
public class Animation {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Fenetre fen = new Fenetre();
// TODO code application logic here
}
}
最佳答案
你确实需要某种插值方法。您当前的代码只是在屏幕上进行翻译 - 这与有意在两点之间移动有很大不同。
这是一个非常简单的实现。更稳健的解决方案(即恒定速度)将使用速度参数和帧之间的时间变化。
public Point interpolate(Point start, Point end, double fraction) {
int dx = end.x - start.x;
int dy = end.y - start.y;
int newX = (int) (start.x + dx * fraction);
int newY = (int) (start.y + dy * fraction);
return new Point(newX, newY);
}
此外,您需要一些随机点来进行插值。
ArrayList<Point> pointList = new ArrayList<>();
Random rand = new Random();
for (int i = 0; i < 2 + rand.nextInt(10); i++) {
pointList.add(new Point(rand.nextInt(pan.getWidth()),
rand.nextInt(pan.getHeight())));
}
最后,您需要将 Fenetre.go() 中的动画循环替换为:
while (true) {
// Change the speed by changing the delta value
for (double i = 0.0; i <= 1.0; i += 0.05) {
Point p = interpolate(pointList.get(0), pointList.get(1), i);
pan.setPosX(p.x);
pan.setPosY(p.y);
pan.repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Push the first point to the back of the list and repeat
pointList.add(pointList.remove(0));
}
关于java - 如何在两个不同点之间绘制移动动画线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27257259/