mirror of
http://junepve.top:3000/chicrobot/CINC.git
synced 2026-10-30 09:41:29 +08:00
feat(SS) 故事场景添加摇杆
This commit is contained in:
1 parent
5644f9c1eb
commit
942ba567f3
2 files changed
+91
No files matched your search
@@ -0,0 +1,79 @@
|
||||
export default class Joystick {
|
||||
constructor(scene, x, y, radius, baseColor, thumbColor) {
|
||||
this.scene = scene
|
||||
this.x = x
|
||||
this.y = y
|
||||
this.radius = radius
|
||||
this.baseColor = baseColor
|
||||
this.thumbColor = thumbColor
|
||||
}
|
||||
/**
|
||||
* 创建摇杆,设置层级
|
||||
*/
|
||||
createJoystick(layer = 100) {
|
||||
// 创建基座
|
||||
this.joystickBase = this.scene.add.circle(0, 0, this.radius, this.baseColor)
|
||||
this.joystickBase.setPosition(this.x, this.y)
|
||||
// 创建按钮
|
||||
this.joystickButton = this.scene.add.circle(0, 0, this.radius / 2, this.thumbColor)
|
||||
this.joystickButton.setPosition(this.x, this.y)
|
||||
// 设置层级
|
||||
this.joystickBase.setDepth(layer)
|
||||
this.joystickButton.setDepth(layer)
|
||||
}
|
||||
/**
|
||||
* 获取摇杆归一化方向与力度
|
||||
* @returns {Object} 归一化方向 {x, y} 与力度 magnitude
|
||||
*/
|
||||
getJoystickDirection() {
|
||||
// 获取摇杆方向,归一化
|
||||
const direction = {
|
||||
x: this.joystickButton.x - this.joystickBase.x,
|
||||
y: this.joystickButton.y - this.joystickBase.y,
|
||||
}
|
||||
// 计算力度
|
||||
const magnitude = Math.sqrt(direction.x ** 2 + direction.y ** 2)
|
||||
// 归一化方向
|
||||
direction.x /= magnitude
|
||||
direction.y /= magnitude
|
||||
return {direction, magnitude}
|
||||
}
|
||||
/**
|
||||
* 重置摇杆位置
|
||||
*/
|
||||
resetJoystick() {
|
||||
this.joystickButton.setPosition(this.x, this.y)
|
||||
}
|
||||
/**
|
||||
* 监听摇杆输入
|
||||
*/
|
||||
listenJoystickInput() {
|
||||
// 监听按钮按下事件
|
||||
this.joystickButton.on('pointerdown', (pointer) => {
|
||||
this.joystickButton.setPosition(pointer.x, pointer.y)
|
||||
})
|
||||
// 监听按钮移动事件
|
||||
this.joystickButton.on('pointermove', (pointer) => {
|
||||
// 计算摇杆按钮到基座中心的距离
|
||||
const dx = pointer.x - this.x
|
||||
const dy = pointer.y - this.y
|
||||
const distance = Math.sqrt(dx * dx + dy * dy)
|
||||
|
||||
if (distance > this.radius) {
|
||||
// 限制在基座范围内
|
||||
const angle = Math.atan2(dy, dx)
|
||||
this.joystickButton.setPosition(
|
||||
this.x + this.radius * Math.cos(angle),
|
||||
this.y + this.radius * Math.sin(angle)
|
||||
)
|
||||
} else {
|
||||
// 在基座范围内,跟随手指
|
||||
this.joystickButton.setPosition(pointer.x, pointer.y)
|
||||
}
|
||||
})
|
||||
// 监听按钮松开事件
|
||||
this.joystickButton.on('pointerup', () => {
|
||||
this.resetJoystick()
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user