Jump to content

Creating Enimies


Shawn salters
 Share

Recommended Posts

Hello guys I am new to Phaser and I've been following some tutorials. I have just finished the Rat Attack Tutorial located here https://phaser.io/examples/v2/create/rat-attack  However, I am running into some difficulty. Can someone help me figure out how to get the rats to appear form the right side of the screen instead of the left side. Currently the rats move from left to right in this tutorial. I would like it to move from right to left. Can someone help me figure this out? 

here is the code

 

function preload(){
    game.load.image('player', 'assets/player.png');
    game.load.image('Enemies', 'assets/greenEnemy.png');
}
var enemy;

function create(){
    game.physics.startSystem(Phaser.Physics.ARCADE);
    
    game.stage.backgroundColor = '#2d2d2d';
    
    
    
    enemy = game.add.physicsGroup();
    
    var y = 80;

    for(var i =0; i < 9; i++){
        var allenemies = enemy.create(game.world.randomX, y, 'Enemies');
        allenemies.body.velocity.x = game.rnd.between(100,300);
        y += 48;

    }
    
    player = game.add.sprite(0, 50, 'player');
    game.physics.arcade.enable(player);
    
    cursors = game.input.keyboard.createCursorKeys();
}

function update(){
    enemy.forEach(checkPos, this);
    
    game.physics.arcade.overlap(player, enemy, collisionHandler, null, this);
    
    player.body.velocity.x = 0;
    player.body.velocity.y = 0;
    
    if(cursors.left.isDown){
        player.body.velocity.x = -200;
        player.body.velocity.scale = 1;
    }
    else if(cursors.right.isDown){
        player.body.velocity.x = 200;
        player.scale.x = 1;    
    }
    
    if (cursors.up.isDown)
    {
        player.body.velocity.y = -200;
    }
    else if (cursors.down.isDown)
    {
        player.body.velocity.y = 200;
    }
        
}
function checkPos(enemy){
    if(enemy.x > 800){
        enemy.x = -100;
    }
}

function collisionHandler (player, rat) {

    player.x = 400;
    player.y = 32;

}

Link to comment
Share on other sites

2 hours ago, Shawn salters said:

allenemies.body.velocity.x = game.rnd.between(100,300);

You need to give them a negative x velocity for them to move towards the left. So try game.rnd.between(-100, -300);

2 hours ago, Shawn salters said:

function checkPos(enemy){
    if(enemy.x > 800){
        enemy.x = -100;
    }
}

 

Additionally this function that checks the enemy position should be reversed since you are switching the sides... if the x position is < -100, set enemy.x = 800.

I think that should do it.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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