我正在尝试将球(椭圆形)移动到最近单击鼠标的位置,但是我不希望它跳到那里,我希望它以某个速度移动到那里。 这是我的代码
int BallX = 200;
int BallY = 150;
final int BALL_SIZE = 30; // size of the ball
final int SPEED = 10; // the ball should move at this speed
void setup(){
size(500 , 500); //canvas size
}
void draw(){
drawBall();
}
void drawBall(){
fill(255);
ellipse(BallX , BallY ,BALL_SIZE,BALL_SIZE); // the ball
}
void mouseClicked(){
golfBallX = pmouseX;
golfBallY = pmouseY;
}
答案 0 :(得分:1)
要生成平滑的运动,我建议使用浮点值(double
)进行计算:
您必须声明球的位置和球应到达的目标位置的变量。在初始状态下,两个位置必须相同:
double BallX = 200.0;
double BallY = 150.0;
double targetBallX = 200.0;
double targetBallY = 150.0;
计算draw function
中球的当前位置和目标位置之间的距离:
double deltaX = targetBallX - BallX;
double deltaY = targetBallY - BallY;
double dist = Math.sqrt(deltaX*deltaX + deltaY*deltaY);
如果当前位置与目标位置不同,则朝目标方向执行一个步骤:
if ( dist > 0.0 ) {
double step = Math.min(dist, SPEED);
BallX += step * deltaX / dist;
BallY += step * deltaY / dist;
}
完整代码如下:
double BallX = 200.0;
double BallY = 150.0;
double targetBallX = 200.0;
double targetBallY = 150.0;
final int BALL_SIZE = 30; // size of the ball
final double SPEED = 10.0; // the ball should move at this speed
void setup(){
size(500 , 500); //canvas size
}
void draw(){
double deltaX = targetBallX - BallX;
double deltaY = targetBallY - BallY;
double dist = Math.sqrt(deltaX*deltaX + deltaY*deltaY);
if ( dist > 0.0 ) {
double step = Math.min(dist, SPEED);
BallX += step * deltaX / dist;
BallY += step * deltaY / dist;
}
drawBall();
}
void drawBall(){
background(128);
fill(255);
ellipse((int)BallX, (int)BallY, BALL_SIZE, BALL_SIZE); // the ball
}
void mouseClicked(){
targetBallX = (double)pmouseX;
targetBallY = (double)pmouseY;
}