如何在Phaser3中获取鼠标点到特定对象之间的距离



我想要归档的是,当用户单击时,获取鼠标指针与预定义图像之间的距离。

假设在[0,0]位置有一个图像,当用户点击屏幕[9,10]时,我需要获得这两个位置之间的距离,单位为m或cm。

在相位器3中有什么方法可以做到这一点吗?非常感谢你的帮助。感谢

Math.sqrt(Math.pow(imageSprite.y - MousePointer.y,2)+Math.pow(imageSprite.x - MousePointer.x,2))

Phaser在几个命名空间中内置了实用程序方法。你可以在这里找到的是Phaser.Math.Distance。您对世界x/y值是正确的,这些值不是通过移动相机来转换的。

import * as Phaser from "phaser";
new Phaser.Game({
scene: {
create
}
});
function create(this: Phaser.Scene) {
const rect = this.add.rectangle(200, 200, 30, 30, 0xff0000);
this.input.on(Phaser.Input.Events.POINTER_DOWN, (pointer: Phaser.Input.Pointer) => {
const dist = Phaser.Math.Distance.Between(pointer.worldX, pointer.worldY, rect.x, rect.y);
console.log(dist);
});
}

我们可以得到这样的鼠标坐标。我在鼠标点击中使用了这个代码

var pointer = this.input.activePointer;
console.log([
'x: ' + pointer.worldX,
'y: ' + pointer.worldY,
'isDown: ' + pointer.isDown,
'rightButtonDown: ' + pointer.rightButtonDown()
]);

我们可以得到像这样的图像位置

this.x1 = this.elephantImage.x.toFixed();
this.y1 = this.elephantImage.y.toFixed();

我们可以得到这样的距离

var dx = this.x1 - this.x2;
var dy = this.y1 - this.y2;
var distance = Math.sqrt(dx * dx + dy * dy);
console.log("distance--->" + distance.toFixed());

最新更新