How stay on the floor - javascript

Can you help with the code? I'm creating a parkour game and everything went well but I got stuck on it: as the cube will stand on the floor. Here is my js code:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//Налаштування
var width = canvas.width;
var height = canvas.height;
var gameOver = function() {
clearInterval(intervalId);
ctx.font = "60px Caurier";
ctx.textAlign = "cener";
ctx.textBaseline = "middle";
ctxfillText("GAME OVER", width / 2, height / 2);
};
var cicle = function(x, y, radius, fillCircle) {
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2, false);
if (fillCircle) {
ctx.fill();
} else {
ctx.stroke();
}
}; //Людина
//намалювати
function Draw() {
this.x = 10;
this.y = 10;
}
Draw.prototype.draw = function() {
ctx.beginPath();
ctx.moveTo(this.x, this.y);
ctx.lineTo(this.x + 50, this.y);
ctx.lineTo(this.x + 50, this.y + 50);
ctx.lineTo(this.x, this.y + 50);
ctx.lineTo(this.x, this.y);
ctx.fill();
}
Draw.prototype.move = function() {
if (this.x < 0) {
this.x = 0;
} else if (this.x > 1250) {
this.x = 1250;
}
if (this.y < 0) {
this.y = 0;
} else if (this.y > 450) {
this.y = 450;
}
while (this.y < 450) {
this.y++;
}
}
Draw.prototype.setDirection = function(direction) {
if (direction === "left") {
this.x = this.x - 10;
} else if (direction === "right") {
this.x = this.x + 10;
} else if (direction === "up") {
this.y = this.y - 150;
}
}
var person = new Draw;
var keyActions = {
37: "left",
38: "up",
39: "right"
};
$("body").keydown(function(event) {
var direction = keyActions[event.keyCode];
person.setDirection(direction);
});
setInterval(function() {
ctx.clearRect(0, 0, 1300, 500);
person.draw();
person.move();
//карта
var floor = ctx.strokeStyle = "LimeGreen";
ctx.lineWidth = 4;
ctx.strokeRect(0, 312, 1300, 362);
}, 30);
body {
background-color: rgb(44, 235, 225);
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>parcur</title>
</head>
<body>
<canvas id="canvas" width="1300" height="500"></canvas>
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
</body>
</html>
I tried a lot but it didn't work out. For example, I tried this: first the code checks whether the cube and the floor are in the same coordinates, if so it reflects, if not, then no.I want the cube to be able to walk on the floor which is painted green, and not pass through it.

Related

How to add element with circular motion on HTML5 canvas using JavaScript that provides function when something goes near it?

Here is my current HTML file
<!DOCTYPE html>
<html>
<head>
<title>Space Ship</title>
<style type="text/css">
canvas{
border: 1px solid black;
}
body{
margin: 0;
}
</style>
</head>
<body>
<canvas id="game"></canvas>
<script src="game.js"></script>
</body>
</html>
And here is my current JS file which is where I make all the changes to the canvas
(function () {
const canvas = document.getElementById('game');
const context = canvas.getContext('2d');
const SPACESHIP_SIZE = { width: 15, height: 25 };
const SPACESHIP_POSITION = { x: window.innerWidth/2, y: window.innerHeight/2};
const GRAVITY = 0;
//Update thrust constant
const THRUST = 15;
class SpaceShip {
constructor(size, position) {
this.color = 'yellow';
this.size = size;
this.position = position;
this.angle = 0;
this.engineOn = false;
this.rotatingLeft = false;
this.rotatingRight = false;
this.velocity = {
x: 0,
y: 0,
};
}
draw() {
const triangleCenterX = this.position.x + 0.5 * this.size.width;
const triangleCenterY = this.position.y + 0.5 * this.size.height;
context.save();
context.translate(triangleCenterX, triangleCenterY);
context.rotate(this.angle);
context.lineWidth = 5;
context.beginPath();
// Triangle
context.moveTo(0, -this.size.height / 2);
context.lineTo(-this.size.width / 2, this.size.height / 2);
context.lineTo(this.size.width / 2, this.size.height / 2);
context.closePath();
context.strokeStyle = this.color;
context.stroke();
context.fillStyle = "red";
context.fill();
// Flame for engine
if (this.engineOn) {
const fireYPos = this.size.height / 2 + 4;
const fireXPos = this.size.width * 0.25;
context.beginPath();
context.moveTo(-fireXPos, fireYPos);
context.lineTo(fireXPos, fireYPos);
context.lineTo(0, fireYPos + Math.random() * 100);
context.lineTo(-fireXPos, fireYPos);
context.closePath();
context.fillStyle = 'orange';
context.fill();
}
context.restore();
}
moveSpaceShip() {
// Angle has to be in radians
const degToRad = Math.PI / 180;
// Change the position based on velocity
this.position.x += this.velocity.x;
this.position.y += this.velocity.y;
// Move spaceship to other side when leaving screen
this.position.x = (canvas.width + this.position.x) % canvas.width;
this.position.y = (canvas.height + this.position.y) % canvas.height;
/*
Adding floating point numbers to the end of the
rotaion handling to make roation faster
*/
if (this.rotatingLeft) this.angle -= (degToRad+.1);
if (this.rotatingRight) this.angle += (degToRad+.1);
// Acceleration
if (this.engineOn) {
this.velocity.x += (THRUST / 100) * Math.sin(this.angle);
this.velocity.y -= (THRUST / 100) * Math.cos(this.angle);
}
// Update the velocity depending on gravity
this.velocity.y += GRAVITY / 2500;
}
}
const spaceShip = new SpaceShip(SPACESHIP_SIZE, SPACESHIP_POSITION);
function handleKeyInput(event) {
const { keyCode, type } = event;
const isKeyDown = type === 'keydown' ? true : false;
if (keyCode === 37) spaceShip.rotatingLeft = isKeyDown;
if (keyCode === 39) spaceShip.rotatingRight = isKeyDown;
if (keyCode === 38) spaceShip.engineOn = isKeyDown;
}
function draw() {
console.log('drawing');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Clear screen
context.fillStyle = 'rgb(0, 10, 60)';
context.fillRect(0, 0, window.innerWidth, canvas.height);
context.font = "30px Arial";
context.fillText("Hello World", window.innerWidth, window.innerHeight);
//Loading small stars
for (var i = 1; i<window.innerWidth; i+=100){
for(var j = 1; j<window.innerHeight; j+=100){
context.beginPath();
context.arc(i, j, 1, 0, Math.PI*2, false);
context.fillStyle = 'white';
context.fill();
context.stroke();
}
}
//loading medium stars
for (var i = 1; i<window.innerWidth; i+=150){
for(var j = 1; j<window.innerHeight; j+=150){
context.beginPath();
context.arc(i, j, 2, 0, Math.PI*2, false);
context.fillStyle = 'white';
context.fill();
context.stroke();
}
}
//loading larger stars
for (var i = 1; i<window.innerWidth; i+=225){
for(var j = 1; j<window.innerHeight; j+=225){
context.beginPath();
context.arc(i, j, 3, 0, Math.PI*2, false);
context.fillStyle = 'white';
context.fill();
context.stroke();
}
}
spaceShip.moveSpaceShip();
// Begin drawing
spaceShip.draw();
// Repeats
requestAnimationFrame(draw);
}
// Event Listeners
document.addEventListener('keydown', handleKeyInput);
document.addEventListener('keyup', handleKeyInput);
// Start the game
draw();
})();
The output works and looks like this...
Little rocket that flies around in space and it works perfectly fine
Now the issue I have is that I want to add elements that represent black holes which spin in a circular motion. When the spaceship which is controlled by the arrow keys hovers over one of these spinning "black hole" like objects, I want to prompt the user to click "enter" in order to go to a new area and space which means they will be redirected to a new canvas (which will just be a different version of the one you see here.
I have no ideas on how to go about adding one of these objects onto the canvas and then give it this function. Does anyone know how to?
Im sure its not as difficult as i'm making it seem, I just don't have that much experience using JavaScript and an HTML5 canvas. Thanks.
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth - 4;
canvas.height = window.innerHeight - 4;
ctx.font = "30px Arial";
ctx.shadowColor = "rgba(255,255,255,.6)";
// Constants in objects doesnt work cause objects passing as reference and will by modified!
// If you want constant constant, use primitives
const SPACESHIP_SIZE = { width: 15, height: 25 };
const SPACESHIP_POSITION = { x: window.innerWidth/2, y: window.innerHeight/2};
const GRAVITY = 0;
const HOVER_TICKS = 80;
//Update thrust constant
const THRUST = 15;
const Systems = {
'main': {
holes:[
{x: 100, y: 350, size: 20, dest: 'J204853'},
{x: 550, y: 50, size: 20, dest: 'J111000'},
{x: 400, y: 150, size: 30, dest: 'J235456'},
{x: 300, y: 100, size: 20, dest: 'Jita'},
{x: 200, y: 400, size: 10, dest: 'Amarr'},
{x: 450, y: 300, size: 20, dest: 'Thera'},
]
},
'J204853': {holes:[{x: 550, y: 50, size: 30, dest: 'main'}]},
'J235456': {holes:[{x: 350, y: 70, size: 20, dest: 'main'}]},
'J111000': {holes:[{x: 150, y: 150, size: 10, dest: 'main'}]},
'Amarr': {holes:[{x: 350, y: 270, size: 30, dest: 'main'}]},
'Thera': {holes:[{x: 250, y: 170, size: 40, dest: 'main'}]},
'Jita': {holes:[{x: 450, y: 250, size: 20, dest: 'main'}]},
};
let spaceShip;
let currentSystem = 'main';
const spaceObjects = [];
class SpaceObject {
constructor(size, position, color = 'black', angle = 0) {
this.color = color;
this.size = size;
this.position = position;
this.angle = angle;
spaceObjects.push(this);
}
tick() {
this.update();
this.draw();
}
update() {}
draw() {}
isAbove({x, y}) {
return Math.abs(this.position.x - x) < this.size && Math.abs(this.position.y - y) < this.size;
}
destroy() {
spaceObjects.splice(spaceObjects.indexOf(this), 1);
}
}
class SpaceShip extends SpaceObject {
constructor(size, position) {
super(size, position, 'yellow');
this.aboveHole = 0;
this.engineOn = false;
this.rotatingLeft = false;
this.rotatingRight = false;
this.velocity = {x: 0, y: 0};
}
draw() {
const triangleCenterX = this.position.x + 0.5 * this.size.width;
const triangleCenterY = this.position.y + 0.5 * this.size.height;
ctx.shadowBlur = 0;
ctx.save();
ctx.translate(triangleCenterX, triangleCenterY);
ctx.rotate(this.angle);
ctx.lineWidth = 5;
ctx.beginPath();
// Triangle
ctx.moveTo(0, -this.size.height / 2);
ctx.lineTo(-this.size.width / 2, this.size.height / 2);
ctx.lineTo(this.size.width / 2, this.size.height / 2);
ctx.closePath();
ctx.strokeStyle = this.color;
ctx.stroke();
ctx.fillStyle = "red";
ctx.fill();
// Flame for engine
if (this.engineOn) {
const fireYPos = this.size.height / 2 + 4;
const fireXPos = this.size.width * 0.25;
ctx.beginPath();
ctx.moveTo(-fireXPos, fireYPos);
ctx.lineTo(fireXPos, fireYPos);
ctx.lineTo(0, fireYPos + Math.random() * 100);
ctx.lineTo(-fireXPos, fireYPos);
ctx.closePath();
ctx.fillStyle = 'orange';
ctx.fill();
}
ctx.restore();
}
update() {
this.moveSpaceShip();
this.checkAboveHole();
}
moveSpaceShip() {
// Angle has to be in radians
const degToRad = Math.PI / 180;
// Change the position based on velocity
this.position.x += this.velocity.x;
this.position.y += this.velocity.y;
// Move spaceship to other side when leaving screen
this.position.x = (canvas.width + this.position.x) % canvas.width;
this.position.y = (canvas.height + this.position.y) % canvas.height;
/*
Adding floating point numbers to the end of the
rotaion handling to make roation faster
*/
if (this.rotatingLeft) this.angle -= (degToRad+.1);
if (this.rotatingRight) this.angle += (degToRad+.1);
// Acceleration
if (this.engineOn) {
this.velocity.x += (THRUST / 100) * Math.sin(this.angle);
this.velocity.y -= (THRUST / 100) * Math.cos(this.angle);
}
// Update the velocity depending on gravity
this.velocity.y += GRAVITY / 2500;
}
checkAboveHole() {
const hole = spaceObjects.find(spaceObject => spaceObject !== this && spaceObject.isAbove(this.position));
if(hole) {
this.aboveHole++;
if(this.aboveHole > HOVER_TICKS) {
confirm(`Jump to system ${hole.dest}?`) && jump(hole);
this.aboveHole = 0;
}
} else {
this.aboveHole = 0;
}
}
}
const circle = (ctx, x, y, radius, color = 'white') => {
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI*2, false);
ctx.fillStyle = color;
ctx.fill();
ctx.stroke();
ctx.closePath();
};
class BlackHole extends SpaceObject {
constructor(size, position, dest) {
super(size, position);
this.dest = dest;
}
update() {
// Spin?
this.angle+=.01;
}
draw() {
// Shadow
ctx.shadowBlur = this.size >>> 2;
circle(ctx, this.position.x, this.position.y, this.size + 1, `rgba(255, 255, 255, .6)`);
// Hole
circle(ctx, this.position.x, this.position.y, this.size, this.color);
// Spinning view
circle(ctx, this.position.x + (this.size * Math.sin(this.angle) - 1), this.position.y + (this.size * Math.cos(this.angle) - 1), 2, 'gray');
circle(ctx, this.position.x - (this.size * Math.sin(this.angle) - 1), this.position.y - (this.size * Math.cos(this.angle) - 1), 2, 'gray');
}
}
function handleKeyInput(event) {
const { keyCode, type } = event;
const isKeyDown = type === 'keydown' ? true : false;
if (keyCode === 37) spaceShip.rotatingLeft = isKeyDown;
if (keyCode === 39) spaceShip.rotatingRight = isKeyDown;
if (keyCode === 38) spaceShip.engineOn = isKeyDown;
}
function jump({dest}) {
currentSystem = dest || 'main';
while(spaceObjects.length) spaceObjects[0].destroy();
Systems[currentSystem].holes.forEach(hole => new BlackHole(hole.size, {x: hole.x, y: hole.y}, hole.dest));
spaceShip = new SpaceShip(SPACESHIP_SIZE, SPACESHIP_POSITION);
}
function draw() {
// Clear screen
ctx.fillStyle = 'rgb(0, 10, 60)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'rgb(150, 150, 150)';
ctx.fillText(`You are in system ${currentSystem}`, 40, 40);
//Loading small stars
ctx.shadowBlur = 1;
for (var i = 1, j = 1; j<canvas.height; i+=100, i > canvas.width && (i=1, j+=100), circle(ctx, i, j, 1));
//loading medium stars
ctx.shadowBlur = 2;
for (var i = 1, j = 1; j<canvas.height; i+=150, i > canvas.width && (i=1, j+=150), circle(ctx, i, j, 2));
//loading larger stars
ctx.shadowBlur = 3;
for (var i = 1, j = 1; j<canvas.height; i+=225, i > canvas.width && (i=1, j+=225), circle(ctx, i, j, 3));
// tick all objects
spaceObjects.forEach(spaceObject => spaceObject.tick());
// Repeats
requestAnimationFrame(draw);
}
// Event Listeners
document.addEventListener('keydown', handleKeyInput);
document.addEventListener('keyup', handleKeyInput);
// Start the game
jump({dest: 'main'});
draw();
<!DOCTYPE html>
<html>
<head>
<title>Space Ship</title>
<style type="text/css">
canvas{
border: 1px solid black;
}
body{
margin: 0;
}
</style>
</head>
<body>
<canvas id="game"></canvas>
</body>
</html>

Building simple 2d javascript game, how to stop game piece leaving the canvass

So i'm new to this and have probably coded it wrong to start off with. I'm thinking after doing research that i should have stored my other game pieces in an array or as seperate variables. Please correct me if im wrong.
Here is my code
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:5px solid #d3d3d3;
background-color: green;
}
</style>
</head>
<body onload="startGame()">
<script>
var myGamePiece;
var myObstacle
function startGame() {
myGamePiece = new component(30, 30, "black", 350, 445);
blueGamePiece = new component(20, 20, "blue", 20, 20);
whiteGamePiece = new component(5, 40, "white",400, 20);
brownGamePiece = new component(25, 25, "brown", 650, 20);
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 700;
this.canvas.height = 480;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function (e) {
myGameArea.key = e.keyCode;
})
window.addEventListener('keyup', function (e) {
myGameArea.key = false;
})
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop : function() {
clearInterval(this.interval);
}
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function(){
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
}
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.key && myGameArea.key == 37) {myGamePiece.speedX = -5; }
if (myGameArea.key && myGameArea.key == 39) {myGamePiece.speedX = 5;}
myGamePiece.newPos();
myGamePiece.update();
myGamePiece.update();
blueGamePiece.y += 1;
blueGamePiece.update();
whiteGamePiece.y +=3;
whiteGamePiece.update();
brownGamePiece.y +=2;
brownGamePiece.update();
}
</script>
</body>
</html>
I simply want to stop myGamePiece leaving the canvass not bounce it back.
Any other advice would be more than welcome.
Thankyou very much in advance.
Solution: Replace "this.update" function with this code.
this.update = function(){
if(this.x < 0){this.x = 0}
if(this.y < 0){this.y = 0}
if(this.x + this.width > myGameArea.canvas.width){this.x = myGameArea.canvas.width - this.width}
if(this.y + this.height > myGameArea.canvas.height){this.y = myGameArea.canvas.height - this.height}
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}

