VincentB Posted October 5, 2018 Share Posted October 5, 2018 Hi guys, I have been struggling with the text alignment within a container in order to create a bubble dialog box. I create a container, add graphics inside and then text. However I cannot understand how to have the text centered within the container. I saw in an old post something like label.setOrigin(0.5); which do no work in this case. Here is the result on Chrome followed by the result on a mobile device (emulated with Chrome, just for information) Since more code is always better, I isolated this particular example in the Bubble-sample.zip file attached Just run "npm install" and "npm run start" then go to http://localhost:8080/ and click in the canvas. I'm looking for a global solution that would center some text within a container, independently of the number of lines, I'm certainly missing a big concept here... ? Bubble-sample.zip Link to comment Share on other sites More sharing options...
jamespierce Posted October 5, 2018 Share Posted October 5, 2018 @VincentB If you want to center text inside an image, sprite, or graphics, you have to do this: // Create image with this.add.image() or this.add.sprite() // Create text with this.add.text(); text.setOrigin(0.5); text.setX(img.getCenter().x); text.setY(img.getCenter().y); But there is a problem with your example in particular: The center-point of the image is not where you want your text to be because of the 'spike' going from the rectangle to the talking NPC. So in this case, what you need to do is subtract the height of the 'spike' from the y-position. (If that 'spike' was sticking out in another direction, you'd need to adjust that coordinate accordingly.) Anyways, let's stick with your example: let offset = 21; // Height of the 'spike' going out of your speech bubble text.setX(img.getCenter().x); text.setY(img.getCenter().y - offset); Link to comment Share on other sites More sharing options...
VincentB Posted October 5, 2018 Author Share Posted October 5, 2018 Thanks @jamespierce for the fast answer, I was missing the X and Y coordinates and it now works. For my particular case there is no image but instead a graphic object. Since I added it myself I know its size, and I do not need to worry about the bubble spike. The fix was to add the following: // place the text in the center of the bubble this.textObject.setOrigin(0.5); this.textObject.setX(containerWidth / 2); this.textObject.setY(containerHeight / 2); Pretty simple... but I needed the guidance, thanks for that ! ? Hopefully this will help someone else in the future so here is attached the version with the 3 lines added, Bubble-sample-fixed.zip Bubble-sample-fixed.zip blackhawx 1 Link to comment Share on other sites More sharing options...
jamespierce Posted October 5, 2018 Share Posted October 5, 2018 @VincentB Awesome work! Link to comment Share on other sites More sharing options...
Recommended Posts