Why isn't my paddle moving Javascript Canvas? - javascript

I am attempting to code a rudimentary game but can't get the paddle to move. the code throws no errors. I'm working from a tutorial and know this code (https://drive.google.com/file/d/10-dH62BYlvPY20OeZo5VPWP92jWXvgjE/view) to work fine.
"use strict";
//gameParameters
const height = 550;
const width = height;
const border = 15;
const paddleHeight = 15;
const paddleWidth = 45;
const paddleSpeed = 0.7; //fraction of screen width/sec
//colors
const colorBackground = 'black';
const colorBorder = 'pink';
const colorPaddle = 'pink';
//definitions
const direction = {
left: 0,
right: 1,
stop: 2
}
//gameCanvas
var canv = document.createElement('canvas');
canv.width = width;
canv.height = height;
document.body.appendChild(canv);
//context
var ctx = canv.getContext('2d');
ctx.lineWidth = border;
//game Variables
var paddle;
//start new game
newGame();
//event listeners
document.addEventListener("keydown", keyDown);
document.addEventListener("keyup", keyUp);
// gameLoop
var timeDelta, timeLast;
requestAnimationFrame(loop);
function loop(timeNow) {
if (!timeLast) {
timeLast = timeNow;
}
//calcTimeDifference
timeDelta = (timeNow - timeLast) * 0.001; //ms => sec
timeLast = timeNow;
//update
updatePaddle(timeDelta);
//draw
drawBackground();
drawBorder();
drawPaddle();
//call next loop
requestAnimationFrame(loop);
}
function drawBackground() {
ctx.fillStyle = colorBackground;
ctx.fillRect(0, 0, canv.width, canv.height);
}
function drawBorder() {
let halfBorder = border * 0.5;
ctx.strokeStyle = colorBorder;
ctx.beginPath();
ctx.moveTo(halfBorder, height);
ctx.lineTo(halfBorder, halfBorder);
ctx.lineTo(width - halfBorder, halfBorder);
ctx.lineTo(width - halfBorder, height);
ctx.stroke();
}
function drawPaddle() {
ctx.fillStyle = colorPaddle;
ctx.fillRect(paddle.x - paddle.w * 0.5, paddle.y - paddle.h * 0.5, paddle.w, paddle.h);
}
function keyDown(ev) {
switch (ev.keyCode) {
case 37: //left arrow
movePaddle(direction.left);
break;
case 39: //right arrow
movePaddle(direction.right);
break;
}
}
function keyUp(ev) {
switch (ev.keyCode) {
case 37: //left arrow
case 39: //right arrow
movePaddle(direction.stop);
break;
}
}
function movePaddle(direction) {
switch (direction) {
case direction.left:
paddle.xv = -paddle.spd;
break;
case direction.right:
paddle.xv = paddle.spd;
break;
case direction.stop:
paddle.xv = 0;
break;
}
}
function newGame() {
paddle = new paddle();
}
function updatePaddle(delta) {
paddle.x += paddle.xv * delta;
}
function paddle() {
this.w = paddleWidth;
this.h = paddleHeight;
this.x = canv.width / 2;
this.y = canv.height - this.h * 3;
this.spd = paddleSpeed * width
this.xv = 0;
}
<body></body>

The mistake was in the function movePaddle. You had named the argument direction, and when you used direction.left, you meant to use the globally defined direction object, however since the function argument is local, your function argument was being used, which was just an integer.
Simply rename the function argument to fix the code.
"use strict";
//gameParameters
const height = 550;
const width = height;
const border = 15;
const paddleHeight = 15;
const paddleWidth = 45;
const paddleSpeed = 0.7; //fraction of screen width/sec
//colors
const colorBackground = 'black';
const colorBorder = 'pink';
const colorPaddle = 'pink';
//definitions
const direction = {
left: 0,
right: 1,
stop: 2
}
//gameCanvas
var canv = document.createElement('canvas');
canv.width = width;
canv.height = height;
document.body.appendChild(canv);
//context
var ctx = canv.getContext('2d');
ctx.lineWidth = border;
//game Variables
var paddle;
//start new game
newGame();
//event listeners
document.addEventListener("keydown", keyDown);
document.addEventListener("keyup", keyUp);
// gameLoop
var timeDelta, timeLast;
requestAnimationFrame(loop);
function loop(timeNow) {
if (!timeLast) {
timeLast = timeNow;
}
//calcTimeDifference
timeDelta = (timeNow - timeLast) * 0.001; //ms => sec
timeLast = timeNow;
//update
updatePaddle(timeDelta);
//draw
drawBackground();
drawBorder();
drawPaddle();
//call next loop
requestAnimationFrame(loop);
}
function drawBackground() {
ctx.fillStyle = colorBackground;
ctx.fillRect(0, 0, canv.width, canv.height);
}
function drawBorder() {
let halfBorder = border * 0.5;
ctx.strokeStyle = colorBorder;
ctx.beginPath();
ctx.moveTo(halfBorder, height);
ctx.lineTo(halfBorder, halfBorder);
ctx.lineTo(width - halfBorder, halfBorder);
ctx.lineTo(width - halfBorder, height);
ctx.stroke();
}
function drawPaddle() {
ctx.fillStyle = colorPaddle;
ctx.fillRect(paddle.x - paddle.w * 0.5, paddle.y - paddle.h * 0.5, paddle.w, paddle.h);
}
function keyDown(ev) {
switch (ev.keyCode) {
case 37: //left arrow
movePaddle(direction.left);
break;
case 39: //right arrow
movePaddle(direction.right);
break;
}
}
function keyUp(ev) {
switch (ev.keyCode) {
case 37: //left arrow
case 39: //right arrow
movePaddle(direction.stop);
break;
}
}
function movePaddle(to_direction) {
switch (to_direction) {
case direction.left:
paddle.xv = -paddle.spd;
break;
case direction.right:
paddle.xv = paddle.spd;
break;
case direction.stop:
paddle.xv = 0;
break;
}
}
function newGame() {
paddle = new paddle();
}
function updatePaddle(delta) {
paddle.x += paddle.xv * delta;
}
function paddle() {
this.w = paddleWidth;
this.h = paddleHeight;
this.x = canv.width / 2;
this.y = canv.height - this.h * 3;
this.spd = paddleSpeed * width
this.xv = 0;
}
<body></body>

Related

Why isn't my score function showing up in my canvas with ctx.fillText?

I'm developing a snake game using canvas but am having trouble with displaying the player's score in the upper right corner. This should be handled in the drawScore function but the text doesn't appear. I'm not getting any errors in the console, nor can I find any problem with the code itself.
Any advice would be appreciated!
class SnakePart {
constructor(x,y) {
this.x = x;
this.y = y;
}
}
const body = document.body;
const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');
let speed = 7; // base speed variable of snake
const snakeParts = [];
let tailLength = 2;
let tileCount = 20;//number of tiles on screen
let headX = 10;//snake width
let headY = 10;//snake height
let tileSize = canvas.width / tileCount - 2;//size of tiles where apple spawns
let xv = 0;// x axis velocity
let yv = 0;//y axis velocity
let ax = 5;//apple position x axis
let ay = 5;//apple position y axis
let score = 0;
//draws game loop
function drawGame(){
//game loop
clearScreen();
changeSnakePosition();
checkAppleCollision();
drawApple();
drawSnake();
drawScore();
setTimeout(drawGame, 1000/speed);
}
function drawScore(){
ctx.fillStyle = 'white';
ctx.font = '12px Helvetica';
ctx.fillText = ("Score: " + score, canvas.width-50, 10);
}
function clearScreen(){
ctx.fillStyle = 'black';
ctx.fillRect(0,0,canvas.width,canvas.height);
}
function drawSnake(){
ctx.fillStyle = 'orange';
ctx.fillRect(headX * tileCount, headY * tileCount, tileSize,tileSize);
ctx.fillStyle = 'green'
for(let i = 0; i<snakeParts.length; i++){
let part = snakeParts[i];
ctx.fillRect(part.x *tileCount,part.y*tileCount,tileSize,tileSize)
}
snakeParts.push(new SnakePart(headX,headY)); //put a segment at the end of the snake next to the head
while(snakeParts.length > tailLength){
snakeParts.shift(); //remove the furthest item from the snake parts if we have more than our tailSize.
}
}
body.addEventListener('keydown', keyDown);
function keyDown(event){
switch(event.keyCode) {
case 37:
if(xv == 1)
return;
yv = 0;
xv = -1
break;
case 38:
if(yv == 1)
return;
yv= -1;
xv = 0;
break;
case 39:
if(xv == -1)
return;
yv = 0;
xv = 1
break;
case 40:
if(yv == -1)
return;
yv = 1;
xv = 0;
}
}
function changeSnakePosition(){
headX = headX + xv;
headY = headY + yv;
}
function drawApple(){
ctx.fillStyle = 'red';
ctx.fillRect(ax*tileCount,ay*tileCount,tileSize,tileSize)
}
function checkAppleCollision(){
if(ax === headX && ay == headY){
ax = Math.floor(Math.random()*tileCount);
ay = Math.floor(Math.random()*tileCount);
tailLength++;
score++;
speed++;
}
}
drawGame();
<canvas id="canvas"></canvas>
The problem is this line :
ctx.fillText = ("Score: " + score, canvas.width-50, 10);
Which should be :
ctx.fillText("Score: " + score, canvas.width-50, 10);
Here's a stripped down example :
const body = document.body;
const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');
let score = 0;
function drawGame() {
clearScreen();
drawScore();
}
function drawScore() {
ctx.fillStyle = 'white';
ctx.font = '12px Helvetica';
ctx.fillText("Score: " + score, canvas.width-50, 10);
}
function clearScreen() {
ctx.fillStyle = 'black';
ctx.fillRect(0,0,canvas.width,canvas.height);
}
drawGame();
<canvas id="canvas"></canvas>

how the cube will stand on the floor in a parcur game

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);
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.

