I'm making pong to get better at javascript but the player paddle doesn't move when the left key is pressed, and if I press the right key it doesn't stop going right.
I've checked the capitalization, semicolons, and rearranged the code but nothing changed.
var rightPressed = false;
var leftPressed = false;
var paused = false;
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if(e.keyCode == 39) {
rightPressed = true;
}
else if(e.keycode == 37) {
leftPressed = true;
}
else if(e.keycode == 32) {
paused = !paused;
}//pauses or unpause game
}
//handles when a key isn't being pushed
function keyUpHandler(e) {
if(e.keycode == 39) {
rightPressed = false;
}//tells our code that right isnt being pressed
else if(e.keyCode == 37) {
leftPressed = false;
}//tells code left isnt being pressed
}
var paddleHeight = 10;
var paddleWidth = 75;
var paddleX = (canvas.width-paddleWidth)/2;
var paddleY = canvas.height-paddleHeight-10;
function drawPaddle() {
ctx.fillRect(paddleX,paddleY,paddleWidth,paddleHeight);
ctx.fillStyle = "white";
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
drawPaddle();
if (!paused){//what to do when paused
if (x + dx > canvas.width - ballRadius || x + dx < ballRadius) {
dx = -dx;
}
if (y + dy < ballRadius) {
dy = -dy;
}
if (rightPressed && paddleX < canvas.width-paddleWidth) {
paddleX += 7;
}
else if(leftPressed && paddleX > 0) {
paddleX -= 7;}
x += dx;
y += dy;
//velocity
}
}
The paddle should move right when I press the right arrow key, left when I press the left arrow key, and pause when I hit the spacebar. Instead it doesn't go left or pause and won't stop going right.
Related
I am writing a game in javascript for the first time most of my code is not efficient. I am stuck on how to code a jumping method for my cube(the character for my game). The jump works but the player can double jump. The double jump occurs on the way down if the user presses the jump key again. I have tried setting a variable which will be modified when the player is on the ground and if it is true then your only allowed to jump but it hasn't worked. Here is the code:
//setting screen up
const canvas = document.getElementById('canvas');
const c = canvas.getContext('2d');
canvas.width = innerWidth;
canvas.height = innerHeight;
//ground
gHeight = canvas.height/1.3
function ground(){
c.fillStyle = 'white';
c.fillRect(0,gHeight,canvas.width,canvas.height-gHeight);
}
//player
class Player{
constructor(x,y,w,h){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.color = 'rgb(92,168,255)';
this.l = false;
this.r = false;
this.speed = 10
this.hp = 100;
this.jump = false;
this.jumpC = 0;
}
draw(){
c.fillStyle = this.color;
c.fillRect(this.x,this.y,this.w,this.h);
}
update(){
this.draw();
//gravity
if(this.y < gHeight - this.h){
this.y += 5;
}
//movement
if(this.l == true){
this.x -= this.speed;
}
if(this.r == true){
this.x += this.speed;
}
//jump
if(this.jump == true){
this.y -= 10;
this.jumpC += 5;
}
if (this.jumpC >= 100){
this.jump = false;
this.jumpC = 0;
}
}
}
var player = new Player(100, 100,50,50);
//main loop
var animationId;
function animate(){
c.fillStyle = 'rgba(0,0,0,0.7)';
c.fillRect(0,0, canvas.width, canvas.height);
animationId = requestAnimationFrame(animate);
//drawing the ground
ground();
//drawing the player
player.update();
//ending game
if(player.hp == 0){
cancelAnimationFrame(animationId);
}
}
//keypress
addEventListener('keydown', (event)=>{
if(event.keyCode == 37) {
player.l = true;
}
if(event.keyCode == 39) {
player.r = true;
}
if(event.keyCode == 38 && player.jump == false){
player.jump = true;
}
});
//keyup
addEventListener('keyup', (event)=>{
if(event.keyCode == 37 ) {
player.l = false;
}
if(event.keyCode == 39) {
player.r = false;
}
});
animate();
tell me if more info is needed
After the jump make it impossible to jump until the player reaches the ground.
if(event.keyCode == 38 && player.jump == false){ player.jump = true; }
I would add another comparison in this if like this:
if(event.keyCode == 38 && player.jump == false && player.isOnGround()){ player.jump = true; }
To check if the user landed
I have seen various pages on how to pause my canvas game but I am having no luck! I have used this code now but still, nothing happens. I want to use the 'p' key to pause and then play the game.
<html>
<title>Level Selector</title>
<canvas id="myCanvas" width="750" height="400"></canvas>
<style type="text/css">
canvas { background: #eee; }
</style>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 2;//Ball is moving in x direction at a constant rate
var dy = -2;//Ball is moving in y direction at a constant rate
var ballRadius = 10;//To see if ball is colliding with brick/canvas
var paddleHeight = 10;
var paddleWidth = 75;
var paddleX = (canvas.width-paddleWidth)/2;
var rightPressed = false;//This variable is false because the 'right arrow' key is not pressed.
var leftPressed = false;//This variable is false because the 'left arrow' key is not pressed.
var brickRowCount = 5;
var brickColumnCount = 8;
var brickWidth = 75;
var brickHeight = 20;
var brickPadding = 10;
var brickOffsetTop = 30;
var brickOffsetLeft = 30;
var score = 0;
var lives = 3;
var paused = false;
var bricks = [];//this is an array holding all the bricks
for(var c=0; c<brickColumnCount; c++) {
bricks[c] = [];
for(var r=0; r<brickRowCount; r++) {
bricks[c][r] = { x: 0, y: 0, status: 1 };//If status is '1' then draw it. However, is status is '0', fill in with background
}
}
document.addEventListener("keydown", keyDownHandler, false);//Functions only when key is pressed
document.addEventListener("keyup", keyUpHandler, false);//Functions only when key is not pressed
document.addEventListener("mousemove", mouseMoveHandler, false);//Functions only when mouse curcor moves
//keyCode(39) is the code for the 'right arrow' key and keyCode(37) is the code for the 'left arrow' key
function keyDownHandler(e) {
if(e.keyCode == 39) {
rightPressed = true;
}
else if(e.keyCode == 37) {
leftPressed = true;
}
}
function keyUpHandler(e) {
if(e.keyCode == 39) {
rightPressed = false;
}
else if(e.keyCode == 37) {
leftPressed = false;
}
}
function mouseMoveHandler(e) {
var relativeX = e.clientX - canvas.offsetLeft;//This represents the hoizontal mouse movement.
if(relativeX > 0 && relativeX < canvas.width) {
paddleX = relativeX - paddleWidth/2;
}
}
function paused{
if (e.keyCode == 80) pauseGame();
}
function pauseGame{
if (!paused)
{
paused = true;
} else if (paused)
{
paused= false;
}
}
//Collisions only true when:
// -The x position of the ball is greater than the x position of the brick.
// -The x position of the ball is less than the x position of the brick plus its width.
// -The y position of the ball is greater than the y position of the brick.
// -The y position of the ball is less than the y position of the brick plus its height.
function collisionDetection() {
for(var c=0; c<brickColumnCount; c++) {
for(var r=0; r<brickRowCount; r++) {
var b = bricks[c][r];
if(b.status == 1) {
if(x > b.x && x < b.x+brickWidth && y > b.y && y < b.y+brickHeight) {
dy = -dy;
b.status = 0;
score++;
if(score == brickRowCount*brickColumnCount) {
alert("YOU WIN, CONGRATULATIONS!");
document.location.reload();
}
}
}
}
}
}
//this is the score variable of the game
function drawScore() {
ctx.font = "16px Arial";
ctx.fillStyle = "#0095DD";
ctx.fillText("Score: "+score, 8, 20);
}
//this is the lives variable of the game
function drawLives() {
ctx.font = "16px Arial";
ctx.fillStyle = "#0095DD";
ctx.fillText("Lives: "+lives, canvas.width-65, 20);
}
//this creates the ball
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI*2);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
//this creates the paddle
function drawPaddle() {
ctx.beginPath();
ctx.rect(paddleX, canvas.height-paddleHeight, paddleWidth, paddleHeight);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
//this creates the bricks
function drawBricks() {
for(var c=0; c<brickColumnCount; c++) {
for(var r=0; r<brickRowCount; r++) {
if(bricks[c][r].status == 1) {
var brickX = (c*(brickWidth+brickPadding))+brickOffsetLeft;
var brickY = (r*(brickHeight+brickPadding))+brickOffsetTop;
bricks[c][r].x = brickX;
bricks[c][r].y = brickY;
ctx.beginPath();
ctx.rect(brickX, brickY, brickWidth, brickHeight);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
}
}
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);//clears canvas content from previous frame
drawBall();//this code draws the ball onto the canvas
drawPaddle();//this code draws the paddle onto the canvas
collisionDetection();//this codes enables the collision detection for the ball and bricks
drawBricks();//this code draws the bricks onto the canvas
drawScore();//this code draws the score variable onto the canvas
drawLives();//this code draws the lives variable onto the canvas
//Reverse Ball movement when the ball collides with wall in 'x' direction (Left/Right wall)
if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
dx = -dx;
}
//Reverse Ball movement when the ball collides with wall in 'y' direction (Top/Bottom wall)
if(y + dy < ballRadius) {
dy = -dy;
} else if(y + dy > canvas.height-ballRadius) {
if(x > paddleX && x < paddleX + paddleWidth) {
dy = -dy;//If the ball collides with the paddle, the ball is rebounded in the opposite direction.
}
else {
lives--;
if(!lives) {
alert("GAME OVER");
document.location.reload();
}
else {
x = canvas.width/2;
y = canvas.height-30;
dx = 2;
dy = -2;
paddleX = (canvas.width-paddleWidth)/2;
}
}
}
if(rightPressed && paddleX < canvas.width-paddleWidth) {//limits paddle movement in between the canvas width
paddleX += 7;//Paddle shifts 7 pixels in the positive x direction
}
else if(leftPressed && paddleX > 0) {//limits paddle movement in between the canvas width
paddleX -= 7;//Paddle shifts 7 pixels in the negative x direction
}
x += dx;//Ball is updated by painting it over each position it moves in
y += dy;//Ball is updated by painting it over each position it moves in
requestAnimationFrame(draw);
}
if(!paused)
{
update();
}
</script>
<body>
</body>
</html>
As you can see, everything else about the code is good apart from the pause feature. I am completely bemused and don't know how to make it work at all. Please give a tips or a solution thanks.
EDit: I have put in a pause variable and function but its not working still.
First remove all errors appearing in your console:
1) Add a "paused" var to you code:
var paused = false;
2) Remove unnecessary code:
if(!paused)
{
update();
}
3) Your togglePause function is using a keycode var that does not exists. Change it to:
function togglePause() {
paused = !paused;
draw();
}
Calling the draw function will do the trick to continue the game when paused.
4) And fix the function that calls it:
function pauseGameKeyHandler(e) {
var keyCode = e.keyCode;
switch(keyCode){
case 80: //p
togglePause();
break;
}
}
5) At the end of your draw function add a test to the paused variable:
if(!paused) {
requestAnimationFrame(draw);
}
Full code with the changes:
<html>
<title>Level Selector</title>
<canvas id="myCanvas" width="750" height="400"></canvas>
<style type="text/css">
canvas { background: #eee; }
</style>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 2;//Ball is moving in x direction at a constant rate
var dy = -2;//Ball is moving in y direction at a constant rate
var ballRadius = 10;//To see if ball is colliding with brick/canvas
var paddleHeight = 10;
var paddleWidth = 75;
var paddleX = (canvas.width-paddleWidth)/2;
var rightPressed = false;//This variable is false because the 'right arrow' key is not pressed.
var leftPressed = false;//This variable is false because the 'left arrow' key is not pressed.
var brickRowCount = 5;
var brickColumnCount = 8;
var brickWidth = 75;
var brickHeight = 20;
var brickPadding = 10;
var brickOffsetTop = 30;
var brickOffsetLeft = 30;
var score = 0;
var lives = 3;
var paused = false;
var bricks = [];//this is an array holding all the bricks
for(var c=0; c<brickColumnCount; c++) {
bricks[c] = [];
for(var r=0; r<brickRowCount; r++) {
bricks[c][r] = { x: 0, y: 0, status: 1 };//If status is '1' then draw it. However, is status is '0', fill in with background
}
}
document.addEventListener("keydown", keyDownHandler, false);//Functions only when key is pressed
document.addEventListener("keyup", keyUpHandler, false);//Functions only when key is not pressed
document.addEventListener("mousemove", mouseMoveHandler, false);//Functions only when mouse curcor moves
//keyCode(39) is the code for the 'right arrow' key and keyCode(37) is the code for the 'left arrow' key
function keyDownHandler(e) {
if(e.keyCode == 39) {
rightPressed = true;
}
else if(e.keyCode == 37) {
leftPressed = true;
}
}
function keyUpHandler(e) {
if(e.keyCode == 39) {
rightPressed = false;
}
else if(e.keyCode == 37) {
leftPressed = false;
}
}
function mouseMoveHandler(e) {
var relativeX = e.clientX - canvas.offsetLeft;//This represents the hoizontal mouse movement.
if(relativeX > 0 && relativeX < canvas.width) {
paddleX = relativeX - paddleWidth/2;
}
}
window.addEventListener('keydown', pauseGameKeyHandler, false);
function pauseGameKeyHandler(e) {
var keyCode = e.keyCode;
switch(keyCode){
case 80: //p
togglePause();
break;
}
}
function togglePause() {
paused = !paused;
draw();
}
//Collisions only true when:
// -The x position of the ball is greater than the x position of the brick.
// -The x position of the ball is less than the x position of the brick plus its width.
// -The y position of the ball is greater than the y position of the brick.
// -The y position of the ball is less than the y position of the brick plus its height.
function collisionDetection() {
for(var c=0; c<brickColumnCount; c++) {
for(var r=0; r<brickRowCount; r++) {
var b = bricks[c][r];
if(b.status == 1) {
if(x > b.x && x < b.x+brickWidth && y > b.y && y < b.y+brickHeight) {
dy = -dy;
b.status = 0;
score++;
if(score == brickRowCount*brickColumnCount) {
alert("YOU WIN, CONGRATULATIONS!");
document.location.reload();
}
}
}
}
}
}
//this is the score variable of the game
function drawScore() {
ctx.font = "16px Arial";
ctx.fillStyle = "#0095DD";
ctx.fillText("Score: "+score, 8, 20);
}
//this is the lives variable of the game
function drawLives() {
ctx.font = "16px Arial";
ctx.fillStyle = "#0095DD";
ctx.fillText("Lives: "+lives, canvas.width-65, 20);
}
//this creates the ball
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI*2);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
//this creates the paddle
function drawPaddle() {
ctx.beginPath();
ctx.rect(paddleX, canvas.height-paddleHeight, paddleWidth, paddleHeight);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
//this creates the bricks
function drawBricks() {
for(var c=0; c<brickColumnCount; c++) {
for(var r=0; r<brickRowCount; r++) {
if(bricks[c][r].status == 1) {
var brickX = (c*(brickWidth+brickPadding))+brickOffsetLeft;
var brickY = (r*(brickHeight+brickPadding))+brickOffsetTop;
bricks[c][r].x = brickX;
bricks[c][r].y = brickY;
ctx.beginPath();
ctx.rect(brickX, brickY, brickWidth, brickHeight);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
}
}
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);//clears canvas content from previous frame
drawBall();//this code draws the ball onto the canvas
drawPaddle();//this code draws the paddle onto the canvas
collisionDetection();//this codes enables the collision detection for the ball and bricks
drawBricks();//this code draws the bricks onto the canvas
drawScore();//this code draws the score variable onto the canvas
drawLives();//this code draws the lives variable onto the canvas
//Reverse Ball movement when the ball collides with wall in 'x' direction (Left/Right wall)
if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
dx = -dx;
}
//Reverse Ball movement when the ball collides with wall in 'y' direction (Top/Bottom wall)
if(y + dy < ballRadius) {
dy = -dy;
} else if(y + dy > canvas.height-ballRadius) {
if(x > paddleX && x < paddleX + paddleWidth) {
dy = -dy;//If the ball collides with the paddle, the ball is rebounded in the opposite direction.
}
else {
lives--;
if(!lives) {
alert("GAME OVER");
document.location.reload();
}
else {
x = canvas.width/2;
y = canvas.height-30;
dx = 2;
dy = -2;
paddleX = (canvas.width-paddleWidth)/2;
}
}
}
if(rightPressed && paddleX < canvas.width-paddleWidth) {//limits paddle movement in between the canvas width
paddleX += 7;//Paddle shifts 7 pixels in the positive x direction
}
else if(leftPressed && paddleX > 0) {//limits paddle movement in between the canvas width
paddleX -= 7;//Paddle shifts 7 pixels in the negative x direction
}
x += dx;//Ball is updated by painting it over each position it moves in
y += dy;//Ball is updated by painting it over each position it moves in
if(!paused) {
requestAnimationFrame(draw);
}
}
draw();
</script>
<body>
</body>
</html>
I'm having a few issues with my code. Can't get my cube to jump. Take a look at my code and let me know if you can help please.
My left, right and duck abilities all currently work at desired level, but I cannot get my cube to jump. I've been trying for three days and can't find anything online. My javascript is embedded within a tag in a html page.
var canvas = document.getElementById("gameCanvas");
var ctx = canvas.getContext("2d");
var coinRad = 8;
var coinX = 40;
var coinY = 80;
var x = 20;
var y = 510;
var w = 30;
var h = 50;
var rightPressed = false;
var leftPressed = false;
var ducked = false;
var jumping = false;
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if (e.keyCode == 39) {
rightPressed = true;
} else if (e.keyCode == 37) {
leftPressed = true;
} else if (e.keyCode == 40) {
ducked = true;
} else if (e.keycode == 32) {
jumping = true;
}
}
function keyUpHandler(e) {
if (e.keyCode == 39) {
rightPressed = false;
} else if (e.keyCode == 37) {
leftPressed = false;
} else if (e.keyCode == 40) {
ducked = false;
} else if (e.keycode == 32) {
jumping = false;
}
}
function drawCube() {
ctx.beginPath();
ctx.rect(x, y, w, h);
ctx.fillStyle = "Green";
ctx.fill();
ctx.closePath();
}
function run() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (leftPressed) {
if (x > 0) {
x -= 2.5;
}
} else if (rightPressed) {
if (x < canvas.width - w) {
x += 2.5;
}
}
if (jumping) {
y -= 10;
h -= 10;
}
if (ducked) {
y = 535;
h = 25;
} else {
y = 510;
h = 50;
}
drawCube();
}
setInterval(run, 10);
<canvas id="gameCanvas"></canvas>
Additionally, your keyCode check is improperly capitalized for the jumping condition.
else if (e.keyCode == 40) {
ducked = false;
} else if (e.keycode == 32) { //should be keyCode
jumping = false;
}
because when the run method end, you do this.
if (jumping) {
y -= 10;
h -= 10;
}
if (ducked) {
y = 535;
h = 25;
} else {
y = 510;
h = 50;
}
even if you change the values from Y and H, their values always change to 510 and 50 respectively, because the else in ducked condition.
Remove this else or find another logic to do the same
I am creating a 2 player tennis sort of game right now in JavaScript and I got the ball to make an alert box popup saying "gameover" when it hits the top, but I can't seem to make it work on the top border. If someone could tell me what I'm doing wrong thanks in advance.
I have inputted the code for my game below:
var canvas = document.getElementById("gameCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width / 2;
var y = canvas.height - 30;
var dx = 2;
var dy = -2;
var ballRadius = 10;
var paddleHeight = 10;
var paddleWidth = 75;
var paddle2Height = 10;
var paddle2Width = 75;
var paddleX = (canvas.width - paddleWidth) / 2;
var paddle2X = (canvas.width - paddleWidth) / 2;
var rightPressed = false;
var leftPressed = false;
var rightPressed2 = false;
var leftPressed2 = false;
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
ctx.fillStyle = "#0095DD"; //color of ball
ctx.fill();
ctx.closePath();
}
//Draws the bottom paddle
function drawPaddle1() {
ctx.beginPath();
ctx.rect(paddleX, canvas.height - paddleHeight, paddleWidth, paddleHeight);
ctx.fillStyle = "#0095DD"; //color of paddle
ctx.fill();
ctx.closePath();
}
//Draws the top paddle
function drawPaddle2() {
ctx.beginPath();
ctx.rect(paddle2X, 0, paddle2Width, paddle2Height);
ctx.fillStyle = "#0095DD"; //color of paddle
ctx.fill();
ctx.closePath();
}
function draw() {
//Checks collison for left and right
if (x + dx > canvas.width || x + dx < 0) {
dx = -dx;
}
//Paddle collison for top and down "still fixing"
if (y + dy < ballRadius || y + dy < 0) {
dy = -dy;
} else if (y + dy > canvas.height - ballRadius) {
if (x > paddleX && x < paddleX + paddleWidth) {
dy = -dy;
} else {
alert("GAME OVER");
document.location.reload();
}
}
//Clears canvas so the ball won't leave a trail
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall(); //Draws the ball
//Draws the paddle
drawPaddle1();
drawPaddle2();
//Makes the ball move
x += dx;
y += dy;
//Moves the paddle
if (rightPressed && paddleX < canvas.width - paddleWidth) {
paddleX += 7;
} else if (leftPressed && paddleX > 0) {
paddleX -= 7;
} else if (rightPressed2 && paddle2X < canvas.width - paddleWidth) {
paddle2X += 7;
} else if (leftPressed2 && paddle2X > 0) {
paddle2X -= 7;
}
}
//Handles the keyboard commands
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if (e.keyCode == 39) {
rightPressed = true;
} else if (e.keyCode == 68) {
rightPressed2 = true;
} else if (e.keyCode == 37) {
leftPressed = true;
} else if (e.keyCode == 65) {
leftPressed2 = true;
}
}
function keyUpHandler(e) {
if (e.keyCode == 39) {
rightPressed = false;
} else if (e.keyCode == 68) {
rightPressed2 = false;
} else if (e.keyCode == 37) {
leftPressed = false;
} else if (e.keyCode == 65) {
leftPressed2 = false;
}
}
//Refreshes screen every 10 seconds
setInterval(draw, 10);
* {
padding: 0;
margin: 0;
}
canvas {
background: #eee;
display: block;
margin: 0 auto;
}
<canvas id="gameCanvas" width="480" height="320"></canvas>
You are missing a block for paddle2.
//Paddle collison for top and down "still fixing"
if (y + dy < ballRadius || y + dy < 0) {
if (x > paddle2X && x < paddle2X + paddleWidth) {
dy = -dy;
} else {
alert("GAME OVER");
document.location.reload();
}
} else if (y + dy > canvas.height - ballRadius) {
if (x > paddleX && x < paddleX + paddleWidth) {
dy = -dy;
} else {
alert("GAME OVER");
document.location.reload();
}
}
Your game is cool. I just want to complete it.
JSfiddle
var canvas = document.getElementById("gameCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width / 2;
var y = canvas.height - 30;
var dx = 2;
var dy = -2;
var ballRadius = 10;
var paddleHeight = 10;
var paddleWidth = 75;
var paddle2Height = 10;
var paddle2Width = 75;
var paddleX = (canvas.width - paddleWidth) / 2;
var paddle2X = (canvas.width - paddleWidth) / 2;
var rightPressed = false;
var leftPressed = false;
var rightPressed2 = false;
var leftPressed2 = false;
var isStart = false;
var interval;
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
ctx.fillStyle = "#0095DD"; //color of ball
ctx.fill();
ctx.closePath();
}
//Draws the bottom paddle
function drawPaddle1() {
ctx.beginPath();
ctx.rect(paddleX, canvas.height - paddleHeight, paddleWidth, paddleHeight);
ctx.fillStyle = "#0095DD"; //color of paddle
ctx.fill();
ctx.closePath();
}
//Draws the top paddle
function drawPaddle2() {
ctx.beginPath();
ctx.rect(paddle2X, 0, paddle2Width, paddle2Height);
ctx.fillStyle = "#0095DD"; //color of paddle
ctx.fill();
ctx.closePath();
}
function draw() {
//Checks collison for left and right
if (x + dx > canvas.width || x + dx < 0) {
dx = -dx;
}
//Paddle collison for top and down "still fixing"
if (y + dy < ballRadius) {
console.log("touch border top - Game over");
start();
}
if (y + dy >= ballRadius && y + dy <= ballRadius + paddle2Height && x > paddle2X && x < paddle2X + paddleWidth) {
console.log("touch paddle top");
dy = -dy;
}
if (y + dy > canvas.height - ballRadius) {
if (x > paddleX && x < paddleX + paddleWidth) {
console.log("touch paddle bot");
dy = -dy;
} else {
console.log("touch border bot - Game over");
start();
}
}
//Clears canvas so the ball won't leave a trail
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall(); //Draws the ball
//Draws the paddle
drawPaddle1();
drawPaddle2();
//Makes the ball move
x += dx;
y += dy;
//Moves the paddle
if (rightPressed && paddleX < canvas.width - paddleWidth) {
paddleX += 7;
};
if (leftPressed && paddleX > 0) {
paddleX -= 7;
};
if (rightPressed2 && paddle2X < canvas.width - paddleWidth) {
paddle2X += 7;
};
if (leftPressed2 && paddle2X > 0) {
paddle2X -= 7;
}
}
//Handles the keyboard commands
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
document.getElementById("start-button").addEventListener("click", start);
function keyDownHandler(e) {
if (e.keyCode == 39) {
rightPressed = true;
};
if (e.keyCode == 68) {
rightPressed2 = true;
};
if (e.keyCode == 37) {
leftPressed = true;
};
if (e.keyCode == 65) {
leftPressed2 = true;
}
}
function keyUpHandler(e) {
if (e.keyCode == 39) {
rightPressed = false;
};
if (e.keyCode == 68) {
rightPressed2 = false;
};
if (e.keyCode == 37) {
leftPressed = false;
};
if (e.keyCode == 65) {
leftPressed2 = false;
}
}
function start() {
isStart = !isStart;
if (isStart) {
x = canvas.width / 2;
y = canvas.height - 30;
paddleX = (canvas.width - paddleWidth) / 2;
paddle2X = (canvas.width - paddleWidth) / 2;
//Refreshes screen every 10 seconds
interval = setInterval(draw, 10);
} else
clearInterval(interval);
}
* {
padding: 0;
margin: 0;
}
canvas {
background: #eee;
display: block;
margin: 0 auto;
}
button {
display: block;
margin: 10px auto;
padding: 10px;
}
<canvas id="gameCanvas" width="480" height="320"></canvas>
<button id="start-button">Start/Pause</button>
I'm working on a simple html/js project to get a box moving in a canvas that can shoot a ball. I got the box moving but I cant get the ball to appear. The program makes it to the drawBall() and moveBall()(Tested using alerts) functions but they don't do anything. I've been working on this the past hour and so and I just can't get it to work. Here's my javascript code that moves the box and should draw a ball whenever the spacebar is released.
function init() {
//canvas = document.getElementById('canvas');
context = $('#canvas')[0].getContext('2d');
WIDTH = $('#canvas').width();
HEIGHT = $('#canvas').height();
block_x = WIDTH / 2;
block_y = HEIGHT / 2;
setInterval('draw()', 25);
}
function clearCanvas() {
context.clearRect(0,0,WIDTH,HEIGHT);
}
function draw() {
clearCanvas();
if(shotBall)
{
drawBall();
moveBall();
}
if (rightKey) block_x += 5;
else if (leftKey) block_x -= 5;
if (upKey) block_y -= 5;
else if (downKey) block_y += 5;
if (block_x <= 0) block_x = 0;
if ((block_x + block_w) >= WIDTH) block_x = WIDTH - block_w;
if (block_y <= 0) block_y = 0;
if ((block_y + block_h) >= HEIGHT) block_y = HEIGHT - block_h;
context.fillRect(block_x, block_y, block_w, block_h);
}
function drawBall() {
context.beginPath();
context.arc(ball_x, ball_y, ball_radius, 0, Math.PI * 2, false);
}
function moveBall() {
ball_y += 1;
ball_x -= 1;
}
function onKeyDown(evt) {
if (evt.keyCode == 68) rightKey = true;
else if (evt.keyCode == 65) leftKey = true;
if (evt.keyCode == 87) upKey = true;
else if (evt.keyCode == 83) downKey = true;
}
function onKeyUp(evt) {
if (evt.keyCode == 68) rightKey = false;
else if (evt.keyCode == 65) leftKey = false;
if (evt.keyCode == 87) upKey = false;
else if (evt.keyCode == 83) downKey = false;
if(evt.keyCode == 32) createBall();
}
function createBall()
{
ball_x = block_x + (block_w / 2);
ball_y = block_y + (block_y / 2);
radius = 20;
shotBall = true;
}
$(document).keydown(onKeyDown);
$(document).keyup(onKeyUp);
When I tried your code
the problem that I can see is that you haven't initialized the block_w, and block_h and the ball_radius variables, because these values are seems to be undefined as I see in firebug tool.
So you have to make sure that you have defined and initialized every variable that you use.
Also You have to make sure that you are calling every function that you have defined.
When I put values manually in the context.arc(23, 34, 45, 0, Math.PI*2, false); function
then it works fine for me.
So make sure you have defined and initialized every variable.