JavaScript canvas color-property interference

Problem: The color of block should be grey, but instead inherits the color-property of ball which is red. block2 should be blue, but inherits the color of block which is grey. How do I fix this problem? I have just started to learn how to program so i do not have much experience with things like this:/
Code:
function Player(x, y, w, h, color) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.color = color;
this.dy = 3;
this.draw = function() {
c.fillRect(this.x, this.y, this.w, this.h);
c.fillStyle = this.color;
c.stroke();
c.closePath();
};
this.update = function() {
if (keyW === true) {
block.y -= block.dy;
}
if (keyS === true) {
block.y += block.dy;
}
if (arrowUp === true) {
block2.y -= block2.dy;
}
if (arrowDown === true) {
block2.y += block2.dy;
}
if (this.y + this.h > canvas.height) {
this.y = canvas.height - this.h;
}
if (this.y < 0) {
this.y = 0;
}
this.draw();
};
}
block = new Player(10, (canvas.height / 2) - 50, 250, 100, "grey");
block2 = new Player(canvas.width - 30, (canvas.height / 2) - 50, 20, 100, "blue");
function Ball(x, y, radius, color) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.dx = 3;
this.dy = 0;
this.draw = function() {
c.beginPath();
c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
c.fillStyle = this.color;
c.fill();
c.closePath();
};
this.update = function() {
this.x -= this.dx;
if (this.y + this.radius > canvas.height) {
this.y = canvas.height - this.radius;
}
if (this.y - this.radius < 0) {
this.y = this.radius;
}
if (this.x + this.radius > canvas.width) {
this.dx = -this.dx;
}
if (this.x - this.radius < 0) {
this.dx = -this.dx;
}
this.draw();
};
}
ball = new Ball(canvas.width / 2 - 50, canvas.height / 2, 10, "red");
You are filling a rect inside Player update method before changing the color, so it uses previous fillStyle value which is red.
Instead of:
c.fillRect(x, y, w, h);
c.fillStyle = this.color;
Do:
c.fillStyle = this.color;
c.fillRect(x, y, w, h);