requestAnimationFrame too fast

I am creating simple animation in canvas. I use requestanimationframe to control animation. There is 3 circle. But i can only see 3 circle and animation is too fast. My question is how can i slow my animation and how can show each frame. here is my live link.
const swing = (time) => {
for(var i = 0; i < 3; i++) {
circle[i] = new ball();
circle[i].draw(i, circle[i].color);
}
requestAnimationFrame(swing);
}
requestAnimationFrame(swing);
//swing();
function ball(i){
this.x = random(100, 150);
this.y = random(40, 60);
this.radius = 45;
this.color = getRandomColor(random(1, 30));
this.strokeText = "m"
ctx.clearRect(0, 0, el.width, el.height);
this.draw = function(i, color){
ctx.beginPath();
ctx.font="30px Verdana";
ctx.arc(i*this.x, this.y, this.radius, 0, 2*Math.PI, false);
ctx.fillStyle = color;
ctx.globalAlpha = 0.5;
ctx.strokeText(i,i*this.x,this.y);
ctx.fill();
ctx.closePath();
}
}
Thanks in advance.
Edited:- I am creating something similar like this:- http://codepen.io/jscottsmith/pen/oWyxjp?editors=1010
Just a simple example, let three balls doing some circular motion:
// refer below
// http://codepen.io/jscottsmith/pen/oWyxjp?editors=1010
const el = document.getElementById('canvas'),
ctx = el.getContext('2d');
let circle = [];
el.width = document.body.clientWidth;
el.height = document.body.clientHeight;
const getRandomColor = (i) => {
let count = 30,
color = 1,
hue = (i / count * color) * 360;
return `hsla(${hue}, 100%, 50%, 1)`
}
for (var i = 0; i < 3; i++) {
circle[i] = new ball();
}
let angle = 0;
let speed = 0.02;
const swing = (time) => {
ctx.clearRect(0, 0, el.width, el.height);
for (var i = 0; i < 3; i++) {
circle[i].x = circle[i].x + Math.cos(angle) * 1;
circle[i].y = circle[i].y + Math.sin(angle) * 2;
}
for (var i = 0; i < 3; i++) {
circle[i].draw(i, circle[i].color);
}
angle += speed;
requestAnimationFrame(swing);
}
requestAnimationFrame(swing);
//swing();
function ball(i){
this.x = random(100, 150);
this.y = random(40, 60);
this.radius = 45;
this.color = getRandomColor(random(1, 30));
this.strokeText = "m"
this.draw = function(i, color){
ctx.beginPath();
ctx.font="30px Verdana";
ctx.arc(i*this.x, this.y, this.radius, 0, 2*Math.PI, false);
ctx.fillStyle = color;
ctx.globalAlpha = 0.5;
ctx.strokeText(i,i*this.x,this.y);
ctx.fill();
ctx.closePath();
}
}
function random (num1, num2) {
var max = Math.max(num1, num2);
var min = Math.min(num1, num2);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
#canvas {
width: 600px;
height: 600px;
}
<canvas id="canvas"></canvas>

