Reputation: 611
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?
Upvotes: 1
Views: 3108
Reputation: 14730
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
)
img.displayWidth = 100;
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>
Upvotes: 3