Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (function() {
- var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
- window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
- window.requestAnimationFrame = requestAnimationFrame;
- })();
- var canvas = document.getElementById("canvas"),
- width = canvas.width,
- height = canvas.height,
- ctx = canvas.getContext("2d"),
- player = {
- x: 0,
- y: canvas.height - 25,
- velX: 0,
- velY: 0,
- speed: 3,
- width: 25,
- height: 25,
- friction: 0.9,
- gravity: 0.2,
- jumping: false
- },
- keys = [];
- document.body.addEventListener("keydown", function(e) {
- keys[e.keyCode] = true;
- });
- document.body.addEventListener("keyup", function(e) {
- keys[e.keyCode] = false;
- });
- function rect(x, y, width, height, color) {
- ctx.fillStyle = color;
- ctx.fillRect(x, y, width, height);
- ctx.fillStyle = 'black';
- }
- function update() {
- if (keys[87]) {
- if (!player.jumping) {
- player.jumping = true;
- player.velY = -player.speed * 2;
- }
- }
- if (keys[68]) {
- if (player.velX < player.speed) {
- player.velX++;
- }
- }
- if (keys[65]) {
- if (player.velX > -player.speed) {
- player.velX--;
- }
- }
- if (player.x >= canvas.width - player.width) {
- player.x = canvas.width - player.width;
- } else if (player.x <= 0) {
- player.x = 0;
- }
- if (player.y >= canvas.height - player.height) {
- player.y = canvas.height - player.height;
- player.jumping = false;
- }
- player.x += player.velX;
- player.y += player.velY;
- player.velX *= player.friction;
- player.velY += player.gravity;
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- rect(player.x, player.y, player.width, player.height, 'black');
- requestAnimationFrame(update);
- }
- requestAnimationFrame(update);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement