Jump to content

Create Objects From Tilemap


onmyown
 Share

Recommended Posts

Hello, I have a tiled map with an object layer but am unsure how to add them...

 

I have this JavaScript:

 

var createItems = function(type) {
    //create items
    items = game.add.group();
    items.enableBody = true;
    var item;    
    result = findObjectsByType(type, map, 'Object Layer 1');
    result.forEach(function(element){
      createFromTiledObject(element, items);
    });
  };
  //find objects in a Tiled layer that containt a property called "type" equal to a certain value
  var findObjectsByType = function(type, map, layer) {
    var result = new Array();
    map.objects[layer].forEach(function(element){
      if(element.properties.type === type) {
      console.log("Found a " + type);
        //Phaser uses top left, Tiled bottom left so we have to adjust
        //also keep in mind that the cup images are a bit smaller than the tile which is 16x16
        //so they might not be placed in the exact position as in Tiled
        element.y -= map.tileHeight;
        result.push(element);
      }      
    });
    return result;
  };
  //create a sprite from an object
  var createFromTiledObject = function(element, group) {
    var sprite = group.create(element.x, element.y, element.properties.sprite);
 
      //copy all properties to the sprite
      Object.keys(element.properties).forEach(function(key){
        sprite[key] = element.properties[key];
      });
  }

createItems("coin");

 

But it doesn't fire on account of getting neither no console log nor coins being rendered. Please help!

Link to comment
Share on other sites


    map = game.add.tilemap('map');

    map.addTilesetImage('ground_1x1');
    map.addTilesetImage('walls_1x2');
    map.addTilesetImage('tiles2');

    map.setCollisionBetween(1, 12);

    layer = map.createLayer('Tile Layer 1');

    layer.resizeWorld();

    game.physics.startSystem(Phaser.Physics.ARCADE);

    //  Here we create our coins group
    coins = game.add.group();
    coins.enableBody = true;

    //  And now we convert all of the Tiled objects with an ID of 34 into sprites within the coins group
    map.createFromObjects('Object Layer 1', 34, 'coin', 0, true, false, coins);

    //  Add animations to all of the coin sprites
    coins.callAll('animations.add', 'animations', 'spin', [0, 1, 2, 3, 4, 5], 10, true);
    coins.callAll('animations.play', 'animations', 'spin');

You don't need to write custom code to create the objects from within an object layer, phaser takes care of this.

Please see the example here: http://phaser.io/examples/v2/tilemaps/create-from-objects

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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