我试图这样做,但在某些位置,对象,在这种情况下,我的ImageView
,只会传送"在另一个程度上。
如何让它不会在JavaFX场景中不稳定并正确地跟随我的鼠标光标?
答案 0 :(得分:1)
我最近在一篇关于how to create a heat seeking missile的博客文章中这样做了。
您的相关部分是此代码片段:
public void move() {
SpriteBase follower = this;
if( target != null)
{
//get distance between follower and target
double distanceX = target.getCenterX() - follower.getCenterX();
double distanceY = target.getCenterY() - follower.getCenterY();
//get total distance as one number
double distanceTotal = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
//calculate how much to move
double moveDistanceX = this.turnRate * distanceX / distanceTotal;
double moveDistanceY = this.turnRate * distanceY / distanceTotal;
//increase current speed
follower.dx += moveDistanceX;
follower.dy += moveDistanceY;
//get total move distance
double totalmove = Math.sqrt(follower.dx * follower.dx + follower.dy * follower.dy);
//apply easing
follower.dx = missileSpeed * follower.dx/totalmove;
follower.dy = missileSpeed * follower.dy/totalmove;
}
//move follower
follower.x += follower.dx;
follower.y += follower.dy;
//rotate follower toward target
double angle = Math.atan2(follower.dy, follower.dx);
double degrees = Math.toDegrees(angle) + 90;
follower.r = degrees;
}
跟随者是你的对象,目标是鼠标光标。您可以使用Point2D的Java 8功能来计算距离,这将使代码更少。出于与Java 7的兼容性原因,我没有这样做。
如果这有助于您,请告诉我。如果它不是您想要的,请更准确。