Game Tutorial 4

Objective

  • Check collusion of enemy and player. Add score and reset enemy if there is a collusion.

Code

**View Source code: game-tutorial4.js

I will only explain the code that is new or updated from the previous tutorial.

function calculate(){
  // check key and move player
  if(TMI.keyboard.checkKey(KEYSET.LEFT) && player.x>2) player.x--;
  if(TMI.keyboard.checkKey(KEYSET.UP) && player.y>1) player.y--;
  if(TMI.keyboard.checkKey(KEYSET.RIGHT) && player.x+player.text.length<frame.width-2) player.x++;
  if(TMI.keyboard.checkKey(KEYSET.DOWN) && player.y<frame.height-2) player.y++;
  processCollusion();

  //reset enemy
  if(enemy.y===null || enemy.y>frame.height-3){
    resetEnemy();
  }

  //move enemy
  if(++enemy.turnCount>enemy.turnCountMax){
    enemy.turnCount = 0;
    enemy.y++;
  }
  processCollusion();
}

processCollusion function call is added to the last line of // check key and move player and //move enemy. Collusion check should be done after every movement.

function processCollusion(){
  if(player.y==enemy.y && player.x<=enemy.x && player.x+player.text.length>=enemy.x){
    resetEnemy();
    frame.score += 100;
  }
}

This checks collusion considering x, y and width of player and  x and y of enemy. It adds score and call resetEnemy function if there is a collusion. The checking algorithm can be more complicated if there are more facts added to check collusion. (for example: adding enemy's width or player's height)

Run Example

The functionalities are all done!

Comments

Add Comment

Login with SNS account to write comments. see details

UP