Pau

Enemy must changes direction when arrive to the end of platform

Recommended Posts

Hello,

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:

https://pablomonteserin.com/apuntes/8-enemigo-inteligente-2

 

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)
console.log(nextY)

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

 

8-enemigo-inteligente-2.zip

Share this post


Link to post
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.

Share this post


Link to post
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).

Share this post


Link to post
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.

Guest
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.

Loading...

  • Recently Browsing   0 members

    No registered users viewing this page.