You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Phaser 3中实现球杆围绕母球圆周旋转?

Phaser 3实现球杆围绕母球圆周旋转

问题背景

我正在用Phaser 3重制8球台球,已实现球杆随鼠标旋转的瞄准功能,但需要让球杆围绕母球圆周旋转(杆头始终贴住母球,整体绕母球中心做圆周运动)。尝试过Phaser.Actions.RotateAround()系列方法未成功,目前用setOrigin(0, 0.5)设置了球杆绕杆头旋转。

现有代码

场景create方法

create() {
    this.setupTable();

    this.cueball = new Ball(this, 847, 400, 'ballsAndCue', '14ball.png', true);
    
    this.cue = new Cue(this, 800, 400, 'ballsAndCue', 'cue.png', this.cueball);

    this.input.on('pointermove', function (pointer) {
        this.angle = Phaser.Math.Angle.BetweenPoints(this.cue, pointer);
        this.cue.rotation = this.angle;
    }, this);
}

Cue类

import Phaser from 'phaser';

export default class Cue extends Phaser.GameObjects.Sprite {
    constructor(scene, x, y, spritesheet, sprite, cueball) {
        super(scene, x, y, spritesheet, sprite);
        scene.add.existing(this);
        this.setX(cueball.x);
        this.setY(cueball.y);
        this.setScale(0.7, 1);
        this.setOrigin(0, 0.5);
    }
}

解决方案

核心是通过三角函数计算球杆位置,让它始终处于母球与鼠标的反向延长线上,同时保持旋转角度指向鼠标:

  1. 修改pointermove事件逻辑
this.input.on('pointermove', function (pointer) {
    // 计算母球到鼠标的夹角
    const angle = Phaser.Math.Angle.BetweenPoints(this.cueball, pointer);
    
    // 设置球杆旋转角度,指向鼠标
    this.cue.rotation = angle;
    
    // 计算球杆偏移距离:根据素材实际长度和缩放比例调整,这里假设原始杆长一半为200
    const offset = 200 * this.cue.scaleX;
    // 球杆位置:母球往角度方向偏移offset,让杆头贴住母球
    this.cue.x = this.cueball.x + Math.cos(angle) * offset;
    this.cue.y = this.cueball.y + Math.sin(angle) * offset;
}, this);
  1. 优化Cue类初始化
import Phaser from 'phaser';

export default class Cue extends Phaser.GameObjects.Sprite {
    constructor(scene, x, y, spritesheet, sprite, cueball) {
        super(scene, x, y, spritesheet, sprite);
        scene.add.existing(this);
        this.setScale(0.7, 1);
        this.setOrigin(0, 0.5);
        this.cueball = cueball; // 保存母球引用
        
        // 初始位置:母球后方偏移一段距离
        const initialOffset = 200 * this.scaleX;
        this.x = cueball.x - initialOffset;
        this.y = cueball.y;
    }
}

关键说明

  • 不用依赖RotateAround方法,直接通过Math.cos/Math.sin计算位置更灵活,能精准控制球杆与母球的距离。
  • setOrigin(0, 0.5)确保杆头是旋转原点,配合位置计算,刚好让杆头贴住母球,实现绕母球圆周旋转的效果。
  • 偏移距离需要根据你的球杆素材实际长度和缩放比例调整,确保杆头位置准确。

内容的提问来源于stack exchange,提问作者GreasyJam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 19:25:23