Jump to content

How to correctly extend a sprite with children when anchor.set is used?


Recommended Posts

I am extending phaser.sprite to make a card out of 2 images. The back of the card is positioned in the center of the base card image.

This works as expected until I add anchor.set(0.5) in the game and the child does not get positioned relative to the parent.

Am I adding the child sprite incorrectly?

CardMc = function (game, x, y, cardOuterImage, cardBackImage) {    Phaser.Sprite.call(this, game, x, y, cardOuterImage);    // Add child sprite (back of card)    this.backImage = game.add.sprite(x,y,cardBackImage);    this.addChild(this.backImage);    this.backImage.x = this.width / 2 - this.backImage.width / 2;    this.backImage.y = this.height / 2 - this.backImage.height / 2;    };CardMc.prototype = Object.create(Phaser.Sprite.prototype);CardMc.prototype.constructor = CardMc;

In the game

					// Works correctly					var card = new CardMc(game, 100, 200, 'card', 'card-back');					game.add.existing(card);					card.x = 100;					// Child is not positioned correctly relative to the parent					var card = new CardMc(game, 100, 200, 'card', 'card-back');					game.add.existing(card);					card.anchor.set(0.5);					card.x = 100;

Thanks in advance.

Link to comment
Share on other sites

You need to ensure the backImage gets the same anchor as its parent. A simple way to do this would be to create a new function such as 'setAnchor' on your CardMc object (add this after the CardMc.prototype.constructor line):

CardMc.prototype.setAnchor = function(x, y) {  this.anchor.x = this.backImage.anchor.x = x || 0;  this.anchor.y = this.backImage.anchor.y = y || ( (y !== 0) ? this.anchor.x : 0 );}
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Create New...