Jump to content

How to make the enemy auto change direction face to player??


khleug35
 Share

Recommended Posts

I would like to create some platform game,

when the player jumps through the enemy, the enemy will  face the player automatically.

https://jsfiddle.net/sm80pwgt/3/

A.thumb.png.f51d07212331967af42ff0f6b45463ab.png

 

 

B.thumb.png.398d80ae4cf5eaafacb49dfe578693ba.png

 

I try to find the solution, but I think it is not good method

if (player.x > 340)
    {
        enemy.scale.x = -1;
    }else{
        enemy.scale.x =  1;
    }

 

My full code



var game = new Phaser.Game(780, 500, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update});

var crouchFlag = false;


function preload() {

    game.stage.backgroundColor = '#85b5e1';
    game.load.image('enemy', 'http://i.imgur.com/VKpkHXz.png');


    game.load.image('player', 'http://examples.phaser.io/assets/sprites/phaser-dude.png');
    game.load.image('platform', 'http://examples.phaser.io/assets/sprites/platform.png');

}

function create() {

    player = game.add.sprite(100, 200, 'player');
    enemy = game.add.sprite(390, 410, 'enemy');
    enemy.anchor.setTo(0.5,0.5);
    game.physics.arcade.enable(player);

    player.body.collideWorldBounds = true;
    player.body.gravity.y = 800;

    platforms = game.add.physicsGroup();


    platforms.create(0, 450, 'platform');
    platforms.create(400, 450, 'platform');

    platforms.setAll('body.immovable', true);

    cursors = game.input.keyboard.createCursorKeys();
    jumpButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
    jumpButton2 = game.input.keyboard.addKey(Phaser.Keyboard.UP);
}

function update () {

    game.physics.arcade.collide(player, platforms);

    player.body.velocity.x = 0;

    if (cursors.left.isDown)
    {
        player.body.velocity.x = -250;
    }
    else if (cursors.right.isDown)
    {
        player.body.velocity.x = 250;
    }

    if (jumpButton.isDown && (player.body.onFloor() || player.body.touching.down))
    {
        player.body.velocity.y = -600;
    }
/*    
    if (player.x > 340)
    {
        enemy.scale.x = -1;
    }else{
        enemy.scale.x =  1;
    }
/*    
}

 

 

Thank you very much!!!!!!!

Link to comment
Share on other sites

15 minutes ago, Tom Atom said:

Your solution is OK, but you should generalize it like this:


    if (player.x - enemy.x > 0)
    {
        enemy.scale.x = 1;
    } else {
        enemy.scale.x = -1;
    }

... so you are not dependent on fixed (340) position of enemy.

OH!!!!!It work!!! Thank you very much!!

Have a nice day ,Thanks:D

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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