GithubHelp home page GithubHelp logo

englercj / phaser-tiled Goto Github PK

View Code? Open in Web Editor NEW
288.0 24.0 31.0 985 KB

A tilemap implementation for phaser focusing on large complex maps built with the Tiled Editor.

License: MIT License

JavaScript 99.42% CSS 0.21% HTML 0.37%

phaser-tiled's Introduction

Phaser Tiled

This is a replacement for the tilemap implementation in the Phaser game framework. The purpose of this plugin is to optimize the tilemaps for large complex maps built with the Tiled Map Editor.

This plugin optimizes the rendering of large scrolling tilemaps. It also adds support for many more Tiled features and lots of advanced functionality. You can read Why use this plugin? below for more details.

Note: The recommended version of Tiled for use with this plugin is v0.15. Any other version is not officially supported.

Usage

Simply download the phaser-tiled.js script from the latest release and include it on your page after including Phaser:

<script src="phaser.js"></script>
<script src="phaser-tiled.js"></script>

Javascript

After adding the script to the page you can activate it by enabling the plugin:

game.add.plugin(Phaser.Plugin.Tiled);

Then you can add a Tiled map to your game like this:

// By using the built-in cache key creator, the plugin can automagically
// find all the necessary items in the cache.
// The params are (map-key, type, tiled-name). The `key` is an arbitrary key
// you make up to identify the map it belongs to. The `type` is the type of
// resource it is loading. The `tiled-name` is for layers, the name should match
// the name of the layer in the map.
var cacheKey = Phaser.Plugin.Tiled.utils.cacheKey;

// load the tiled map, notice it is "tiledmap" and not "tilemap"
game.load.tiledmap(cacheKey('my-tiledmap', 'tiledmap'), 'assets/levels/tilemap.json', null, Phaser.Tilemap.TILED_JSON);

// load the images for your tilesets, make sure the last param to "cacheKey" is
// the name of the tileset in your map so the plugin can find it later
game.load.image(cacheKey('my-tiledmap', 'tileset', 'tileset1-name'), 'assets/levels/tileset1.png');
game.load.image(cacheKey('my-tiledmap', 'tileset', 'tileset2-name'), 'assets/levels/tileset2.png');

// if you have image layers, be sure to load those too! Again,
// make sure the last param is the name of your layer in the map.
game.load.image(cacheKey('my-tiledmap', 'layer', 'layer-name'), 'assets/levels/layer.png');

////////////
// Later after loading is complete:

// add the tiledmap to the game
// this method takes the key for the tiledmap which has been used in the cacheKey calls
// earlier, and an optional group to add the tilemap to (defaults to game.world).
var map = game.add.tiledmap('my-tiledmap');

That can get pretty heavy, and hardcoding what to load and how to name it can stink! Luckily, there is an easier way to handle it. Instead of hard-coding what the tilemap should load and be named, this plugin has a gulp task that can generate a Phaser Asset Pack that describes what and how to load the tiledmap. If you have this pack it becomes trivial to load and create a tiledmap:

// the key will be the filename of the map without the extension.
game.load.pack('my-tiledmap', 'assets/levels/tilemap-assets.json');

////////////
// Later after loading is complete:
var map = game.add.tiledmap('my-tiledmap');

Wow, that was a lot easier! You can find out more about the generator on it's GitHub page.

Typescript

Download the phaser-tiled.d.ts and add it to your project. (The file is located in the typescript folder) You also need the normal phaser-tiled.js file.

First of all you need to make sure you add a reference to the phaser and phaser-tiled typescript files.

/// <reference path="lib/phaser.d.ts"/>
/// <reference path="lib/phaser-tiled.d.ts"/>

Now you need to load the plugin. This needs to be done in the preload function.

//This is in the preload function
this.game.add.plugin(new Tiled(this.game, this.game.stage));

