Jump to content

unexpected behaviour of sprite in group


eleven
 Share

Recommended Posts

Hi,

 

i'm a webdeveloper but quite new to Phaser and trying to build a litte tower defence game to learn the framework. At the moment i'm trying to detect, if a tower has already been placed at the location where player wants to build a new tower.

The towers are stored in:

this.towers = new Phaser.GameObjects.Group(this);

A new Tower is build like this:

  buildTower(key, x, y) {
    this.towers.create(
      new Tower({
        'scene': this,
        'key': key,
        'x': x,
        'y': y
      })
    );
  }

Tower is a class that extends from Sprite:

export default class Tower extends Phaser.GameObjects.Sprite {

  constructor(config) {

    super(config.scene, config.x, config.y, config.key);

    config.scene.add.existing(this);

    ...
  }

 ...

}

This works fine so far. The towers are placed as expected.

If the player tries to build a new tower i want to check if there is already a tower on that position on the map.

let towersArray = this.towers.getChildren();
for (let i = 0; i < towersArray.length; i++) {
    console.log(towersArray[i].getBounds());
    if (Phaser.Geom.Intersects.RectangleToRectangle(newTower.getBounds(), towersArray[i].getBounds())) {
    ...
    }
}

The output of towersArray.getBounds() ist not what i expected:

Object { x: NaN, y: -16, width: NaN, height: 32 }

If i log the towers group to the console i can see, that the child inside has a missing texture.key and the proper sprite with all the correct values is stored inside x (see screenshot).

 

I hope my explanations are understandable and someone can has an idea what i'm doing wrong here.

Thank You!

 

child_of_towers.jpg

Link to comment
Share on other sites

Looking at the documentation, it seems that Group.create will, by default, create a sprite. You are making a sprite which has, as it's only set value, your Tower object as it's x.

You can either use the add method instead:

this.towers.add(new Tower ({...}) 

OR you can set your classType of the group to Tower instead of Sprite, but I'm not sure how this will interact with your config object. 

https://photonstorm.github.io/phaser3-docs/Phaser.GameObjects.Group.html#classType__anchor

 

Best of luck!

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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