Jump to content

Enemy must changes direction when arrive to the end of platform


Recommended Posts


I would like to change the direction of an enemy when it arrive to the end of the platform. I have tried using hasTileAt, but it is not working for me. I think maybe there is a better way.

You have the game code in the attachments, and you can see the same code working in this url:



This is the problematic code:

var nextX = this.x + direccion*(Math.abs(this.width/2) );
nextX=Math.floor(nextX/32)+1 //32px is my tilesize

var nextY = this.y+this.height/2;
nextY = Math.floor(nextY/32)

var nextTile = collisionLayer.hasTileAt(nextX, nextY)
console.log(nextTile + " - " + this.body.blocked.down)
if(!nextTile && this.body.blocked.down){
 this.body.velocity.x *= -1;



Link to comment
Share on other sites

I can't see what's wrong with the code excerpt, but a simple way around the problem would be to use invisible immovable tiles at the end of platforms (one space off of their edge at the walkable height), and set a horizontal bounce property of the moving sprite. So when the sprite hits the invisible tile, it bounces off in the opposite direction.

Link to comment
Share on other sites

It's this line that I worry about the most (using the current live version):

var nextX = this.x + direccion*(Math.abs(this.width/2)+1);

Also, Math.abs() doesn't make sense, unless your sprites have negative width? Is it supposed to be Math.floor()?

I would setup a "nextGridY" set of variables. For nextGridX it would be something like:

var nextGridX = Math.floor(this.x/32) + direccion;

And to make it easier, a setOrigin of (0,1) might help (i.e., so the sprites are bottom-aligned).

Link to comment
Share on other sites


  • Recently Browsing   0 members

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