//Now you need to load the tiledmap. Notice that it says tiledmap.
var cacheKey = Phaser.Plugin.Tiled.utils.cacheKey;
//Since you can't add methods to existing classes in typescript you need to cast to any.
(<any>this.game.load).tiledmap(cacheKey('myTiledMap', 'tiledmap'), 'maps/myTiledMap.json', null, Phaser.Tilemap.TILED_JSON);

//Now you need to load the tilesets.
this.game.load.image(cacheKey('myTiledMap', 'tileset', 'Grass'), 'images/tilesets/Grass.png');
this.game.load.image(cacheKey('myTiledMap', 'tileset', 'Dirt'), 'images/tilesets/Dirt.png');

// You can load image layers like this:
this.game.load.image(cacheKey('myTiledMap', 'layer', 'yourLayerName'), 'images/imageLayers/layer.png');
//The last parameter should be the name of your layer in your tiled map

Now the loading part is done and we will continue after the loading is complete.

//This is normally in the create method
//Make sure you cast it to any again.
var map = (<any>this.game.add).tiledmap('myTiledMap');

Physics

This plugin comes with a couple ways to implement physics for your games. Right now the only officially supported engine is p2.js, but hopefully arcade and others can join the party soon (need it now? submit a PR!).

Using the object tools

To create the physics bodies based on a tilemap, the simplest way is to create an object layer in Tiled Editor and use the object tools to draw physics. You can use the rectangle, ellipse, polygon, or polyline tools. The only caveats are that circles (not ellipses) are supported so height and width of the ellipse must be the same, and if you use the polyline tool be sure to close the path to make a convex polygon!

Here is how you can convert your objects into collision bodies:

var map = game.add.tiledmap('tilemap-key');

game.physics.p2.convertTiledCollisionObjects(map, 'objectlayer-name');

That is it! All the objects in the layer named objectlayer-name will be converted to p2 physics bodies and added to the simulation.

Using collidable tiles

The second method is to set the collides custom property on tiles in a tileset to true. This tells the engine that that specific tile is collidable wherever it is in the map, and a body will be created for it.

Here is how you can convert your collidable tiles into collision bodies:

var map = game.add.tiledmap('tilemap-key');

game.physics.p2.convertTiledmap(map, 'tilelayer-name');

That is it! All the collidable tiles in the layer named tilelayer-name will be converted to p2 physics bodies and added to the simulation. This will also try to combine bodies that are adjacent on the same X axis into a single body to reduce the total number of bodies that are created. This algorithm can (and should) be much improved.

Why use this plugin?

Here are some features this plugin has that Phaser doesn't, or that this plugin tries to do better:

  1. Faster render times
  2. Support for Tiled XML format
  3. Support for tile flipping
  4. Support for animated tiles (added in Tiled v0.10.0)
  5. Automatic layer creation from tiled data
  6. Automatic tileset creation from tiled data

Show me the performance!

Using a large test map with 256x256 tiles, each 16x16 pixels, and 3 layers of them. phaser-debug gives me this performance graph for the core phaser tilemap implementation:

Slow

The spikes you see there are when I pan around the map. Using the same map with this plugin I get this:

Fast

Supported custom properties

Tilemap

None, yet.

Tileset

None, yet.

Tileset Tile (specific tile in the tileset)

  • collideLeft - true will make this tile collide on the left
  • collideRight - true will make this tile collide on the right
  • collideUp - true will make this tile collide on the top
  • collideDown - true will make this tile collide on the bottom
  • collides - true will set all collision sides to true, if that collision side doesn't have a specific override
  • blendMode - string of the blendMode constant to use for this tile (e.g. 'NORMAL')

Tile Layer

  • batch - true will place tile sprites into a SpriteBatch container.

Object Layer

  • batch - true will place object sprites into a SpriteBatch container.
  • blendMode - string of the blendMode constant to use for all objects in this layer (e.g. 'NORMAL').

Object Layer Object (specific object in the layer)

  • blendMode - string of the blendMode constant to use for this object (e.g. 'NORMAL')
  • texture - string of the texture to load from the cache, usually the URL you would load the texture with.
  • collides - true/false whether this object is collidable, falls back to the tileset tile collides property.
  • sensor - Makes the physics shape a sensor shape when collides is true.
  • anchor - A custom anchor override for a tile in array format, e.g. "[0,1]"