Collision detection between circle and rectangle in Javascript game?

I'm creating a javascript game where I need a collision between the ball and rectangle to trigger a reset of the game. For now I just have an alert there for testing purposes. I'm having trouble getting the collision detection working.
This is what I've got so far but it isn't working
function startGame() {
keeper = new obstacle(40, 20, "#666", 130, 180);
theBall = new component("#000", 80, 10);
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 300;
this.canvas.height = 250;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function(e) {
myGameArea.key = e.keyCode;
})
window.addEventListener('keyup', function(e) {
myGameArea.key = false;
})
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function component(color, x, y, type) {
this.type = type;
this.speed = 1.5;
this.angle = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.beginPath();
ctx.arc(this.x, this.y, 10, 0, 2 * Math.PI);
ctx.fillStyle = color;
ctx.fill();
ctx.restore();
}
this.newPos = function() {
this.x -= this.speed * Math.sin(this.angle);
this.y += this.speed * Math.cos(this.angle);
}
}
function obstacle(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
}
this.collideWith = function(theBall){
var collide = true;
var myTop =this.y;
var theBallBottom = theBall.y + (theBall.radius)
if (myTop < theBallBottom)
{
collide = false;
}
return collide;
}
}
function updateGameArea() {
if (keeper.crashWith(theBall)) {
alert("Collision");
} else {
myGameArea.clear();
theBall.newPos();
theBall.update();
keeper.speedX = 0;
keeper.speedY = 0;
if (myGameArea.key && myGameArea.key == 37) {keeper.speedX = -1; }
if (myGameArea.key && myGameArea.key == 39) {keeper.speedX = 1; }
keeper.newPos();
keeper.update();
}
}
The game can be found here http://alexhollingsworth.co.uk/game.php
You named your method collideWith, but you are calling it crashWith in the update method. Plus this will only detect collision on y axis, but I assume this is intended.
I made an if statement that can detect collisions in JavaScript, here it is:
if circle x < rect x + circle width && circle x + rect width > rect x && circle y < rect y + circle height && rect height + circle y > rect y {
This works by putting the ball into an 'imaginary box', then senses if any of the edges of the 'imaginary box' come in contact with any of the edges of the rectangle. I hope this helped.

Why doesn't the Triangle clear?

I have a question, why doesn't the triangle clear here?
Here is the image:
Here is the JSFIddle
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Snake Game</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- Basic styling, centering the canvas -->
<style>
canvas {
position: absolute;
top: 20px;
bottom: 0px;
left: 250px;
right: 0px;
}
</style>
</head>
<body>
<canvas id="game" width="500" height="500"></canvas>
<script>
$(document).ready(function() {
var loadcount = 0;
var loadtotal = 0;
var preloaded = false;
var WIDTH = 500;
var HEIGHT = 500;
var keys = {};
var canvas = document.getElementById('game');
var ctx = canvas.getContext('2d');
var images = loadImages(["spaceship.png"]);
var player = {
x: null,
y: null,
width: 40,
height: 40,
speed: 5,
update: function() {
if (keys[39]) {
ctx.clearRect(this.x, this.y, this.width, this.height);
this.x += this.speed;
}
if (keys[37]) {
ctx.clearRect(this.x, this.y, this.width, this.height);
this.x -= this.speed;
}
if (keys[38]) {
ctx.clearRect(this.x, this.y, this.width, this.height);
this.y -= this.speed;
}
if (keys[40]) {
ctx.clearRect(this.x, this.y, this.width, this.height);
this.y += this.speed;
}
//Checks if it is out of Bounds
if (this.x > WIDTH - this.width) {
this.x = WIDTH - this.width;
}
if (this.x < 0) {
this.x = 0;
}
if (this.y > HEIGHT - 15) {
this.y = HEIGHT - 15;
}
if (this.y < 0) {
this.y = 0;
}
},
draw: function() {
ctx.save();
ctx.beginPath();
ctx.strokeStyle = 'blue'
ctx.moveTo(this.x, this.y);
ctx.lineWidth = 16;
ctx.lineTo(this.x + 15, this.y + 25);
ctx.lineTo(this.x - 15, this.y + 25);
ctx.closePath();
ctx.stroke();
ctx.restore();
}
}
function main() {
document.addEventListener("keydown", function(event) {
keys[event.keyCode] = true;
})
document.addEventListener("keyup", function(event) {
delete keys[event.keyCode];
})
init();
var loop = function() {
update();
draw();
window.requestAnimationFrame(loop, canvas);
};
window.requestAnimationFrame(loop, canvas);
}
function init() {
player.x = (WIDTH / 2);
player.y = (HEIGHT / 2) + 150;
}
function draw() {
//Drawing the Square
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(0, HEIGHT);
ctx.lineTo(HEIGHT, WIDTH);
ctx.lineTo(WIDTH, 0)
ctx.lineTo(0, 0)
ctx.stroke();
player.draw();
}
function update() {
player.update();
}
function loadImages(imagefiles) {
// Initialize variables
loadcount = 0;
loadtotal = imagefiles.length;
preloaded = false;
// Load the images
var loadedimages = [];
for (var i = 0; i < imagefiles.length; i++) {
// Create the image object
var image = new Image();
// Add onload event handler
image.onload = function() {
loadcount++;
if (loadcount == loadtotal) {
// Done loading
preloaded = true;
}
};
// Set the source url of the image
image.src = imagefiles[i];
// Save to the image array
loadedimages[i] = image;
}
// Return an array of images
return loadedimages;
}
main();
})
</script>
</body>
</html>
While using clearRect, clear entire canvas
Try this:
$(document).ready(function() {
var loadcount = 0;
var loadtotal = 0;
var preloaded = false;
var WIDTH = 500;
var HEIGHT = 500;
var keys = {};
var canvas = document.getElementById('game');
var ctx = canvas.getContext('2d');
var images = loadImages(["spaceship.png"]);
var player = {
x: null,
y: null,
width: 40,
height: 40,
speed: 5,
update: function() {
if (keys[39]) {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
this.x += this.speed;
}
if (keys[37]) {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
this.x -= this.speed;
}
if (keys[38]) {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
this.y -= this.speed;
}
if (keys[40]) {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
this.y += this.speed;
}
//Checks if it is out of Bounds
if (this.x > WIDTH - this.width) {
this.x = WIDTH - this.width;
}
if (this.x < 0) {
this.x = 0;
}
if (this.y > HEIGHT - 15) {
this.y = HEIGHT - 15;
}
if (this.y < 0) {
this.y = 0;
}
},
draw: function() {
ctx.save();
ctx.beginPath();
ctx.strokeStyle = 'blue'
ctx.moveTo(this.x, this.y);
ctx.lineWidth = 16;
ctx.lineTo(this.x + 15, this.y + 25);
ctx.lineTo(this.x - 15, this.y + 25);
ctx.closePath();
ctx.stroke();
ctx.restore();
}
}
function main() {
document.addEventListener("keydown", function(event) {
keys[event.keyCode] = true;
})
document.addEventListener("keyup", function(event) {
delete keys[event.keyCode];
})
init();
var loop = function() {
update();
draw();
window.requestAnimationFrame(loop, canvas);
};
window.requestAnimationFrame(loop, canvas);
}
function init() {
player.x = (WIDTH / 2);
player.y = (HEIGHT / 2) + 150;
}
function draw() {
//Drawing the Square
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(0, HEIGHT);
ctx.lineTo(HEIGHT, WIDTH);
ctx.lineTo(WIDTH, 0)
ctx.lineTo(0, 0)
ctx.stroke();
player.draw();
}
function update() {
player.update();
}
function loadImages(imagefiles) {
// Initialize variables
loadcount = 0;
loadtotal = imagefiles.length;
preloaded = false;
// Load the images
var loadedimages = [];
for (var i = 0; i < imagefiles.length; i++) {
// Create the image object
var image = new Image();
// Add onload event handler
image.onload = function() {
loadcount++;
if (loadcount == loadtotal) {
// Done loading
preloaded = true;
}
};
// Set the source url of the image
image.src = imagefiles[i];
// Save to the image array
loadedimages[i] = image;
}
// Return an array of images
return loadedimages;
}
main();
});
canvas {
position: absolute;
top: 20px;
bottom: 0px;
left: 250px;
right: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="game" width="500" height="500"></canvas>
Fiddle here

Categories

Resources