I'm remaking 8ball pool in Phaser for fun and am in the process of setting up the aiming of the cue/cueball. I currently have the cue rotating around the center point of the cueball on mouse movement:
create() {
// Spawn in pool table
this.setupTable();
// Initialize cueball
this.cueball = new Ball(this, 847, 400, 'ballsAndCue', '14ball.png', true);
// Initialize cue
this.cue = new Cue(this, 800, 400, 'ballsAndCue', 'cue.png', this.cueball);
// Set cue rotation to follow cursor on cursor movement
this.input.on('pointermove', function (pointer) {
this.angle = Phaser.Math.Angle.BetweenPoints(this.cue, pointer);
this.cue.rotation = this.angle;
}, this);
}
However I want the cue to rotate around the whole cue ball. I've tried supplying this.cue
to Phaser.Actions.RotateAround()
/Phaser.Actions.RotateAroundDistance()
but couldn't get them to work. Looking at Phaser 2, they had a pivot you could set but I'm not seeing anything similar other than setOrigin()
, which I have already used to have the cue spin around the tip.
Cue class:
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);
}
}
How can I get it so the cue rotates around the circumference of the cueball?
A easy/fast solution is to put the cue into a phaser container (with the desired relative distance to the ball) and use the container as a "pivot" and just rotating it, just set the container position to the x
and y
coordinate of the cueball.
Here a Demo showcasing this solution:
(With some extra sweet cue pushing motion)
The demo doesn't use sprites, but it solution works in the same way with sprites and images
document.body.style = 'margin:0;';
var config = {
type: Phaser.AUTO,
width: 536,
height: 183,
scene: {
create
}
};
function create () {
let ball = this.add.circle(200, 90, 10, 0x6666ff);
let pivot = this.add.container(200, 90);
let cue = this.add.rectangle(10, 0, 200, 4, 0xffffff)
.setOrigin(0, .5);
pivot.add(cue);
// the following two tweens are only to showcase the example
this.tweens.add({
targets: pivot,
rotation: -Math.PI * 2,
duration: 3000,
repeat: -1
});
this.tweens.add({
targets: cue,
x:{
from: 10,
to: 80,
},
duration: 500,
repeat: -1,
yoyo: true
});
}
new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser@3.55.2/dist/phaser.js">
</script>
Or you could simply just add some transparent pixel (with the desired offset) to the image, BUT this is very limiting and only good if you don't need to move the cue in any other way then rotating it.