Image Layer

None, yet.

Tiled features not yet implemented:

  1. Object layers
  2. Image layers
  3. Multi-image tilesets

Phaser Tilemap API features still needed:

Layer Properties:

  • tileColor
  • wrap
  • scrollFactor

Map Methods:

  • setTileIndexCallback
  • setTileLocationCallback
  • setCollision
  • setCollisionBetween
  • setCollisionByExclusion
  • setCollisionByIndex
  • copy
  • paste
  • swap
  • swapHandler
  • forEach
  • replace
  • random
  • shuffle
  • fill

Object Layer:

  • object spritepool to pull custom object from
  • Test, only minimally implemented right now

Image Layer:

  • Completely unimplemented

General:

  • Rerender on resize/rescale seems off
  • Tile render debug stuff (edges, physics, etc)
  • Memory optimizations

phaser-tiled's People

Contributors

amadeus avatar englercj avatar jimvliet avatar lozy219 avatar mannyc avatar photonstorm avatar vrecluse avatar weedshaker avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

phaser-tiled's Issues

Very poor performance with a lot of collisions

capture

For example, just having that many collision bodies destroys performance and it drops to around 20 fps

This is obviously because of p2 physics (game.physics.p2.convertTiledmap(mymap, 'Collision');)

Maybe there is another way to handle a lot of these collisions?

Also, how would we would utilize this function?

Tile.prototype.setCollisionCallback = function (callback, context) {

    this.collisionCallback = callback;
    this.collisionCallbackContext = context;

};

Loop through the bodies and then apply the setCollisionCallback method? For example, if you have a water tile and want the character to swim. I just think the documentation is lacking but I don't really know the code well enough to help, I'm still learning but I definitely think this library's documentation is not giving the library justice, there are so many features here and not a lot of examples to illustrate them :( I also am receiving a 70%+ performance increase from the stock Phaser renderer, this library is amazing but I think it's potential to be utilized 100% is slightly hindered by lack of examples

Phaser.Cache.getPixiBaseTexture

phaser 2.6.0
Phaser.Cache.getPixiBaseTexture has now been removed, as the Pixi Cache isn't used internally anywhere any longer.

Error spacing tilesets

Sorry for my English ... I wonder if there is any solution for when my tilesets have different spacing of 0 ... Because it generates the following error: " Texture Error : frame does not fit inside the base Texture dimensions" .

this.game.physics.p2.convertTiledmap

Hi,

again, need to say how awesome the fps performance is with this. I am very happy! ;-)

But I just can't get it to work that tiles collide. I set collides = true to the tiles I am using in Tiled:

"tileproperties":
            {
             "14":
                {
                 "collides":"true"
                },

But the Tilelayer outputs this:

bodies[...].collidesWith: Array[0]

can't it be that we need to activate something like "map.setCollisionBetween(1, 12);" ?

There is also a problem with the for loop at L:1927. My tiles objects do not start with [0]... but actually with [2], obviously the loop fails there since it tries to access an object key of which the object does exist for. I suggest to check: "if(layer.tiles[y]){"

Thank you for your help.

Prerendering Chunks

An optimization should be to prerender static layers of the tilelayers to larger chunked textures.

This is really more help to canvas so it only renders a couple sprites each frame instead of however many there need to be on the screen based on tile size. For WebGL this might actually hurt performance in some cases since we are no longer using the same texture and just batching the sprites.

User should be allowed to turn on prerendering for a layer regardless of renderer, and also turn on prerendering only if the renderer is canvas.

New update is missing nearly all semicolons on the end of a line?

So I just noticed that the new update is missing a lot of semicolons:

function allocate (that, length) {
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    // Return an augmented `Uint8Array` instance, for best performance
    that = new Uint8Array(length)
    that.__proto__ = Buffer.prototype
  } else {
    // Fallback: Return an object instance of the Buffer class
    that.length = length
  }

  var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1
  if (fromPool) that.parent = rootParent

  return that
}

