I’m trying to center a circle in a given rectangle. One of the approaches to do the job could be graphics working with Phaser.Display.Align.In.Center and I’m having trouble doing that. Here is the code.
class BootScene extends Phaser.Scene {
constructor() {
super({
key: 'BootScene'
});
}
create() {
let btn = this.add.rectangle(800, 600, 200, 150, '#000').setOrigin(1);
let txt = this.add.text(0, 0, 'click');
Phaser.Display.Align.In.Center(txt, btn, );
let graphics = this.add.graphics({
x: 750,
y: 550
});
var shape = new Phaser.Geom.Circle(0, 0, 24);
graphics.fillStyle(0xff0000, 1);
graphics.fillCircleShape(shape);
//Phaser.Display.Align.In.Center(graphics, btn);
}
}
var config = {
width: 800,
height: 600,
backgroundColor: '#555',
scene: [BootScene]
}
var game = new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser@3.55.2/dist/phaser.js"></script>
There are 3 visual parts in the code above: the btn rectangle, the txt text and the graphics.
Phaser.Display.Align.In.Center works well with btn and txt.
graphics works well with btn using
this.add.graphics({
x: 750,
y: 550
});
However, if I uncomment the following line below out
Phaser.Display.Align.In.Center(graphics, btn);
the graphics is gone, not matter I set the config as { x: 750, y: 550 } or { x: 0, y: 0 }.
What am I missing?
I know I could use something like
let circle2 = this.add.circle(0, 0, 32, 0xf00000);
Phaser.Display.Align.In.Center(btn_circle, circle2);
I’d just like to know why it doesn’t work when I combine graphics and Phaser.Display.Align.In.Center together.
>Solution :
I’m not 100% sure why the graphics object is not shown, has maybe to do with the size or so (I will still have to investigate abit)
But here is a possible solution:
- You simply generate a texture out of the
graphicsobject, with the functiongenerateTexture - Align that function with the
btn - I just added a
setDepthcall to thetxtobject so it would be visible
class BootScene extends Phaser.Scene {
constructor() {
super({
key: 'BootScene'
});
}
create() {
let btn = this.add.rectangle(300, 175, 200, 150, '#000').setOrigin(1);
let txt = this.add.text(0, 0, 'click');
Phaser.Display.Align.In.Center(txt, btn );
let graphics = this.make.graphics({
x: 24,
y: 24,
});
var shape = new Phaser.Geom.Circle(24, 24, 24);
graphics.fillStyle(0xff0000, 1);
graphics.fillCircleShape(shape);
graphics.generateTexture('gCircle', 48, 48);
let image = this.add.image(200, 200, 'gCircle');
Phaser.Display.Align.In.Center(image, btn);
// only to make the Button visible
txt.setDepth(2);
}
}
var config = {
width: 400,
height: 200,
backgroundColor: '#555',
scene: [BootScene]
}
var game = new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser@3.55.2/dist/phaser.js"></script>