'Phaser 3: Change width of sprite relative to height
I'd like to be able to change the height of my sprite to fit into a menu, however when I change the height with sprite.displayHeight = menu.height, it's width won't scale along and it will be stretched/squashed.
Is there a way to scale the width relative to the height, to keep the sprite's original ratio?
Solution 1:[1]
I don't know any special function, that does this out-of-the-box, BUT you can achieve this, with only one extra line of code. No extra calculation needed.
(this works also with the displayHeight)
- First set the width of the image:
img.displayWidth = 100; - Then set the scale of the Y axis (since the X-axis is set through setting the
displayWidth):img.scaleY = img.scaleX;
Here the documentation, that points this out:
"...The displayed width of this Game Object.
This value takes into account the scale factor.
Setting this value will adjust the Game Object's scale property..."
Here a working demo:
// Minor formating for stackoverflow
document.body.style = "display: flex;flex-direction: column;";
function preload ()
{
this.load.image('img', 'https://labs.phaser.io/assets/pics/contra3.png');
}
function create ()
{
let imgOrig = this.add.image(100,100, 'img');
let img = this.add.image(320, 100, 'img');
img.displayWidth = 100;
// extra line to scale the image proportional
img.scaleY = img.scaleX;
}
var config = {
type: Phaser.AUTO,
width: 536,
height: 160,
scene: {
preload: preload,
create: create
}
};
var game = new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/phaser.js"></script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