function checked (length) {
  // Note: cannot use `length < kMaxLength` here because that fails when
  // length is NaN (which is otherwise coerced to zero.)
  if (length >= kMaxLength()) {
    throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
                         'size: 0x' + kMaxLength().toString(16) + ' bytes')
  }
  return length | 0
}

function SlowBuffer (subject, encoding) {
  if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding)

  var buf = new Buffer(subject, encoding)
  delete buf.parent
  return buf
}

As you can see none of the line endings have a semicolon

Game world boundaries not obeyed

Without a tileset for collisions, the only collisions appear to be North and West boundaries. The p2physics enabled sprites are not limited by the game.world.setBounds(0, 0, 1600, 1200);

Calls that are supposed to add this feature also fail:
game.physics.p2.setBoundsToWorld(true, true, true, true, false); //fails

Using phaser-tiled current and Phaser 2.2.2 I haven't been able to come up with a hack that forces the sprite to stay in the world. I've even attempted a keyboard input hack, but also without success:
if (this.cursors.down.isDown)
if (this.player.y < game.world._height-17 )
this.player.body.moveDown(150);.

Without the phaser-tiled system for map loading, the game.world boundaries and walls work normally.

Complete Test Suite

Need to create a map test suite that uses all the tiled features to test with this repo. Have one in the works, should upload it soon.

Incorrect Reference in TileLayer.getTiles

These lines:

if (width > this.layer.widthInPixels)
{
    width = this.layer.widthInPixels;
}

if (height > this.layer.heightInPixels)
{
    height = this.layer.heightInPixels;
}

are throwing an error because the scope is in the layer. I corrected this by changing it to:

if (width > this.widthInPixels)
{
    width = this.widthInPixels;
}

if (height > this.heightInPixels)
{
    height = this.heightInPixels;
}

creating an empty tiledmap fails

I would like to not use tiled to build my tilemap but use my own procedural generator hence I do:

game.add.tiledmap();

this fails because the check for data === null fails after the parser. it returns undefined instead of null. The getEmptyData function in the parser that is called causes this. It builds a map object but that object it not returned from the function.

Hope this is clear enough.

Parallax Layers

Right now there is no support for layers that scroll at different speeds, need to implement scrollFactor for layers and get that working. Also have custom properties so they can be set from Tiled.

Add multi-image tileset support

