[英]how to draw a moving animation line between two different points
我正在做一个有关将固定点与动画点链接的项目。 我正在使用它,我想使用随机位于任意位置的点来执行此操作。 源代码仅用于我要对所有点进行的两个位置,例如我从点1取x和y。例如,我希望它转到其他位置点2和点3。
PS:我是说法语而不是说英语的人。 对不起,我在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;
}
}
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();
}
}
}
}
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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.