How can i change the color of a javascript object?

I've created a simple code that looks a bit like "Impossible Game". I'm new with javascript so my question might sound a bit strange but i've created a few opjects like you can see below. When i change the color with ctx.fillstyle all my objects change this specific color. How can i give each object a different color?
Thanks ;)
var PlayerX;
var Blocka;
var Ground
var canvas = document.getElementById("gamefield");
ctx = canvas.getContext("2d");
var Gamespeed = 5;
var Gravity = 0.9;
var Score = 0;
var velocity = 0.01;
var jumping;
PlayerX = new Player();
Blocka = new Block(1);
Ground = new Gameground();
setInterval(Update, 20);
function startGame() {
}
function Player() {
// this staat voor verwijzing naar zichzelf
this.width = 30;
this.height = 50;
this.x = canvas.width / 4;
this.y = canvas.height / 3 * 2;
this.draw = function() {
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
function Block(kolb) {
this.width = 20;
this.height = 40;
this.show = true;
//this.x = canvas.width/2;
this.x = canvas.width + 20;
this.y = (canvas.height / 3 * 2) + 10;
this.draw = function() {
this.move();
if (this.show) {
if (kolb == 1) {
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
}
this.move = function() {
this.x -= Gamespeed;
this.death();
}
this.death = function() {
if (this.x <= 20) {
this.show = false;
}
}
}
function Gameground() {
// this staat voor verwijzing naar zichzelf
this.width = 800;
this.height = 150;
this.x = 0;
this.y = 450;
this.draw = function() {
ctx.fillStyle = "#00FFBF"
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
function Update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
Blocka.draw();
PlayerX.draw();
if (PlayerX.x < Blocka.x + Blocka.width &&
PlayerX.x + PlayerX.width > Blocka.x &&
PlayerX.y < Blocka.y + Blocka.height &&
PlayerX.height + PlayerX.y > Blocka.y) {
// collision detected!
ctx.fillStyle = "#FF0000";
}
Ground.draw();
}
window.addEventListener("keydown", checkKeyPressed, false);
function checkKeyPressed(e) {
if (e.keyCode == "32") { //kijkt of de spatiebalk is ingedrukt
var interval1, interval2, velo, tijd;
velo = 0.00001;
tijd = 20;
interval1 = setInterval(plus, tijd);
function plus() {
if (velo < 20) {
velo += 1.5;
} else {
velo -= 1.5;
}
if (PlayerX.y > 480) {
clearInterval(interval1);
interval2 = setInterval(min, tijd);
}
PlayerX.y += velo;
console.log(PlayerX.y);
}
function min() {
if (velo < 20) {
velo += 1.5;
} else {
velo -= 1.5;
}
if (PlayerX.y < 430) {
clearInterval(interval2);
}
PlayerX.y -= velo;
console.log(PlayerX.y);
}
}
}
You can use ctx.save(); and ctx.restore(); before and after your individual color changes.
This will save the current context state before changing the color, and then restore it back to it's original state after that one specific rectangle was drawn, yet before the others are drawn.
See below for example.
ctx.save();
ctx.fillStyle = "#00FFBF";
ctx.fillRect(this.x, this.y, this.width, this.height);
ctx.restore();
--- EDIT ---
As per the comments on OP's question - another resolution is to ensure that you call the fillStyle function before each fillRect function. See example and fiddle (provided by OP) below.
this.draw = function(){
ctx.fillStyle = "#00FFBF";
ctx.fillRect(this.x, this.y, this.width, this.height);
}
Here's OP's fiddle - https://jsfiddle.net/Nielsvangils/v9hL9d3k/

Remove object on collision with ball

I know you can fillRect right? And you can clearRect. But what happens if there's an animation and you have to remove an object although it would be redrawn from setInterval. How would you remove the fillRect?
Here's an example:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;
var circle = function (x, y, radius, fillCircle, color) {
ctx.beginPath();
ctx.fillStyle = color;
ctx.arc(x, y, radius, 0, Math.PI * 2, false);
if (fillCircle) {
ctx.fill();
} else {
ctx.stroke();
}
};
var drawRect = function (x, y, color) {
ctx.fillStyle = color;
ctx.fillRect(x, y, 20, 20)
}
var Object = function (xPos, yPos) {
this.x = xPos;
this.y = yPos;
}
// The Ball constructor
var Ball = function () {
this.x = width / 2;
this.y = height / 2;
this.xSpeed = 0;
this.ySpeed = 0;
this.radius = 10;
};
// Update the ball's position based on its speed
Ball.prototype.move = function () {
this.x += this.xSpeed;
this.y += this.ySpeed;
if (this.x < 11) {
this.x = 11;
} else if (this.x > width - 11) {
this.x = width - 11;
} else if (this.y < 11) {
this.y = 11;
} else if (this.y > height - 11) {
this.y = height - 11;
}
};
// Draw the ball at its current position
Ball.prototype.draw = function () {
circle(this.x, this.y, 10, true, "Black");
};
Object.prototype.draw = function () {
drawRect(this.x, this.y, "Black")
}
Object.prototype.drawKey = function (color) {
drawRect(this.x, this.y, "Yellow")
}
Object.prototype.checkCollision = function (direction) {
return (ball.x-ball.radius < this.x + 20)
&& (ball.x+ball.radius > this.x)
&& (ball.y-ball.radius < this.y + 20)
&& (ball.y+ball.radius > this.y)
;
}
function draw() {
ctx.clearRect(0, 0, width, height);
ball.draw();
object1.draw("Blue");
object2.draw();
object3.draw();
object4.draw();
object5.draw();
key.drawKey();
ctx.strokeRect(0, 0, width, height);
}
function simulate() {
for (z = 0; z < 5; z++) {
var prev_ball_x = ball.x;
var prev_ball_y = ball.y;
ball.move();
// handle collision here
if (object1.checkCollision() || object2.checkCollision() || object3.checkCollision() || object4.checkCollision() || object5.checkCollision()) {
ball.setDirection('stop');
// reset ball's position so they do not overlap
ball.x = prev_ball_x;
ball.y = prev_ball_y;
}
if (key.checkCollision()) {
ball.x = prev_ball_x;
ball.y = prev_ball_y;
}
}
$("body").keyup(function (event) {
ball.setDirection('stop');
})
}
setInterval(function () {
// separate drawing and simulating phases
simulate();
draw();
}, 30);
// Set the ball's direction based on a string
Ball.prototype.setDirection = function (direction) {
if (direction === "up") {
this.xSpeed = 0;
this.ySpeed = -1;
} else if (direction === "down") {
this.xSpeed = 0;
this.ySpeed = 1;
} else if (direction === "left") {
this.xSpeed = -1;
this.ySpeed = 0;
} else if (direction === "right") {
this.xSpeed = 1;
this.ySpeed = 0;
} else if (direction === "stop") {
this.xSpeed = 0;
this.ySpeed = 0;
}
};
// Create the ball object
var ball = new Ball();
var object1 = new Object(50, 0);
var object2 = new Object(50, 20);
var object3 = new Object(50, 40);
var object4 = new Object(50, 60);
var object5 = new Object(50, 80);
var key = new Object(70, 70);
// An object to convert keycodes into action names
var keyActions = {
37: "left",
38: "up",
39: "right",
40: "down"
};
// The keydown handler that will be called for every keypress
$("body").keydown(function (event) {
var direction = keyActions[event.keyCode];
ball.setDirection(direction);
});
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
<canvas id="canvas" width="800" height="200"></canvas>
You move around a ball with your arrow keys. When I collide with the yellow block, I want it to disappear. Using clearRect would not work simply because it would be redrawn in the setInterval. How would I make it disappear?
Generally when you have several items in a game you place them into a sort of objects array, then when you draw you loop through and call .draw() on each item. Doing it this way allows you to remove items you do not want (such as key), and as such it will no longer be drawn. In your case one thing we could do (assuming there is only a single key) is give your ball a hasKey property. And on collision set it from false to true. Then inside draw, if you wish to also remove the collisions you would do !ball.hasKey && key.checkCollision() inside your collision conditional for the key:
if(!ball.hasKey) key.drawKey();
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;
var circle = function (x, y, radius, fillCircle, color) {
ctx.beginPath();
ctx.fillStyle = color;
ctx.arc(x, y, radius, 0, Math.PI * 2, false);
if (fillCircle) {
ctx.fill();
} else {
ctx.stroke();
}
};
var drawRect = function (x, y, color) {
ctx.fillStyle = color;
ctx.fillRect(x, y, 20, 20)
}
var Object = function (xPos, yPos) {
this.x = xPos;
this.y = yPos;
}
// The Ball constructor
var Ball = function () {
this.x = width / 2;
this.y = height / 2;
this.xSpeed = 0;
this.ySpeed = 0;
this.radius = 10;
this.hasKey = false;
};
// Update the ball's position based on its speed
Ball.prototype.move = function () {
this.x += this.xSpeed;
this.y += this.ySpeed;
if (this.x < 11) {
this.x = 11;
} else if (this.x > width - 11) {
this.x = width - 11;
} else if (this.y < 11) {
this.y = 11;
} else if (this.y > height - 11) {
this.y = height - 11;
}
};
// Draw the ball at its current position
Ball.prototype.draw = function () {
circle(this.x, this.y, 10, true, "Black");
};
Object.prototype.draw = function () {
drawRect(this.x, this.y, "Black")
}
Object.prototype.drawKey = function (color) {
drawRect(this.x, this.y, "Yellow")
}
Object.prototype.checkCollision = function (direction) {
return (ball.x-ball.radius < this.x + 20)
&& (ball.x+ball.radius > this.x)
&& (ball.y-ball.radius < this.y + 20)
&& (ball.y+ball.radius > this.y)
;
}
function draw() {
ctx.clearRect(0, 0, width, height);
ball.draw();
object1.draw("Blue");
object2.draw();
object3.draw();
object4.draw();
object5.draw();
if(!ball.hasKey) key.drawKey();
ctx.strokeRect(0, 0, width, height);
}
function simulate() {
for (z = 0; z < 5; z++) {
var prev_ball_x = ball.x;
var prev_ball_y = ball.y;
ball.move();
// handle collision here
if (object1.checkCollision() || object2.checkCollision() || object3.checkCollision() || object4.checkCollision() || object5.checkCollision()) {
ball.setDirection('stop');
// reset ball's position so they do not overlap
ball.x = prev_ball_x;
ball.y = prev_ball_y;
}
if (!ball.hasKey && key.checkCollision()) {
ball.x = prev_ball_x;
ball.y = prev_ball_y;
ball.hasKey = true;
}
}
$("body").keyup(function (event) {
ball.setDirection('stop');
})
}
setInterval(function () {
// separate drawing and simulating phases
simulate();
draw();
}, 30);
// Set the ball's direction based on a string
Ball.prototype.setDirection = function (direction) {
if (direction === "up") {
this.xSpeed = 0;
this.ySpeed = -1;
} else if (direction === "down") {
this.xSpeed = 0;
this.ySpeed = 1;
} else if (direction === "left") {
this.xSpeed = -1;
this.ySpeed = 0;
} else if (direction === "right") {
this.xSpeed = 1;
this.ySpeed = 0;
} else if (direction === "stop") {
this.xSpeed = 0;
this.ySpeed = 0;
}
};
// Create the ball object
var ball = new Ball();
var object1 = new Object(50, 0);
var object2 = new Object(50, 20);
var object3 = new Object(50, 40);
var object4 = new Object(50, 60);
var object5 = new Object(50, 80);
var key = new Object(70, 70);
// An object to convert keycodes into action names
var keyActions = {
37: "left",
38: "up",
39: "right",
40: "down"
};
// The keydown handler that will be called for every keypress
$("body").keydown(function (event) {
var direction = keyActions[event.keyCode];
ball.setDirection(direction);
});
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
<canvas id="canvas" width="800" height="200"></canvas>

Categories

Resources