A tileset from tiled can be a multi-image tileset, where each tile in the tileset is a separate image. This is not currently supported.`

Object spritepool to pull custom objects from

Right now only base objects are spawned by ObjectLayers. There should be a way to spawn any custom game object you've created.

This was implemented in grapefruit via a pool that you could add prototypes to for the layer to create from. Potentially implement something similar here.

Can't find phaser-tiled.js file?

For some strange reason I am having trouble finding the phaser-tiled.js you speak of in the readme, I'm guessing I'm just missing it somehow? Thanks!

Typescript issues and setting up the plugin

Hey all,

I'm having a few issues with phaser-tiled and typescript.

First the typescript definitions conflict with p2.d.ts, pixi.d.ts, and with phaser.d.ts.

My next issue is adding the plugin to the game and getting it to mesh with the loader.

this.add.plugin(Phaser.Plugin.Tiled);
I get typeof Tiled is not assignable to parameter of type 'Plugin'. Property 'active' is missing in type 'typeof Tiled'

Digging around in englercj's phaser fort of "Link to the Past", I found this way:

this.add.plugin(new Phaser.Plugin.Tiled(this));

When I do this is needs a reference to the game and to a display object.
this.add.plugin(new Phaser.Plugin.Tiled(this.game, this.stage));

This makes VS Code happy, but it leads to the next issue.
this.load.tiledmap(cachKey('map', 'tiledmap'), 'assets/map.json', null, Phaser.Tilemap.Tiled_JSON);

Gives an error saying that tiledmap DNE on type 'Loader'
and I also get a supplied parameters error for cacheKey saying that parameters do not match any signature of call target.

Here is a link to my source code. I add the plugin in the Boot.ts file, and try to load everything in the Preload.ts File

https://bitbucket.org/wgronewold/tilemapzoom_scalegroup/src

I'm currently using node.js to serve app to localhost and the typescript compiles to the game.js file in the bin directory.

Any help is appreciated.
Thanks

Tile-Sprite objects are too "fat"

One issue with distinct Tile-as-Sprite objects is that even a little change really adds up. Not an issue on a desktop, but it matters in a more memory-constrained environment.

For instance, a Phaser.Sprite weighs in at a shallow size of 500+ bytes in Chrome (and enough tile-specific information stored without specific consideration adds about 200 additional bytes) - and Chrome is pretty efficient in how it handles objects and "private classes". Thus the memory foot-print for a 256x256 map (having each Tile as a Sprite) is a very conservative ~50MB+ of memory. A 400x400 map would be in excess of 110MB with each Tile as a Sprite.

To combat this a Tile should fundamentally be a "thin" object - perhaps one that can be/is mostly encoded in a [typed/dense] array and/or a few ancillary object look-ups as required. The amount of actual data in a Tile object is only a few tens of bytes (easily less than 1/10th of the data required by a "fat" Sprite, although even less is required).

These "thin" tile objects would only be fetched (to fatter display Sprites) when displayed. The downside is the loss of truly ad-hoc objects (which arguable is not well-suited to a Tile anyway).

Tileset with margin & spacing bug

Hi,

When Tileset has margin & spacing between tiles, phaser-tiled doesn't calculate well the numTiles attribute. Changing "this.numTiles" in Tileset constructor works well for me.

In Tileset.js :
this.numTiles = this.multiImage ? tileTextures.length : new Phaser.Point(
Phaser.Math.floorTo((this.baseTexture.width - this.margin) / (this.tileWidth - this.spacing)),
Phaser.Math.floorTo((this.baseTexture.height - this.margin) / (this.tileHeight - this.spacing))
);

Thanks!

game.physics.p2.convertTiledmap() not working properly

Thank you for coding this plugin. I'm pretty psyched to see it working. I have a working Phaser Tiled map that I'm trying to convert to using this plugin in hopes for some smoother scrolling.

First small issue, you have a typo in your "Usage" section. In the line: map = game.add.tiledmap('my-tilemap'), you need to change the key text to "my-tiledmap". I cut/pasted your code and it took a bit of debugging to figure this out.

Second larger issue: game.physics.p2.convertTiledmap() doesn't work fully. All of my tiles in Tiled have custom property: collides = true. I also tried collides = 1, neither works. My ball moves through nearly every tile as if it's not there. It will occasionally collide with what seems like a random tile and sometimes it collides with an invisible tile in blank space.

So far it does seem to scroll more smoothly. Which is awesome. However, I'll need the tile collisions to work before I can actually use it.

Thanks again for the plugin work so far! :-)

Better body combine algorithm

I thought I'd make a seperate issue for this, since it didn't seem like you saw it in the main issue.

Anyway I made my own kind of algorithm recently and while it's not perfect, it works alright. Result is here: http://jimvliet.github.io/HTML5-Game/objectConverter

The code is in this file: https://github.com/JimVliet/HTML5-Game/blob/master/scripts/functionFile.ts

It works like this: It starts at the top left and goes to the bottom right. Everytime it finds a solid object which isn't already used it will create a rectangle with the largest possible area from that position. Then the tiles used in that rectangle won't be able to be used again.

If you have any questions, feel free to ask.

This is my current game: http://jimvliet.github.io/HTML5-Game/ in which this is used

Add TypeScript Dist

It would be very useful to have a TypeScript version of your library as well!

Support Tile Collision Editor

As I understand it the new way to handle collisions in Tiled is to draw objects on the tiles themselves (not as a separate layer) with the Tile Collision Editor. It would be fantastic if this plugin supported that. :)

Improve body combine algorithm

When converting a tilemap layer into physics bodies the current algorithm will combine adjacent bodies on an X axis, resulting in bodies which is less than one-per-tile but still can present problems with performance or edge sticking (by stacking strips).

This algorithm should really combine all adjacent bodies into a single polygon.

Isometric and some questions

I've been looking into adapting phaser-tiled to support isometric tiles. I've hacked in some changes which have been working so far. I was looking into doing it using Phaser's implementation but the way this plugin did its rendering made more sense to me.

My general thinking is to just adapt the various points to cope with isometric tiles/coordinates. Generally this consists of:

  • When placing a tile that at MX,MY (map x, map y) project that tile onto the world via a function (currently it just multiplies the MX by the map tile width etc).
  • Update the render region to support an isometric region. This seems like the iffiest bit, but I think it can be done by changing the render region from x,y,w,h to a set of four coordinate pairs. Orthographic would assume it's a standard rectangle, isometric would do its own calculations.
  • I think the _renderRight etc functions can be adapted, in so far as if you're scrolling right then there is a limited set of tiles that will be scrolled into view, they just won't be as simple as grabbing a map column. The pool size might be tricky to size using the current method, as the number of edge tiles can change, but it's easy to work out how many can possibly be on the screen + buffer.
  • Map width in pixels etc will have to support iso, this is quite simple.
  • Render order will probably have to be supported, as 2.5d is very common in iso games. I'd plan on doing a basic approach at first, assigning a number to each tile as they're put on the screen and letting the groups sort function sort it out from there. It seems likely that this can be improved seeing as we can work it out during the _renderRight etc functions but I'd consider that step 2, and might not be necessary. If sorting turns out to be slow it could be opt-in.
  • I haven't considered physics at all yet.

Thoughts on the above strategy and its sanity?

Also, while reviewing the code to get to grips with it, I've come across some things I don't fully understand yet. It seems that this was originally based on Phaser's Tilemap implementation, and it seems to still have some leftover code. Mainly this seems to be some overlapping of functionality between the classes. For instance, I'm not sure what the Tile class is doing. It isn't used by the Tilelayer class, only by the Tilemap.putTile method, which isn't actually called by the plugin itself. There seems to be some very similar looking code in the Tilelayer class and the Tile class, and it feels like the Tile class perhaps should be there at all (or should be used by Tilelayer instead of it using Sprites). I don't want to make too many potentially far reaching changes around this, particularly when I don't understand all of the plugins uses, but if we're implementing iso then the less code that has to be considered the better.

I know that performance is a concern. Do you have a base tileset/map we can use as a benchmark?

Also, is the general thinking to support Tiled maps + additional features, or to be a general Tiling engine that happens to support Tiled maps?

Anyway, just starting a conversation about all this.

is this plugin compatible with phaser version 2.3.0

i cant use use it

here is my code :
tile map created with Tiled and works good with phasers default tile map renderer(but its slow when i use it with camera.follow )

var layer;
var map;
var gameState = {

    init:function(){

        /*
        game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
        game.scale.pageAlignHorizontally = true;
        game.scale.pageAlignVertically = true;
        game.scale.setScreenSize(true);
        */

    },

    preload : function () {

        game.add.plugin(Phaser.Plugin.Tiled);
        var cacheKey = Phaser.Plugin.Tiled.utils.cacheKey;

        game.load.atlasJSONHash('ourgirl','assets/sprites.png','assets/sprites.json');
        game.load.image('background','assets/colored_desert.png');
        game.world.setBounds(0, 0, 3840, 896);
        //game.load.tilemap('MyTilemap', 'assets/level1test.json', null, Phaser.Tilemap.TILED_JSON);
        game.load.tiledmap(cacheKey('MyTilemap', 'tiledmap'), 'assets/level1test.json', null, Phaser.Tilemap.TILED_JSON);
        //game.load.image('tiles_spritesheet', 'assets/tiles_spritesheet.png'); 
        game.load.image(cacheKey('MyTilemap', 'tileset', 'tiles_spritesheet'), 'assets/tiles_spritesheet.png');
        game.load.image(cacheKey('MyTilemap', 'layer', 'Tile Layer 1'), 'assets/tiles_spritesheet.png');


    },

    create : function(){


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

        background = game.add.tileSprite(0, 0, 30920, 950, 'background');

        game.add.plugin(Phaser.Plugin.Debug);

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

        var map = game.add.tiledmap('MyTilemap');

        /*
        map.addTilesetImage('tiles_spritesheet', 'tiles_spritesheet');

        map.setCollisionBetween(103,104);
        map.setCollisionBetween(44,68);
        map.setCollisionBetween(122,124);

        /*
        map.setCollision([128,68,80,44,12,147,134,78,124],true,layer,true);
        */

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

        layer.resizeWorld();

        //layer.wrap = true;
          */      
        girl = game.add.sprite(1200,0,'ourgirl');

        girl.animations.add('rightrun',[12,13,14],10,true);
        girl.animations.add('rightidle',[0,1,2],5,true);
        girl.animations.add('rightjump',[11],5,true);

        //girl.width=girl.width/4;
        //girl.height=girl.height/4;

        cursors=game.input.keyboard.createCursorKeys();

        game.physics.enable([girl],Phaser.Physics.ARCADE);
        game.physics.arcade.gravity.y = 450;
        girl.body.collideWorldBounds = true;

        game.camera.follow(girl);
    },

    update:function(){

        game.physics.arcade.collide(girl, layer);

        this.checkmood();
    },

    checkmood:function(){

            charactermoving = false;
            girl.body.velocity.x=0;
            girlBodyOnFloor=girl.body.onFloor();

            if (cursors.right.isDown){

                girl.animations.play('rightrun');
                background.tilePosition.x = 0.5;
                girl.body.velocity.x = 350;
                charactermoving = true;
                girl.scale.setTo(1,1);

            }




            if(cursors.up.isDown){

                if(girlBodyOnFloor){
                    girl.body.velocity.y = -300;
                    charactermoving = true;
                    }
            }

            if(!(girlBodyOnFloor)){
                charactermoving=true;
                girl.animations.play('rightjump');   
            }




            if(cursors.left.isDown){

                if(girlBodyOnFloor){

                    girl.animations.play('rightrun');   

                }

                background.tilePosition.x = -0.5;
                girl.body.velocity.x = -350;
                charactermoving = true;

                girl.anchor.setTo(0.5,0.5);
                girl.scale.setTo(-1,1);
            }



            if(charactermoving==false){
                girl.animations.play('rightidle');
            }

    },



}

Just got Arcade Physics to work

Hey guys, so I got arcade physics to work.

In Phaser-Tiled, under the Tile.prototype method

add:

    if(this.layer.name == 'Collision'){

            //this.visible = false;
            game.physics.enable(this, Phaser.Physics.ARCADE);
            this.body.immovable = true;


    }

Assuming your layer name is Collision

then, simply add this to your update method:

game.physics.arcade.collide(pSprite, mymap.children[7].children);  

Where pSprite represents your player sprite. and the index 7 represents what layer index your Collision layer is under.

I tested the regular stock Phaser tile renderer with arcade physics and this plugin still performs better. I know this is a hacky way of doing it, but it works. And AFAIK setting the tiles to immovable helps with performance too as it doesn't have to check for velocities so that's nice.

setBoundsToWorld

Hi,

first, big thanks for this, really improves the fps... but I have had some issues. Although, one I could resolve and I wanted to let you know through this:

// resize the world to the new size
// TODO: Seems dangerous to do this here, may break if user wants to manually set bounds
// and this reset it each time scale changes.
this.resizeWorld();

Tilelayer.prototype.resizeWorld = function () {
    this.game.world.setBounds(0, 0, this.widthInPixels, this.heightInPixels);
    this.game.physics.p2.setBoundsToWorld(true, true, false, true, false);
};

solves the issue that bounds get lost... maybe it could be nicer implemented though, but I needed a fast fix.

Cheers

Rotated tiles renders on wrong coordinates

The image to the left is how it looks like in Tiled, and the other one how it's rendered by phaser-tiled. The original tile is the spike pointing upwards, the other ones is rotated with their position displaced. I guess this is'nt a general problem, but I can't think of anything special I've done and I don't know where to start to give any hints on what could have gone wrong.

tiledscreenshot

Removing Collision from tile

So I'm using the collision method with my tileset file.

Add a property in Tiled on a specific tile called collision and set to true.

However there are times in game when I want to remove that collision body and I'm struggling to find a way to do this. Please help :).

How can you use this with typescript?

So I was wondering on how to use this with typescript. I am new to web dev, but I have worked with python and java before. Anyway this is my current code:

/// <reference path="lib/phaser.d.ts"/>
/// <reference path="lib/phaser-tiled.d.ts"/>

class RPGame {

    constructor() {
        this.game = new Phaser.Game(800, 600, Phaser.AUTO, 'content', { preload: this.preload, create: this.create });
    }

    game: Phaser.Game;

    preload() {
        this.game.add.plugin(Phaser.Plugin.Tiled);
        this.game.load.pack("test_01", "maps/tilemap-assets.json");
    }

    create() {
        var map = this.game.add.tiledmap("test_01");
    }

}

window.onload = () => {

    var game = new RPGame();

};

This code doesn't work though as you can see here: http://i.imgur.com/xrsR4Rr.png

This is my project folder:
http://i.imgur.com/S0y2WBj.png

All the images I need are in the image folder and the tmx file is referering to them correctly.

So from what I read, it seems like you need to generate an asset-pack? and then load the asset pack. So how would you do this?

Create tiledmap from already loaded assets

I've got a custom asset management tool that I use to load all Phaser assets. Basically, it wraps the Phaser Loader and does a bunch of other stuff, including loading all assets by game state, from an external json file.

My question is, assuming all my assets for the tilemap are loaded, is there an easy way to skip doing the loading using the cachekey utility and just add a tiledmap from already pre-loaded assets?

Readme / tutorial needs an update?

So I am just starting out here, but in the readme it says you need to download the dist/phaser-tiled.jsbut it doesn't seem to exist. So I am just assuming that the phaser-tiled.d.ts will be compiled to that.

Anyways can the readme be a bit more clear on explaining on how to use this?

I am willing to write a tutorial if I find out how to use this.

Is it possible to use simple Arcade Physics collision instead of P2?

I have a layer called 'Collision' and I paint all boxes red for their collision.

As I am looking over the code here, it seems like convertTiledmap is the only supported method, but this creates p2 bodies.

With Phaser's tile renderer there is a method
map.setCollisionBetween(1, 10000, true, collisionLayer); which works, but cannot seem to find something like that

TLDR: Basically I am trying to set the collides property to true on a specific layer named 'Collision', I think I could just go inside the function Tile and put an if statement in there?

[feature request] support tile images larger than map grid (for 2.5D)

currently the plugin will not render overlapping tile images correctly (required for 2.5D)
tiled
render

also the "right up" rendering order from Tiled is required for this layout. (actually i have to do a custom sort on all tiles with tile.z = tile.y - tile.x anyway so rendering order may not matter)

thanks
j

removeTile causes "flashing" screen

When I trigger the removeTile on the Tilemap object the screen flashes for a brief moment.

Line of code I am using is:

    this.map.map.removeTile((Math.floor((this.sprite.x +directionHorizontal)  / 32)), (Math.floor((this.sprite.y + directionVertical) / 32)), 3);

(The .map.map is an unfortunate naming coincidence that I'll refactor soon).

Can be seen here: chat.outriderstudio.com:3000 (Username: test2 // Password: test2)

Use Case:
The removeTile is bound to a keyboard command, face an object somewhere on the map, and hit the 1 key (non keypad) and you'll see the event fire, might have to press 1 a couple of times due to a seperate issue in a onAnimationComplete callback command.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.