Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Enemies our player must avoid
- var Enemy = function(x,y,speed) {
- // Variables applied to each of our instances go here,
- // we've provided one for you to get started
- this.x = x;
- this.y = y;
- this.speed = speed;
- // The image/sprite for our enemies, this uses
- // a helper we've provided to easily load images
- this.sprite = 'images/enemy-bug.png';
- };
- // Update the enemy's position, required method for game
- // Parameter: dt, a time delta between ticks
- Enemy.prototype.update = function(dt) {
- // You should multiply any movement by the dt parameter
- // which will ensure the game runs at the same speed for
- // all computers.
- this.x += dt * this.speed;
- if(this.x > 505){
- this.reset();
- }
- };
- // Draw the enemy on the screen, required method for game
- Enemy.prototype.render = function() {
- ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
- };
- //Function to reset the enemy when moves off screen
- Enemy.prototype.reset = function(){
- this.x = -50;
- this.speed = Math.floor(Math.random());
- };
- // Now write your own player class
- // This class requires an update(), render() and
- // a handleInput() method.
- var Player = function(x,y) {
- this.x = x;
- this.y = y;
- this.sprite = 'images/char-cat-girl.png';
- };
- Player.prototype.render = function() {
- ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
- };
- Player.prototype.update = function(dt) {
- //prevent player from moving outside canvas
- if(this.y > 606){
- this.y = 606;
- }
- if(this.y < 1){
- this.y = 1;
- }
- if(this.x > 505){
- this.x = 505;
- }
- if(this.x < 1){
- this.x = 0;
- }
- //if player collides with enemy
- allEnemies.forEach(function(enemy) {
- if(this.x == enemy.x && this.y == enemy.y){
- this.reset();
- }
- });
- };
- Player.prototype.handleInput = function(userInput) {
- switch (userInput) {
- case 'left':
- this.x -= this.speed + 50;
- break;
- case 'right':
- this.x += this.speed + 50;
- break;
- case 'up':
- this.y -= this.speed + 50;
- break;
- case 'down':
- this.y += this.speed + 50;
- break;
- }
- };
- Player.prototype.reset = function() {
- this.x = 250;
- this.y = 1;
- };
- // Now instantiate your objects.
- // Place all enemy objects in an array called allEnemies
- // Place the player object in a variable called player
- var allEnemies = [];
- var enemyStart = [50, 150, 200];
- var player = new Player(100, 300);
- var enemy;
- enemyStart.forEach(function(startY) {
- enemy = new Enemy(0, startY, Math.floor(Math.random()));
- allEnemies.push(enemy);
- });
- // This listens for key presses and sends the keys to your
- // Player.handleInput() method. You don't need to modify this.
- document.addEventListener('keyup', function(e) {
- var allowedKeys = {
- 37: 'left',
- 38: 'up',
- 39: 'right',
- 40: 'down'
- };
- player.handleInput(allowedKeys[e.keyCode]);
- });
Add Comment
Please, Sign In to add comment