Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var player = {
- color: "#ff0000",
- x: 0,
- y: 0,
- width: 16,
- height: 16,
- speed: 4,
- velX: 0,
- velY: 0,
- keys: [],
- colliding: [],
- LEFT: false,
- RIGHT: false,
- UP: false,
- DOWN: false,
- updateKeys: function() {
- if(this.keys[68] || this.keys[39]) {
- this.RIGHT = true;
- } else {
- this.RIGHT = false;
- }
- if(this.keys[65] || this.keys[37]) {
- this.LEFT = true;
- } else {
- this.LEFT = false;
- }
- if(this.keys[87] || this.keys[38]) {
- this.UP = true;
- } else {
- this.UP = false;
- }
- if(this.keys[83] || this.keys[40]) {
- this.DOWN = true;
- } else {
- this.DOWN = false;
- }
- },
- update: function() {
- if(this.RIGHT) {
- this.velX = this.speed;
- }
- if(this.LEFT) {
- this.velX = -this.speed;
- }
- if(this.UP) {
- this.velY = -this.speed;
- }
- if(this.DOWN) {
- this.velY = this.speed;
- }
- this.x += this.velX;
- this.y += this.velY;
- if(this.y >= canvas_height - this.height) {
- this.y = canvas_height - this.height;
- } else if(this.y <= 0) {
- this.y = 0;
- }
- if (this.x >= canvas_width-this.width) {
- this.x = canvas_width-this.width;
- } else if (this.x <= 0) {
- this.x = 0;
- }
- this.velX = 0;
- this.velY = 0;
- },
- draw: function() {
- context.fillStyle = "red";
- context.fillRect(this.x, this.y, this.width, this.height);
- },
- collides: function(block) {
- var collide = (Math.abs(this.x - block.tile.x) * 2 < (this.width + block.tile.width)) && (Math.abs(this.y - block.tile.y) * 2 < (this.height + block.tile.height));
- if(collide) {
- if(!inArray(block.id, this.colliding)) {
- this.colliding.push(block.id);
- }
- this.handleCollision(block);
- } else {
- if(inArray(block.id, this.colliding)) {
- this.colliding = removeFromArray(block.id, this.colliding);
- }
- }
- return false;
- },
- handleCollision: function(block) {
- // Approaching from left
- if(this.x + this.width > block.tile.x) {
- this.x = block.tile.x;
- }
- // Approaching from right
- if(this.x < block.tile.x + block.tile.width) {
- this.x = block.tile.x + block.tile.width;
- }
- // Approaching from top
- if(this.y + this.height > block.tile.y) {
- this.y = block.tile.y;
- }
- // Approaching from bottom
- if(this.y < block.tile.y + block.tile.height) {
- this.y = block.tile.y + block.tile.height;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment