Startscreen on Javascript Game / Clickable Play button - javascript

I'm in the middle of making a start-screen for my JavaScript Breakout game. I've (poorly) made the background and a play button.
The background is inside the canvas, which I want. But when I want to place the clickable play button ontop of the background in the canvas, it disappears. I've tried making another picture, and I can place that ontop, I just cant make it clickable.
I dont know what the best solution is, I'm very new to JavaScript.
//Script
var background = new Image();
background.src="breakoutbg.png";
var play = new Image();
play.src="breaoutplay.png";
var startBtn = document.getElementById('startBtn');
//game
function drawCanvas() {
ctx.beginPath();
ctx.drawImage(background,0,0);
ctx.fill();
ctx.closePath();
}
function drawPlay() {
ctx.beginPath();
ctx.drawImage(play,250,250);
ctx.fill();clickable;
ctx.closePath();
}
<div id="container">
<button type="button" id="startBtn" onclick="draw()" >
<img src="breaoutplay.png">
</button>
<canvas id="myCanvas" width="600" height="550"></canvas>
</div>
I dont know if I gave enough of the code, for someone to have an Idea about it. The entire code is on github: https://github.com/katrinemira/katrinemira.github.io/blob/master/breakout.html

Add this to ur CSS
#container {
display: inline-block;
position: relative;
}
#startBtn {
border: none;
background: none;
position: absolute;
top: 50%;
left: 50%;
z-index: 1;
transform: translate(-50%,-50%);
-webkit-transform: translate(-50%,-50%);
-moz-transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
}
The above code will place the button on the canvas in the center.
Also add z-index: 1; to the button to place it on top of canvas
<html>
<head>
<center>
<style>
body {
background-color: black;
}
* {
padding: 0;
margin: 0;
}
canvas {
background: #353d49;
display: block;
margin: 100px;
}
#startBtn {
border: none;
background: none;
position: absolute;
top: 50%;
left: 50%;
z-index: 1;
transform: translate(-50%,-50%);
-webkit-transform: translate(-50%,-50%);
-moz-transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
}
#container {
display: inline-block;
position: relative;
}
#myCanvas {
position: relative;
}
</style>
</head>
<body>
<div id="container">
<button type="button" id="startBtn" onclick="draw()"><img src="https://1.bp.blogspot.com/-fVAKH-3TLuo/W5onDDHje0I/AAAAAAAAB4I/q2ooE6GuzQkS80dtw1JILXjFWdfQ3IKkwCLcBGAs/s1600/breaoutplay.png">
</button>
<canvas id="myCanvas" width="600" height="550"></canvas>
</div>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var ballRadius = 9;
var x = canvas.width - Math.floor(Math.random() * 600)
var y = canvas.height - 30;
var dx = 5;
var dy = -4;
var paddleHeight = 10;
var paddleWidth = 75;
var paddleX = (canvas.width - paddleWidth) / 2;
var rightPressed = false;
var leftPressed = false;
var brickRowCount = 7;
var brickColumnCount = 5;
var brickWidth = 75;
var brickHeight = 20;
var brickPadding = 4;
var brickOffsetTop = 30;
var brickOffsetLeft = 30;
var score = 0;
var lives = 3;
var background = new Image();
background.src = "https://1.bp.blogspot.com/-hs2fckXJBkE/W5obuBm9kII/AAAAAAAAB38/C89KFBJCIlEwfl-g8d-T1Cu4cHFWjYI2QCLcBGAs/s1600/breakoutbg.png";
var play = new Image();
play.src = "https://1.bp.blogspot.com/-fVAKH-3TLuo/W5onDDHje0I/AAAAAAAAB4I/q2ooE6GuzQkS80dtw1JILXjFWdfQ3IKkwCLcBGAs/s1600/breaoutplay.png";
var startBtn = document.getElementById('startBtn');
//game
function drawCanvas() {
ctx.beginPath();
ctx.drawImage(background, 0, 0);
ctx.fill();
ctx.closePath();
}
function drawPlay() {
ctx.beginPath();
ctx.drawImage(play, 250, 250);
ctx.fill();
clickable;
ctx.closePath();
}
function newBrick() {
return {
x: 0,
y: 0,
status: 1
};
}
var bricks = [];
for (var c = 0; c < brickColumnCount; c++) {
bricks[c] = [];
for (var r = 0; r < brickRowCount; r++) {
bricks[c].unshift(newBrick());
}
}
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
document.addEventListener("mousemove", mouseMoveHandler, false);
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;
if (relativeX > 0 && relativeX < canvas.width) {
paddleX = relativeX - paddleWidth / 2;
}
}
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 + ballRadius && y > b.y && y < b.y + brickHeight + ballRadius) {
dy = -dy;
b.status = 0;
score++;
if (score == 9999) {
alert("YOU WIN, CONGRATS!");
document.location.reload();
}
}
}
}
}
}
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
function drawPaddle() {
ctx.beginPath();
ctx.rect(paddleX, canvas.height - paddleHeight, paddleWidth, paddleHeight);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
function moreBricks() {
bricks.unshift([]);
newBrick();
brickColumnCount++;
for (r = 0; r < brickRowCount; r++) {
bricks[0].unshift(newBrick());
}
}
function drawBricks() {
for (var c = 0; c < brickColumnCount; c++) {
for (var r = 0; r < brickRowCount; r++) {
if (bricks[c][r].status == 1) {
var brickX = (r * (brickWidth + brickPadding)) + brickOffsetLeft;
var brickY = (c * (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 drawScore() {
ctx.font = "16px Arial";
ctx.fillStyle = "#0095DD";
ctx.fillText("Score: " + score, 8, 20);
}
function drawLives() {
ctx.font = "16px Arial";
ctx.fillStyle = "#0095DD";
ctx.fillText("Lives: " + lives, canvas.width - 65, 20);
}
var frameCount = 0;
const FRAME_COUNT_NEW_LINE = 500;
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
startBtn.style.display = 'none';
frameCount += 1;
if (frameCount === FRAME_COUNT_NEW_LINE) {
frameCount = 0;
moreBricks();
}
drawBricks();
drawBall();
drawPaddle();
drawScore();
drawLives();
collisionDetection();
if (x + dx > canvas.width - ballRadius || x + dx < ballRadius) {
dx = -dx;
}
if (y + dy < ballRadius) {
dy = -dy;
} else if (y + dy > canvas.height - ballRadius) {
if (x > paddleX && x < paddleX + paddleWidth) {
dy = -dy;
} else {
lives--;
if (!lives) {
document.location.reload();
} else {
x = canvas.width - Math.floor(Math.random() * 600);
y = canvas.height - 30;
dx = 5;
dy = -4;
paddleX = (canvas.width - paddleWidth) / 2;
}
}
}
if (rightPressed && paddleX < canvas.width - paddleWidth) {
paddleX += 7;
} else if (leftPressed && paddleX > 0) {
paddleX -= 7;
}
x += dx;
y += dy;
requestAnimationFrame(draw);
}
drawCanvas();
drawPlay();
</script>
</body>
</html>

Related

How to make bullet launcher point in mouse position? Canvas JavaScript

When the mouse moves it doesn't point in the mouseX or mouseY direction.
The current method points and rotates at the top right point slightly offset on the canvas.
All the other SO questions didn't work for this specific game.
I would prefer the most straightforward answer and an explanation of how it works.
I need a vanilla javascript answer.
/**
* #type { HTMLCanvasElement }
*/
var scene = document.getElementById("scene");
var ctx = scene.getContext("2d");
var mouseX = 0;
var mouseY = 0;
var prevSceneTranslateXL = 0;
var prevSceneTranslateYL = 0;
var prevSceneTranslateXR = 0;
var prevSceneTranslateYR = 0;
var sceneTranslateX = 0;
var sceneTranslateY = 0;
var friction = 4 / 5;
var keysDown = [];
scene.width = window.innerWidth;
scene.height = window.innerHeight;
var bg = new Image();
bg.src = "./assets/groundBgAlt.png";
class Player {
constructor(x, y, radius, color, borderColor) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.borderColor = borderColor;
this.velX = 0;
this.velY = 0;
this.speed = 15;
this.angle = 0;
}
}
class Enemy {
constructor(radius, color, borderColor) {
this.x = Math.random() * scene.width + 25;
this.y = Math.random() * scene.height + 25;
this.radius = radius;
this.color = color;
this.borderColor = borderColor;
this.velX = 0;
this.velY = 0;
this.speed = 15;
this.angle = 0;
}
}
var player1 = new Player(1000, 1000, 25, "#0080ff", "#606060");
var enemies = [];
// for (i = 0; i < 20; i++) {
// enemies.push(new Enemy(50, 50, "#ff0000", "#bb0000"));
// }
function drawPlayer(player) {
ctx.strokeStyle = "#606060";
ctx.lineWidth = 2;
ctx.fillStyle = "#cccccc";
ctx.save();
ctx.beginPath();
ctx.translate(player.x, player.y);
ctx.rotate(player1.angle);
ctx.roundRect(-10, -45, 20, 25, 2);
ctx.fill();
ctx.stroke();
ctx.closePath();
ctx.restore();
ctx.strokeStyle = player.borderColor;
ctx.lineWidth = 2;
ctx.fillStyle = player.color;
ctx.beginPath();
ctx.arc(player.x, player.y, player.radius, 0, 2 * Math.PI);
ctx.fill();
ctx.stroke();
ctx.closePath();
}
function drawEnemies(enemy) {
ctx.strokeStyle = enemy.borderColor;
ctx.lineWidth = 3;
ctx.fillStyle = enemy.color;
ctx.beginPath();
ctx.rect(enemy.x, enemy.y, enemy.width, enemy.height);
ctx.fill();
ctx.stroke();
ctx.closePath();
}
var gradientBG = ctx.createRadialGradient(1000, 1000, 1000, 1000, 1000, 100);
gradientBG.addColorStop(0.0, "#ffffff");
gradientBG.addColorStop(1.0, "#eeeeee");
function main() {
ctx.clearRect(-250, -250, 2500, 2500);
ctx.fillStyle = gradientBG;
ctx.fillRect(0, 0, 2000, 2000);
if (player1.x < 0) {
sceneTranslateX = prevSceneTranslateXL;
player1.x = 0;
player1.velX = 0;
}
if (player1.x > 2000) {
sceneTranslateX = prevSceneTranslateXR;
player1.x = 2000;
player1.velX = 0;
}
if (player1.y < 0) {
sceneTranslateY = prevSceneTranslateYL;
player1.y = 0;
player1.velY = 0;
}
if (player1.y > 2000) {
sceneTranslateY = prevSceneTranslateYR;
player1.y = 2000;
player1.velY = 0;
}
if (keysDown["w"] || keysDown["ArrowUp"]) {
if (player1.velY > player1.speed * -1) {
player1.velY--;
}
}
if (keysDown["a"] || keysDown["ArrowLeft"]) {
if (player1.velX > player1.speed * -1) {
player1.velX--;
}
}
if (keysDown["s"] || keysDown["ArrowDown"]) {
if (player1.velY < player1.speed) {
player1.velY++;
}
}
if (keysDown["d"] || keysDown["ArrowRight"]) {
if (player1.velX < player1.speed) {
player1.velX++;
}
}
player1.velX *= friction;
player1.velY *= friction;
player1.x += player1.velX;
player1.y += player1.velY;
sceneTranslateX *= friction;
sceneTranslateY *= friction;
sceneTranslateX += -player1.velX;
sceneTranslateY += -player1.velY;
prevSceneTranslateXL = sceneTranslateX - 1;
prevSceneTranslateYL = sceneTranslateY - 1;
prevSceneTranslateXR = sceneTranslateX + 1;
prevSceneTranslateYR = sceneTranslateY + 1;
ctx.translate(sceneTranslateX / 5, sceneTranslateY / 5);
drawPlayer(player1);
// for (i = 0; i < enemies.length; i++) {
// drawEnemies(enemies[i]);
// }
requestAnimationFrame(main);
}
ctx.translate((scene.width / 2) - player1.x, (scene.height / 2) - player1.y);
main();
document.addEventListener("keydown", (e) => {
keysDown[e.key] = true;
});
document.addEventListener("keyup", (e) => {
keysDown[e.key] = false;
});
document.addEventListener("mousemove", (e) => {
var angle = Math.atan2(e.pageY - player1.y, e.pageX - player1.x);
player1.angle = angle;
});
* {
font-family: roboto, Arial, Helvetica, sans-serif, system-ui, system 'Courier New', Courier, monospace;
padding: 0px 0px;
margin: 0px 0px;
box-sizing: border-box;
}
body {
background: radial-gradient(circle, #bbbbbb 10%, #cccccc);
overflow: hidden;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles/styles.css">
<script src="scripts/index.js" defer></script>
<title>Document</title>
</head>
<body>
<canvas id="scene" width="1024" height="576"></canvas>
</body>
</html>
The way the game is made makes it really hard to rotate objects.

Game doesn't work, but my code looks fine

I've been following an online tutorial for making a Breakout Game using JS, but it doesn't work. Even something as simple as an alert popup doesn't work. All of this started happening after I created the keyboard controls, and all of the errors are in that section as well. But it looks fine, i've compared the sample code with mine and everything's identical. What am I doing wrong?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Gamedev</title>
<style>
* {
padding: 0;
margin: 0;
}
canvas {
background:rgba(104, 10, 93, 0.61);
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="480" height="320"></canvas>
</body>
<script>
// JS goes here
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var ballRadius = 10;
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 2;
var dy = -2;
var paddleHeight = 10;
var paddleWidth = 75;
var paddleX = (canvas.width-paddleWidth)/2;
var rightPressed = false;
var leftPressed = false;
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUphandler, false);
alert('test')
function keyDownHandler(e) {
if(e.key == "Right" || e.key == "ArrowRight") {
rightPressed = true;
}
elseif(e.key == "Left" || e.key == "ArrowLeft") {
leftPressed = true;
}
}
function keyUpHandler(e) {
if(e.key -- "Right" || e.key == "ArrowRight") {
rightPressed = false;
}
elseif(e.key-- "Left" || e.key == "ArrowLeft") {
leftPressed = false;
}
}
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
ctx.fillStyle = "#EE82EE";
ctx.fill();
ctx.closePath();
}
function drawPaddle() {
ctx.beginPath();
ctx.rect(paddleX, canvas.height - paddleheight, paddleWidth, paddleHeight);
ctx.fillStyle = "#9400D3";
ctx.fill();
ctx.closePath();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
drawPaddle();
if(x + dx > canvas.width - ballRadius || x + dx < ballRadius) {
dx = -dx;
}
if (y + dy > canvas.height - ballRadius || y + dy < ballRadius) {
dy = -dy;
}
if(rightPressed) {
paddleX += 7;
if (paddleX + paddleWidth > canvas.width){
paddleX = canvas.width - paddleWidth;
}
}
else if(leftPressed) {
paddleX -= 7;
if (paddleX < 0){
paddleX = 0;
}
x += dx;
y += dy;
}
}
setInterval(draw, 10);
</script>
</body>
</html>
You have numerous typos in your code. This version should work better (at least it does not generate any errors):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Gamedev</title>
<style>
* {
padding: 0;
margin: 0;
}
canvas {
background:rgba(104, 10, 93, 0.61);
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="480" height="320"></canvas>
</body>
<script>
// JS goes here
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var ballRadius = 10;
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 2;
var dy = -2;
var paddleHeight = 10;
var paddleWidth = 75;
var paddleX = (canvas.width-paddleWidth)/2;
var rightPressed = false;
var leftPressed = false;
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
alert('test')
function keyDownHandler(e) {
if(e.key == "Right" || e.key == "ArrowRight") {
rightPressed = true;
}
else if(e.key == "Left" || e.key == "ArrowLeft") {
leftPressed = true;
}
}
function keyUpHandler(e) {
if (e.key == "Right" || e.key == "ArrowRight") {
rightPressed = false;
}
else if(e.key == "Left" || e.key == "ArrowLeft") {
leftPressed = false;
}
}
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
ctx.fillStyle = "#EE82EE";
ctx.fill();
ctx.closePath();
}
function drawPaddle() {
ctx.beginPath();
ctx.rect(paddleX, canvas.height - paddleHeight, paddleWidth, paddleHeight);
ctx.fillStyle = "#9400D3";
ctx.fill();
ctx.closePath();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
drawPaddle();
if(x + dx > canvas.width - ballRadius || x + dx < ballRadius) {
dx = -dx;
}
if (y + dy > canvas.height - ballRadius || y + dy < ballRadius) {
dy = -dy;
}
if (rightPressed) {
paddleX += 7;
if (paddleX + paddleWidth > canvas.width){
paddleX = canvas.width - paddleWidth;
}
}
else if(leftPressed) {
paddleX -= 7;
if (paddleX < 0){
paddleX = 0;
}
x += dx;
y += dy;
}
}
setInterval(draw, 10);
</script>
</html>

Collision detection of a ball with the canvas edges

I was following the Mozilla game dev tutorial, and making a simple Breakout game in the HTML5 Canvas and JS.
However, I wanted to enlarge the canvas because it was a bit small so I tried a 800x600 canvas. Then, I noticed the ball was a bit too slow for this new canvas size.
Originaly in the mozilla tutorial, the ball speed was 2. I tried to use 3 instead. And thus comes the problem ...
As I use requestAnimationFrame, which refreshes about 60x per second, we can say that my ball will move about 3 x 60 = 180px per second.
To detect the collision with the right edge of the canvas I use the condition:
if (ball.x + ball.radius >= canvas.width) {
ball.speed = -ball.speed;
// I reverse the speed, which goes from 3 to -3, so the ball bounces.
}
THE PROBLEM IS :
If I put the ball in the starting position x = 2 and, my canvas is 600 pixels wide.
As the ball moves 3px by 3px and a radius of 10px, the ball will arrive at 589 ... and only at 592 it will bounce. While it should bounce at 590.
I tried a lot of things but nothing seems to correct this problem.
The goal is the ball to bounce on the position 590 (well the canvas.width - ball.radius), regardless of the speed, or the starting position.
The problem maybe lies within my gameloop.
I'm using a simple gameloop like this :
function update {
requestAnimationFrame(update)
Drawball();
Moveball()
Collision();
}
requestAnimationFrame(update);
Is it wrong to do collision like this ??
Thanks for the help i'm stuck with this problem since 2 weeks !
I will provide my code
<style>
* {
padding: 0;
margin: 0;
}
body {
position: relative;
background-color: black;
background-image: radial-gradient(rgba(0, 150, 0, 0.3), black 120%);
height: 100vh;
}
canvas {
background: #000;
display: block;
position: absolute;
top: 20px;
right: 20px;
border: solid #00FA61 1px;
}
#debug {
position: absolute;
padding: 10px;
top: 20px;
left: 20px;
border: solid #00FA61 1px;
color: #00FA61;
font-family: 'Courier', monospace;
font-size: 18px;
text-align: center;
}
#debug span {
font-size: 2em;
font-weight: bold;
}
</style>
</head>
<body>
<div id="debug">
<h3>Debug mode</h3>
<p id="posX"></p>
<p id="posY"></p>
<p id="collision"></p>
</div>
<canvas id="myCanvas" width="800" height="600"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var hauteur_canvas = canvas.height;
var largeur_canvas = canvas.width;
var infoPosX = document.getElementById("posX");
var infoPosY = document.getElementById("posY");
var infoCollide = document.getElementById("collision");
/* BALL POS X/Y */
var x = canvas.width / 2;
var y = canvas.height - 40;
/* BALL SPEED */
var direction_x = 8;
var direction_y = -direction_x;
/* RAYON DE LA BOULE */
var rayon_balle = 10;
var timer = 0;
var id_frame;
var currentSeconde = 0,
frameCount = 0,
frameLastSecond = 0;
var colorBall = "#00FA61";
/* HAUTEUR ET LARGEUR DU PADDLE */
var paddleHeight = 10;
var paddleWidth = 75;
/* POSITION X ET Y DU COIN GAUCHE HAUT */
var paddleX = (largeur_canvas - paddleWidth) / 2;
var paddleY = hauteur_canvas - paddleHeight;
/* DISTANCES ENTRE BOULES ET PADDLE */
var dist_center_X;
var dist_center_Y;
/* DETECTION DES INPUTS */
var rightPressed = false;
var leftPressed = false;
/* GESTION DES BRIQUES */
var brickRowCount = 3;
var brickColumnCount = 5;
var brick = {
hauteur: 50,
largeur: 132,
padding: 20,
offsettop: 30,
offsetleft: 30
};
var bricks = [];
for (var c = 0; c < brickColumnCount; c++) {
bricks[c] = [];
for (var r = 0; r < brickRowCount; r++) {
bricks[c][r] = {
x: 0,
y: 0
};
}
}
/* ------------------- */
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, rayon_balle, 0, Math.PI * 2);
ctx.fillStyle = colorBall;
ctx.fill();
ctx.closePath();
}
function drawPaddle() {
ctx.beginPath();
ctx.rect(paddleX, paddleY, paddleWidth, paddleHeight);
ctx.fillStyle = "#00FA61";
ctx.fill();
ctx.closePath();
}
function drawBricks() {
for (var c = 0; c < brickColumnCount; c++) {
for (var r = 0; r < brickRowCount; r++) {
var brickX = (c * (brick.largeur + brick.padding)) + brick.offsetleft;
var brickY = (r * (brick.hauteur + brick.padding)) + brick.offsettop;
bricks[c][r].x = brickX;
bricks[c][r].y = brickY;
ctx.beginPath();
ctx.rect(brickX, brickY, brick.largeur, brick.hauteur);
ctx.fillStyle = "#1aa829";
ctx.fill();
ctx.closePath();
}
}
}
function distance_boule_paddle() {
/* CALCUL DES DISTANCES ENTRE BOULES ET PADDLE */
dist_center_X = Math.abs(x - paddleX - paddleWidth / 2);
dist_center_Y = Math.abs(y - paddleY - paddleHeight / 2);
}
function fps_count() {
var sec = Math.floor(Date.now() / 1000);
if (sec != currentSeconde) {
currentSeconde = sec;
frameLastSecond = frameCount;
frameCount = 1;
} else {
frameCount++;
}
ctx.fillText("FPS : " + frameLastSecond, 10, 20);
}
function clear() {ctx.clearRect(0, 0, largeur_canvas, hauteur_canvas);}
function collide_paddle() {
if (dist_center_X > (paddleWidth / 2 + rayon_balle)) {
return false;}
if (dist_center_Y > (paddleHeight / 2 + rayon_balle)) {
return false;}
if (dist_center_X <= (paddleWidth / 2)) {
return true;}
if (dist_center_Y <= (paddleHeight / 2)) {
return true;}
var dx = dist_center_X - paddleWidth / 2;
var dy = dist_center_Y - paddleHeight / 2;
return (dx * dx + dy * dy <= (rayon_balle * rayon_balle));
}
function collision() {
/* COLLIDE AVEC LE HAUT DU CANVAS */
if (y - rayon_balle <= 0) {
direction_y = -direction_y;
collideInfo();
} else {
if (y + rayon_balle >= hauteur_canvas - paddleHeight) {
if (collide_paddle()) {
direction_y = -direction_y;
} else {
if (y - rayon_balle > hauteur_canvas) {
// so if the ball is 100% off screen of the down edge its gameover
collideInfo();
alert("GAME OVER");
document.location.reload();
}
}
}
}
/* COLLIDE WITH LEFT AND RIGHT EDGES */
if (x + rayon_balle >= largeur_canvas) {
direction_x = -direction_x;
collideInfo();
} else {
if (x - rayon_balle <= 0) {
direction_x = -direction_x;
collideInfo();
}
}
}
function move_ball() {
x += direction_x;
y += direction_y;
}
function move_paddle() {
if (rightPressed && paddleX < canvas.width - paddleWidth) {
paddleX += 7;
} else if (leftPressed && paddleX > 0) {
paddleX -= 7;
}
}
/* EVENTS LISTENERS */
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;
}
}
function keyUpHandler(e) {
if (e.keyCode == 39) {
rightPressed = false;
} else if (e.keyCode == 37) {
leftPressed = false;
}
}
function collideInfo() {
infoCollide.innerHTML = "<br>La collision s'est produite <br> à la position X <span>: " + x + "</span>" + "<br> la position Y : <span>" + y + "</span>";
}
function gameInfo() {
infoPosX.innerHTML = "La position X de la balle : " + x;
infoPosY.innerHTML = "La position Y de la balle : " + y;
}
function draw() {
id_frame = requestAnimationFrame(draw);
clear();
fps_count();
drawBall();
drawPaddle();
drawBricks();
move_ball();
move_paddle();
distance_boule_paddle();
collision();
gameInfo();
timer++;
if (timer === 2500) {
console.log("STOP !");
cancelAnimationFrame(id_frame);
}
}
requestAnimationFrame(draw);
</script>
</body>
</html>
First of all I don't think you should be doing this
function update {
requestAnimationFrame(update)
Drawball();
Moveball()
Collision();
}
requestAnimationFrame(update);
due to the fact that the requestAnimationFrame(update); is already in the function it self.
try changing it to this
function update {
requestAnimationFrame(update)
Drawball();
Moveball()
Collision();
}
update();

