获取 Image/Transform/Shape 旋转以跟随 JavaFX 中的鼠标光标
Get Image/Transform/Shape to rotate to Follow Mouse Cursor in JavaFX
我试过这样做,但在某些位置,对象,在这种情况下,我的 ImageView
,将只是 "teleport" 到另一个程度。
我怎样才能让它不不稳定并在 JavaFX 场景中正确地跟随我的鼠标光标?
我最近在一篇关于 how to create a heat seeking missile 的博客 post 中做了这个。
与您相关的部分是这段代码:
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.
的兼容性原因,我没有这样做
如果这对您有帮助,请告诉我。如果这不是您要查找的内容,请更准确。
我试过这样做,但在某些位置,对象,在这种情况下,我的 ImageView
,将只是 "teleport" 到另一个程度。
我怎样才能让它不不稳定并在 JavaFX 场景中正确地跟随我的鼠标光标?
我最近在一篇关于 how to create a heat seeking missile 的博客 post 中做了这个。
与您相关的部分是这段代码:
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.
的兼容性原因,我没有这样做如果这对您有帮助,请告诉我。如果这不是您要查找的内容,请更准确。