mraps98

JS_Sprite

May 24th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. $(document).ready(function(){
  2.     "use strict";
  3.     var Game = {
  4.         canvas : undefined,
  5.         c : undefined,
  6.         spriteHeight: 340,
  7.         spriteWidth: 454,
  8.         backgroundColor: 'black',
  9.         foregroundColor: 'white',
  10.         xPos : 0,
  11.         yPos : 0,
  12.         sprite : undefined,
  13.         xSpeed : 1,
  14.         ySpeed : 1
  15.     };
  16.  
  17.     Game.start = function(){
  18.         Game.canvas = document.getElementById('myCanvas');
  19.         Game.c = Game.canvas.getContext("2d");
  20.         Game.canvas.width = 1000;
  21.         Game.canvas.height = 600;
  22.         Game.sprite = new Image(Game.spriteWidth, Game.spriteHeight);
  23.         Game.sprite.src = "sprite.png";
  24.         setTimeout(Game.mainLoop,1000);
  25.     };
  26.  
  27.     Game.update = function(){
  28.         switch(Game.xPos){
  29.             case (Game.canvas.width - Game.spriteWidth):
  30.                 Game.xSpeed = -2;
  31.                 break;
  32.             case 0:
  33.                 Game.xSpeed = 2;
  34.         }
  35.         switch(Game.yPos){
  36.             case (Game.canvas.height - Game.spriteHeight):
  37.                 Game.ySpeed = -2;
  38.                 break;
  39.             case 0:
  40.                 Game.ySpeed = 2;
  41.         }
  42.         Game.xPos = Game.xPos + Game.xSpeed;
  43.         Game.yPos = Game.yPos + Game.ySpeed;
  44.         console.log(Game.yPos,Game.ySpeed);
  45.     };
  46.  
  47.     Game.draw = function(){
  48.         Game.clearCanvas();
  49.         Game.c.fillStyle = Game.backgroundColor;
  50.         Game.c.fillRect(0,0,Game.canvas.width, Game.canvas.height);
  51.         Game.c.fillStyle = Game.foregroundColor;
  52.         // Game.c.fillRect(Game.xPos,Game.yPos,Game.spriteWidth, Game.spriteHeight);
  53.         Game.c.drawImage(Game.sprite,Game.xPos,Game.yPos,Game.spriteWidth,Game.spriteHeight);
  54.     };
  55.  
  56.     Game.mainLoop = function(){
  57.         Game.update();
  58.         Game.draw();
  59.         setTimeout(Game.mainLoop, 1000/30);
  60.     }
  61.  
  62.     Game.clearCanvas = function(){
  63.         Game.c.clearRect(0,0,Game.canvas.width,Game.canvas.height);
  64.     }
  65.  
  66.     Game.start();
  67. });
Add Comment
Please, Sign In to add comment