How to make the ball move faster when it hits paddle?

How to make the ball move faster when it hits paddle !
var canvas = document.getElementById("myCanvas");var ctx = canvas.getContext("2d");
var dx = 2;var dy = -2;
var w = canvas.width, h = canvas.height;
var x = w/2;var y = h-30;
var ballRadius = 10;
var color = getColor();
var paddleHeight = 10;var paddleWidth = 75;var paddleX = (w-paddleWidth)/2;
var rightPressed = false;
var leftPressed = 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;
}
}
function keyUpHandler(e) {
if(e.keyCode == 39) {
rightPressed = false;
}
else if(e.keyCode == 37) {
leftPressed = false;
}
}
function getColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI*2);
ctx.fillStyle = color;
ctx.fill();
ctx.closePath();
}
function drawPaddle() {
ctx.beginPath();
ctx.rect(paddleX, h-paddleHeight, paddleWidth, paddleHeight);
ctx.fillStyle = "#eee";
ctx.fill();
ctx.closePath();
}
function draw() {
ctx.clearRect(0,0,w,h);
drawBall();
drawPaddle();
if(x + dx < ballRadius || x + dx > w-ballRadius) {
dx = -dx;
color = getColor();
}
if(y + dy < ballRadius) {
dy = -dy;
color = getColor();
}else if(y + dy > h-ballRadius) {
if(x > paddleX && x < paddleX + paddleWidth) {
dy = -dy;
}
else {
alert("GAME OVER");
}
}
if(rightPressed && paddleX < w-paddleWidth) {
paddleX += 7;
}
else if(leftPressed && paddleX > 0) {
paddleX -= 7;
}
x += dx;
y += dy;
}
setInterval(draw, 10);
/*left arrow: 37
up arrow: 38
right arrow: 39
down arrow: 40*/
* {
background-color: #224;
padding: 0; margin: 0;
}
canvas {
background: #555;
display: block;
margin: 10px auto;
}
<canvas id="myCanvas" width="480px" height="320px"></canvas>
Modify the bounce code in the draw function:
if(y + dy < ballRadius) {
dy = -dy;
color = getColor();
}
else if(y + dy > h-ballRadius) {
if(x > paddleX && x < paddleX + paddleWidth) {
dy = -dy * 1.1;
}
Note the last line:
dy = -dy * 1.1;
This means that dy will be increased by 10% each time the paddle hits the ball. You could change 1.1 to modify the scaling factor.

My HTML game is not running, what's wrong?

I wrote this game from a tutorial i read online, it was working just fine, until i messed it up, my developer tools console says theres a reference error but i just cant see it, please help, the error i get through my we developer console is "Uncaught ReferenceError: Draw is not defined(anonymous function) # games.html:228 "
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Gamedev Canvas Workshop</title>
<style>
* { padding: 0; margin: 0; }
canvas { background: #eee;
display: block;
margin: 0 auto;
}
#checking {
margin-left:650px;
}
#checking1 {
margin-left:650px;
}
#checking2 {
margin-left:650px;
}
#checking3 {
margin-left:650px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="480" height="320"></canvas>
<br/>
<div id ="checking">Current Position</div>
<div id ="checking1">Nothings Moving Bro</div>
<br/>
<div id ="checking3">Color State</div>
<div id ="checking2">Nope, still nothing</div>
<script>
// JavaScript code goes here
var checking1 = document.getElementById("checking1");
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width/2;
var y = canvas.height-30;
var ballRadius = 20;
var dx = 2;
var dy = -2;
var paddleheight = 10;
var paddlewidth = 50;
var paddleX = (canvas.height - paddlewidth)/2;
var RightKeyPressed = false;
var LeftKeyPressed = false;
document.addEventListener("keydown", keyDownHandler,false);
document.addEventListener("keyup",keyUpHandler,false);
function keyDownHandler(e){
if(e.keycode == 39){
RightKeyPressed = true;
}else if(e.keycode == 37){
LeftKeyPressed = true;
}
}
function keyUpHandler(e){
if(e.keycode == 39){
RightKeyPressed = false;
}else if(e.keycode == 37){
LeftKeyPressed = false;
}
function randomInt(min,max){
return Math.floor(Math.random() * (max - min))+ min; }
function paddle(){
ctx.beginPath;
ctx.rect(paddleX,canvas.height - paddleheight,paddlewidth,paddleheight);
ctx.fillStyle="#0095DD";
ctx.fill();
ctx.closePath;
}
function drawball(){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.beginPath();
ctx.arc(x,y,ballRadius,0,Math.PI*2,false);
ctx.fillStyle = "rgb(0,149,221)";
ctx.fill();
ctx.closePath();
}
function Draw(){
ctx.clearRect(0,0,canvas.width,canvas.height);
drawball();
paddle();
if(y + dy > canvas.height - 20 || y + dy < ballRadius){
var cx = randomInt(0,255);
var cy = randomInt(0,255);
var cz = randomInt(0,255);
ctx.fillStyle = "rgb(cx,cy,cz)";
ctx.fill();
dy = -dy;
}
if ( x + dx > canvas.width - 20 || x + dx < ballRadius){
var cx = randomInt(0,255);
var cy = randomInt(0,255);
var cz = randomInt(0,255);
ctx.fillStyle = "rgb(cx,cy,cz)";
ctx.fill();
dx = -dx; }
x += dx;
y += dy
var color = ctx.fillStyle;
checking1.innerHTML = " x: " + x + "y: " + y ;
checking2.innerHTML = color ;
}
}
if(RightKeyPressed && paddleX < canvas.width - 50 ){
paddleX += 7;
}else if(LeftKeyPressed && paddleX > 0){
paddleX -= 7;
}
setInterval(Draw,10);
</script>
</body>
</html>
Your code throws the error because it cannot find the function Draw():
setInterval(Draw, 10);
This is because your function is not in the same scope. Your code structure is like this:
function keyUpHandler(e) {
...
function Draw(){
//Codes here
}
...
}
...
setInterval(Draw, 10);
Since the Draw() function is inside the keyUpHandler(e), it cannot be seen from any outside function (that is functions that are on a higher level/scope).
Hope this clears your mind :)
Check out this fiddle , you closing bracket of function keyDownHandlercode is wrong
var checking1 = document.getElementById("checking1");
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width / 2;
var y = canvas.height - 30;
var ballRadius = 20;
var dx = 2;
var dy = -2;
var paddleheight = 10;
var paddlewidth = 50;
var paddleX = (canvas.height - paddlewidth) / 2;
var RightKeyPressed = false;
var LeftKeyPressed = false;
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if (e.keycode == 39) {
RightKeyPressed = true;
} else if (e.keycode == 37) {
LeftKeyPressed = true;
}
}
function keyUpHandler(e) {
if (e.keycode == 39) {
RightKeyPressed = false;
} else if (e.keycode == 37) {
LeftKeyPressed = false;
}
}
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function paddle() {
ctx.beginPath;
ctx.rect(paddleX, canvas.height - paddleheight, paddlewidth, paddleheight);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath;
}
function drawball() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI * 2, false);
ctx.fillStyle = "rgb(0,149,221)";
ctx.fill();
ctx.closePath();
}
function zan(){
alert('test');
}
function Draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawball();
paddle();
if (y + dy > canvas.height - 20 || y + dy < ballRadius) {
var cx = randomInt(0, 255);
var cy = randomInt(0, 255);
var cz = randomInt(0, 255);
ctx.fillStyle = "rgb(cx,cy,cz)";
ctx.fill();
dy = -dy;
}
if (x + dx > canvas.width - 20 || x + dx < ballRadius) {
var cx = randomInt(0, 255);
var cy = randomInt(0, 255);
var cz = randomInt(0, 255);
ctx.fillStyle = "rgb(cx,cy,cz)";
ctx.fill();
dx = -dx;
}
x += dx;
y += dy
var color = ctx.fillStyle;
checking1.innerHTML = " x: " + x + "y: " + y;
checking2.innerHTML = color;
}
if (RightKeyPressed && paddleX < canvas.width - 50) {
paddleX += 7;
} else if (LeftKeyPressed && paddleX > 0) {
paddleX -= 7;
}
setInterval(Draw, 10);
You probably forgot to close your keyuphandler function (currently you have like 3 function inside it until you finally close it at line 193).
add a function closure at about line 88 to close your keyuphandler.
Than you have a extra function closure at line 193 remove that and it works
(by function closure i mean brackets {} )

Categories

Resources