increment then decrement radius of arc canvas html5 - javascript

hi i am trying to gat an arc to resize as it moves across the screen.
I cant seem to asign the value of increment to the radius of the arc for it to get bigger and then smaller.
please see below for the code block in question and then the entire code.
resize(){
this.up = true;
this.r = 0;
this.increment = 10;
this.ceiling = 100;
function PerformCalc() {
if (this.up == true && this.r <= this.ceiling) {
this.r += increment
if (this.r == ceiling) {
this.up = false;
}
} else {
this.up = false
this.r -= increment;
if (this.r == 0) {
this.up = true;
}
}
console.log(this.r);
}
setInterval(PerformCalc, 1000);
}
When i log out the radius to the console it gives nan for some reason.
Any help would be greatly appreciated.
<!DOCTYPE html>
<html>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<head>
<meta charset="UTF-8">
<title>Canvas</title>
<style type="text/css">
canvas {
border: 1px solid grey;
}
</style>
</head>
<body>
<canvas id="canvas-for-ball"></canvas>
<script type="text/javascript">
// Gets a handle to the element with id canvasOne.
var canvas = document.getElementById("canvas-for-ball");
// Get a 2D context for the canvas.
var ctx = canvas.getContext("2d");
function init(){
canvas.width = 500;
canvas.height = 500;
}
init();
//angle defining spin and sections of ball
var theta = 0;
//for the sections of the ball
var theta2 = 0;
//fort he amount of sections needed
var seventh = (Math.PI*2)/7
//to control the amount of spin the ball has
var thetaInc = 0.0029;
//ball object
class Ball {
constructor(x,y,r,xvel,yvel,mass){
this.x =x;
this.y = y;
this.r =r;
this.xvel = xvel;
this.yvel = yvel;
this.mass = mass;
}
draw(){
// Update the y location.
this.x = this.x + this.xvel;
this.y = this.y + this.yvel;
//draw circle
ctx.beginPath();
ctx.arc(this.x,this.y,this.r,0,Math.PI*2,false);
ctx.stroke();
//fill the circle
ctx.fillStyle = "orange";
ctx.fill();
//draw inner circle of ball
ctx.beginPath();
ctx.arc(this.x,this.y,this.r*.9,0,Math.PI*2,false);
ctx.stroke();
//spin control
theta += thetaInc;
//loop for adding sections to pie
for( var n = 0; n < 7; ++n) { // add loop to draw radii
theta2 = theta + n * seventh;
ctx.moveTo( this.x, this.y);
ctx.lineTo( this.x + this.r*Math.cos(theta2), this.y + this.r*Math.sin(theta2));
}
ctx.lineWidth = "2";
ctx.lineCap = "round";
ctx.strokeStyle = "black";
ctx.stroke();
}
move(){
//condition take into account the this.r of the ball so
//it bounces at the edge of the canvas instead
//of going off of the screen to its center point.
if(this.y > canvas.height - this.r || this.y - this.r <0){
this.yvel = -1*this.yvel;
//to reverse the direction of the ball when hitting walls
if((this.xvel<0 && this.yvel >0) && thetaInc <0){
thetaInc = -1*thetaInc;
}
else if((this.xvel <0 && this.yvel>0) && thetaInc >0){
thetaInc = -1*thetaInc
}
else if((this.xvel >0 && this.yvel >0) && thetaInc >0){
thetaInc = -1 * thetaInc;
}
else if((this.xvel > 0 && this.yvel < 0)&& thetaInc <0){
thetaInc = -1 * thetaInc;
}
}
if(this.x > canvas.width - this.r || this.x - this.r < 0){
this.xvel = -1*this.xvel;
}
}
resize(){
this.up = true;
this.r = 0;
this.increment = 10;
this.ceiling = 100;
function PerformCalc() {
if (this.up == true && this.r <= this.ceiling) {
this.r += increment
if (this.r == ceiling) {
this.up = false;
}
} else {
this.up = false
this.r -= increment;
if (this.r == 0) {
this.up = true;
}
}
console.log(this.r);
}
setInterval(PerformCalc, 1000);
}
colour(){
}
}
//Intersect function takes a ball as a perameter
//ball will be the the object used to test if the two are touching.
function intersect(ball,ball1) {
//the x and y cordinates of the first ball are subtracted from the test ball and stored
//in productX and productY
var productX = ball1.x - ball.x;
var productY = ball1.y - ball.y;
//pythagoras theorem is used to get the distance between both center points of each circle.
var distance = Math.sqrt(productX * productX + productY * productY);
//A condition is used to check if the distance between both bencer point of each circle
//is less than or equal to the sum of both radii the circles are touching.
//the result is p[rinted out to the console
if (distance <= (ball1.r + ball.r)) {
dx = ball.x-ball1.x;
dy = ball.y-ball1.y;
collision_angle = Math.atan2(dy,dx);
magnitude_1 = Math.sqrt(ball.xvel*ball.xvel+ball.yvel*ball.yvel);
magnitude_2 = Math.sqrt(ball1.xvel*ball1.xvel+ball1.yvel*ball1.yvel);
direction_1 = Math.atan2(ball.yvel, ball.xvel);
direction_2 = Math.atan2(ball1.yvel, ball1.xvel);
new_xvel_1 = magnitude_1 * Math.cos(direction_1-collision_angle);
new_yvel_1 = magnitude_1 * Math.sin(direction_1-collision_angle);
new_xvel_2 = magnitude_2 * Math.cos(direction_2-collision_angle);
new_yvel_2 = magnitude_1 * Math.sin(direction_2-collision_angle);
final_xvel_1 = ((ball.mass-ball1.mass)*new_xvel_1+(ball1.mass+ball1.mass)*new_xvel_2)/(ball.mass+ball1.mass);
final_xvel_2 = ((ball.mass+ball.mass)*new_xvel_1+(ball1.mass-ball.mass)*new_xvel_2)/(ball.mass+ball1.mass);
final_yvel_1 = new_yvel_1;
final_yvel_2 = new_yvel_2;
ball.xvel = Math.cos(collision_angle)*final_xvel_1+Math.cos(collision_angle+Math.PI/2)*final_yvel_1;
ball.yvel = Math.sin(collision_angle)*final_xvel_1+Math.sin(collision_angle+Math.PI/2)*final_yvel_1;
ball1.xvel = Math.cos(collision_angle)*final_xvel_2+Math.cos(collision_angle+Math.PI/2)*final_yvel_2;
ball1.yvel = Math.sin(collision_angle)*final_xvel_2+Math.sin(collision_angle+Math.PI/2)*final_yvel_2;
}
}
canvas.addEventListener("click", function(event) {
var clickX = event.clientX - canvas.offsetLeft;
var clickY = event.clientY- canvas.offsetTop;
b1.x = clickX;
b1.y = clickY;
});
// Add a Javascript event listener to the keypress event.
window.addEventListener("keypress", function(event) {
// Just log the event to the console.
console.log(event);
});
//keypresses with jQuery
$(document.body).on('keydown', function(e) {
console.log(e.which);
switch (e.which) {
// key code for left arrow
case 37:
console.log('left arrow key pressed!');
b1.xvel --;
break;
//keycode for up
case 38:
console.log('up key pressed');
b1.yvel++;
break;
//key code for right
case 39:
console.log('right arrow key pressed!');
b1.xvel++;
break;
//key code for down
case 40:
console.log('down arrow key pressed!');
b1.yvel--;
break;
//key code for + key to increase spin
case 107:
console.log('down arrow key pressed!');
thetaInc +=.001;
break;
//key code for - key to decrease spin
case 109:
console.log('down arrow key pressed!');
thetaInc -=.001;
break;
}
});
b1 = new Ball(200,200,40,1,1,50);
b2 = new Ball(100,100,40,2,2,5);
b1.resize();
// A function to repeat every time the animation loops.
function repeatme() {
//clear canvas for each frame of the animation.
ctx.clearRect(0,0,500,500);
// Draw the ball (stroked, not filled).
b1.draw();
b2.draw();
b1.move();
b2.move();
intersect(b1,b2);
//put repeatme function into the animation frame and store it in animate
animate = window.requestAnimationFrame(repeatme);
}
// Get the animation going.
repeatme();
</script>
</body>
</html>

There is a reference error for increment, e.g. you didn't use this.increment, same for ceiling, should be this.ceiling.
this is used by the setInterval so you save this as that so you can use them. this removes the NaN.
<!DOCTYPE html>
<html>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<head>
<meta charset="UTF-8">
<title>Canvas</title>
<style type="text/css">
canvas {
border: 1px solid grey;
}
</style>
</head>
<body>
<canvas id="canvas-for-ball"></canvas>
<script type="text/javascript">
// Gets a handle to the element with id canvasOne.
var canvas = document.getElementById("canvas-for-ball");
// Get a 2D context for the canvas.
var ctx = canvas.getContext("2d");
function init(){
canvas.width = 500;
canvas.height = 500;
}
init();
//angle defining spin and sections of ball
var theta = 0;
//for the sections of the ball
var theta2 = 0;
//fort he amount of sections needed
var seventh = (Math.PI*2)/7
//to control the amount of spin the ball has
var thetaInc = 0.0029;
//ball object
class Ball {
constructor(x,y,r,xvel,yvel,mass){
this.x =x;
this.y = y;
this.r =r;
this.xvel = xvel;
this.yvel = yvel;
this.mass = mass;
}
draw(){
// Update the y location.
this.x = this.x + this.xvel;
this.y = this.y + this.yvel;
//draw circle
ctx.beginPath();
ctx.arc(this.x,this.y,this.r,0,Math.PI*2,false);
ctx.stroke();
//fill the circle
ctx.fillStyle = "orange";
ctx.fill();
//draw inner circle of ball
ctx.beginPath();
ctx.arc(this.x,this.y,this.r*.9,0,Math.PI*2,false);
ctx.stroke();
//spin control
theta += thetaInc;
//loop for adding sections to pie
for( var n = 0; n < 7; ++n) { // add loop to draw radii
theta2 = theta + n * seventh;
ctx.moveTo( this.x, this.y);
ctx.lineTo( this.x + this.r*Math.cos(theta2), this.y + this.r*Math.sin(theta2));
}
ctx.lineWidth = "2";
ctx.lineCap = "round";
ctx.strokeStyle = "black";
ctx.stroke();
}
move(){
//condition take into account the this.r of the ball so
//it bounces at the edge of the canvas instead
//of going off of the screen to its center point.
if(this.y > canvas.height - this.r || this.y - this.r <0){
this.yvel = -1*this.yvel;
//to reverse the direction of the ball when hitting walls
if((this.xvel<0 && this.yvel >0) && thetaInc <0){
thetaInc = -1*thetaInc;
}
else if((this.xvel <0 && this.yvel>0) && thetaInc >0){
thetaInc = -1*thetaInc
}
else if((this.xvel >0 && this.yvel >0) && thetaInc >0){
thetaInc = -1 * thetaInc;
}
else if((this.xvel > 0 && this.yvel < 0)&& thetaInc <0){
thetaInc = -1 * thetaInc;
}
}
if(this.x > canvas.width - this.r || this.x - this.r < 0){
this.xvel = -1*this.xvel;
}
}
resize(){
var that = this;
that.up = true;
that.r = 0;
that.increment = 10;
that.ceiling = 100;
function PerformCalc() {
if (that.up == true && that.r <= that.ceiling) {
that.r += that.increment
if (that.r == that.ceiling) {
that.up = false;
}
} else {
that.up = false
that.r -= that.increment;
if (that.r == 0) {
that.up = true;
}
}
console.log(that.r);
}
setInterval(PerformCalc, 1000);
}
colour(){
}
}
//Intersect function takes a ball as a perameter
//ball will be the the object used to test if the two are touching.
function intersect(ball,ball1) {
//the x and y cordinates of the first ball are subtracted from the test ball and stored
//in productX and productY
var productX = ball1.x - ball.x;
var productY = ball1.y - ball.y;
//pythagoras theorem is used to get the distance between both center points of each circle.
var distance = Math.sqrt(productX * productX + productY * productY);
//A condition is used to check if the distance between both bencer point of each circle
//is less than or equal to the sum of both radii the circles are touching.
//the result is p[rinted out to the console
if (distance <= (ball1.r + ball.r)) {
dx = ball.x-ball1.x;
dy = ball.y-ball1.y;
collision_angle = Math.atan2(dy,dx);
magnitude_1 = Math.sqrt(ball.xvel*ball.xvel+ball.yvel*ball.yvel);
magnitude_2 = Math.sqrt(ball1.xvel*ball1.xvel+ball1.yvel*ball1.yvel);
direction_1 = Math.atan2(ball.yvel, ball.xvel);
direction_2 = Math.atan2(ball1.yvel, ball1.xvel);
new_xvel_1 = magnitude_1 * Math.cos(direction_1-collision_angle);
new_yvel_1 = magnitude_1 * Math.sin(direction_1-collision_angle);
new_xvel_2 = magnitude_2 * Math.cos(direction_2-collision_angle);
new_yvel_2 = magnitude_1 * Math.sin(direction_2-collision_angle);
final_xvel_1 = ((ball.mass-ball1.mass)*new_xvel_1+(ball1.mass+ball1.mass)*new_xvel_2)/(ball.mass+ball1.mass);
final_xvel_2 = ((ball.mass+ball.mass)*new_xvel_1+(ball1.mass-ball.mass)*new_xvel_2)/(ball.mass+ball1.mass);
final_yvel_1 = new_yvel_1;
final_yvel_2 = new_yvel_2;
ball.xvel = Math.cos(collision_angle)*final_xvel_1+Math.cos(collision_angle+Math.PI/2)*final_yvel_1;
ball.yvel = Math.sin(collision_angle)*final_xvel_1+Math.sin(collision_angle+Math.PI/2)*final_yvel_1;
ball1.xvel = Math.cos(collision_angle)*final_xvel_2+Math.cos(collision_angle+Math.PI/2)*final_yvel_2;
ball1.yvel = Math.sin(collision_angle)*final_xvel_2+Math.sin(collision_angle+Math.PI/2)*final_yvel_2;
}
}
canvas.addEventListener("click", function(event) {
var clickX = event.clientX - canvas.offsetLeft;
var clickY = event.clientY- canvas.offsetTop;
b1.x = clickX;
b1.y = clickY;
});
// Add a Javascript event listener to the keypress event.
window.addEventListener("keypress", function(event) {
// Just log the event to the console.
console.log(event);
});
//keypresses with jQuery
$(document.body).on('keydown', function(e) {
console.log(e.which);
switch (e.which) {
// key code for left arrow
case 37:
console.log('left arrow key pressed!');
b1.xvel --;
break;
//keycode for up
case 38:
console.log('up key pressed');
b1.yvel++;
break;
//key code for right
case 39:
console.log('right arrow key pressed!');
b1.xvel++;
break;
//key code for down
case 40:
console.log('down arrow key pressed!');
b1.yvel--;
break;
//key code for + key to increase spin
case 107:
console.log('down arrow key pressed!');
thetaInc +=.001;
break;
//key code for - key to decrease spin
case 109:
console.log('down arrow key pressed!');
thetaInc -=.001;
break;
}
});
b1 = new Ball(200,200,40,1,1,50);
b2 = new Ball(100,100,40,2,2,5);
b1.resize();
// A function to repeat every time the animation loops.
function repeatme() {
//clear canvas for each frame of the animation.
ctx.clearRect(0,0,500,500);
// Draw the ball (stroked, not filled).
b1.draw();
b2.draw();
b1.move();
b2.move();
intersect(b1,b2);
//put repeatme function into the animation frame and store it in animate
animate = window.requestAnimationFrame(repeatme);
}
// Get the animation going.
repeatme();
</script>
</body>
</html>

Related

Uncaught TypeError: Cannot read property 'show' of undefined

I'm making a simple brick breaker game using Java Script, and my console is showing me error while displaying blocks on to the canvas, they are being drawn onto the canvas but all the other objects are not working and console is showing
index.js:173 Uncaught TypeError: Cannot read property 'show' of undefined
at update (index.js:173)
at index.js:177
if you comment out from line no:172 and 173, which is a for loop that tells the canvas to draw them on it
everything's is working fine.
one more thing: that canvasRendering...rundedRectangle is a function that draws rounded edge rectangles
someone please find a solution!
CanvasRenderingContext2D.prototype.roundedRectangle = function(x, y, width, height, rounded) {
const radiansInCircle = 2 * Math.PI
const halfRadians = (2 * Math.PI)/2
const quarterRadians = (2 * Math.PI)/4
// top left arc
this.arc(rounded + x, rounded + y, rounded, -quarterRadians, halfRadians, true)
// line from top left to bottom left
this.lineTo(x, y + height - rounded)
// bottom left arc
this.arc(rounded + x, height - rounded + y, rounded, halfRadians, quarterRadians, true)
// line from bottom left to bottom right
this.lineTo(x + width - rounded, y + height)
// bottom right arc
this.arc(x + width - rounded, y + height - rounded, rounded, quarterRadians, 0, true)
// line from bottom right to top right
this.lineTo(x + width, y + rounded)
// top right arc
this.arc(x + width - rounded, y + rounded, rounded, 0, -quarterRadians, true)
// line from top right to top left
this.lineTo(x + rounded, y)
}
var canvas= document.getElementById("gameCanvas");
var ctx = canvas.getContext("2d");
function Player(x,y,w,h){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.show = function(){
ctx.beginPath();
ctx.rect(this.x, this.y, this.w, this.h);
ctx.fillStyle = "#ffff";
ctx.fill();
ctx.closePath();
}
this.move = function(speed){
this.x += speed;
}
}
function Ball(x,y,r){
this.x = x;
this.y = y;
this.r = r;
this.show = function(){
ctx.beginPath();
ctx.arc(this.x,this.y,this.r,0,2* Math.PI);
ctx.fillStyle = "tomato";
ctx.fill();
ctx.closePath();
}
this.move= function(speedX,speedY){
this.show();
this.speed = 2;
this.x += speedX;
this.y += speedY;
}
}
function Block(x,y,w,h){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.show= function(color){
ctx.beginPath();
ctx.roundedRectangle(this.x,this.y,this.w,this.h,7);
ctx.fillStyle = color;
ctx.fill();
ctx.closePath();
};
};
var player = new Player(canvas.width/2-50,canvas.height*0.95,100,20);
var ball = new Ball(canvas.width/2-5, player.y-20,15);
var rigthPressed = false;
var leftPressed = false;
var blocks = [];
var rowCount = 5;
var columnCount = 6;
var noInRow = 6;
var blockCount = (rowCount*columnCount)+1;
var blockRow = 0;
var blockCol = 0;
var ballSpeedX = 5;
var ballSpeedY = -10;
for(let i = 1; i < blockCount; i++){
blocks.push(new Block(blockCol*60+25,blockRow*60+30,50,50));
blockCol++;
if(i % noInRow == 0){
blockRow++;
blockCol = 0;
}
}
window.addEventListener("keydown", function(e){
if(e.keyCode == 39){
rigthPressed = true;
}
if(e.keyCode == 37){
leftPressed = true;
}
});
window.addEventListener("keyup", function(e){
if(e.keyCode == 39){
rigthPressed = false;
}
if(e.keyCode == 37){
leftPressed = false;
}
});
function objMovement(){
if(rigthPressed){
player.move(5);
if (player.x > canvas.width-player.w){
player.x = canvas.width-player.w;
}
}
if(leftPressed){
player.move(-5);
if(player.x < 0){
player.x = 0;
}
}
if(ball.x > canvas.width-ball.r || ball.x < 0+ball.r){
ballSpeedX = -ballSpeedX;
}
if (ball.y > canvas.height-ball.r || ball.y < 0+ball.r){
ballSpeedY = -ballSpeedY;
}
if(ball.x<player.x+player.w &&ball.x>player.x && ball.y>player.y){
ballSpeedY = -ballSpeedY;
ballSpeedX= ballSpeedX;
}
function Bump(){
if (ball.x>player.x && ball.x<player.x+player.w/2){
if (ball.y >= player.y){
ballSpeedX = -5;
}
}
if(ball.x>player.x+player.w/2 && ball.x<player.x+player.w){
if(ball.y >= player.y){
ballSpeedX = 5;
}
}
}
//Bump();
}
function update(){
ctx.clearRect(0,0,canvas.width,canvas.height);
ball.show();
ball.move(ballSpeedX,ballSpeedY);
player.show();
objMovement();
for(let i=0;i<blockCount;i++){
blocks[i].show("violet");
}
window.requestAnimationFrame(update);
}
update();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>🌝🩲🩲🌝</title>
<style>
#body{
background-color: rgb(31, 30, 30);
}
#gameCanvas{
border: 15px solid rgb(44, 44, 44);
border-radius: 20px;
background-color:rgb(19, 18, 18);
margin: 250px;
}
</style>
</head>
<body id="body">
<canvas id="gameCanvas" width=400 height=800></canvas>
<script type="text/javascript" src="./index.js"></script>
</body>
</html>
When you create blocks you start from 1
for (let i = 1; i < blockCount; i++) {
blocks.push(new Block(blockCol * 60 + 25, blockRow * 60 + 30, 50, 50));
...
so when you update you need to consider that
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ball.show();
ball.move(ballSpeedX, ballSpeedY);
player.show();
objMovement();
for (let i = 0; i < blockCount -1; i++) { // or for (let i = 0; i < blocks.length; i++) {
blocks[i].show("violet");
}
window.requestAnimationFrame(update);
}

How to rotate/transform image using arrow keys

I'm relatively new to canvas and I'm trying to make a space ship type game. I have everything else I'd like down, except for the ship turning itself. I want to make the image of the ship rotate when the arrow keys are clicked.
So if the left arrow key is clicked, it will turn to face the left, and the right arrow key is clicked it will turn to face the right, and so on. I really can't figure this out, if anyone can show me how to do this I would really appreciate it.
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
/*Variable to store score*/
var score = 0;
/*Variable that stores the players object properties*/
var x = 50;
var y = 100;
var speed = 6;
var sideLength = 50;
/*Flags to track when keypress is active*/
var down = false;
var up = false;
var left = false;
var right = false;
/*Variables that store target position and size*/
var targetX = 0;
var targetY = 0;
var targetLength = 25;
/*If a number is within range b to c*/
function isWithin(a, b, c) {
return (a > b && a < c)
}
var countDown = 30;
/*Id to track set time*/
var id = null;
/*Listening for if one of the keys is pressed*/
canvas.addEventListener('keydown', function (event) {
event.preventDefault();
console.log(event.key, event.keyCode);
if (event.keyCode === 40) {
down = true;
}
if (event.keyCode === 38) {
up = true;
}
if (event.keyCode === 37) {
left = true;
}
if (event.keyCode === 39) {
right = true;
}
});
/*Listening for if one of the keys is released*/
canvas.addEventListener('keyup', function (event) {
event.preventDefault();
console.log(event.key, event.keyCode);
if (event.keyCode === 40) {
down = false;
}
if (event.keyCode === 38) {
up = false;
}
if (event.keyCode === 37) {
left = false;
}
if (event.keyCode === 39) {
right = false;
}
});
/*Function to show menu*/
function menu() {
erase();
context.fillStyle = '#000000';
context.font = '36px Arial';
context.textAlign = 'center';
context.fillText('Collect The Thing', canvas.width / 2, canvas.height / 4);
context.font = '30px Arial';
context.fillText('Press to Start', canvas.width / 2, canvas.height / 2);
/*Listen for click to start game*/
canvas.addEventListener('click', startGame);
}
/*Function to start the game*/
function startGame() {
/*reduce the countdown timer every 1 second*/
id = setInterval(function () {
countDown--;
}, 1000)
/*remove click events*/
canvas.removeEventListener('click', startGame);
moveTarget();
draw();
}
/*Show game over screen*/
function endGame() {
/*stop the countdown*/
clearInterval(id);
/*clear game board*/
erase();
context.fillStyle = '#000000';
context.font = '36px Arial';
context.textAlign = 'center';
context.fillText('Finale Score: ' + score, canvas.width / 2, canvas.height / 4);
}
/*Move target to random location in canvas*/
function moveTarget() {
targetX = Math.round(Math.random() * canvas.width - targetLength);
targetY = Math.round(Math.random() * canvas.height - targetLength);
}
/*Clear the Canvas*/
function erase() {
context.fillStyle = '#FFFFFF';
context.fillRect(0, 0, 600, 500);
}
/*Main animation drawing loop with game logic*/
function draw() {
erase();
/*Move the player sqaure*/
if (down) {
y += speed;
}
if (up) {
y -= speed;
}
if (right) {
x += speed;
}
if (left) {
x -= speed;
}
if (y + sideLength > canvas.height) {
y = canvas.height - sideLength;
}
if (y < 0) {
y = 0;
}
if (x < 0) {
x = 0;
}
if (x + sideLength > canvas.width) {
x = canvas.width - sideLength;
}
/*Collide with target*/
if (isWithin(targetX, x, x + sideLength) || isWithin(targetX + targetLength, x, x + sideLength)) {
if (isWithin(targetY, y, y + sideLength) || isWithin(targetY + targetLength, y, y + sideLength)) {
/*respawn target in a random location*/
moveTarget();
/*Increase score by 1*/
score++;
}
}
//Draw player object
context.fillRect(x, y, sideLength, sideLength);
context.drawImage(baseImage, x, y, sideLength, sideLength);
/*Draw target sqaure*/
context.fillStyle = '#00FF00';
context.fillRect(targetX, targetY, targetLength, targetLength);
//Timer and Score
context.fillStyle = '#000000';
context.font = '24px Arial';
context.textAlign = 'left';
context.fillText('Score: ' + score, 10, 24);
context.fillText('Time Remaining: ' + countDown, 10, 50);
if (countDown <= 0) {
endGame();
} else {
window.requestAnimationFrame(draw);
}
}
baseImage= new Image();
baseImage.src='xwing3.png';
baseImage.onload= function() {
menu();
}
canvas.focus();
I think in this regard you have two options.
You could have a sprite for every direction that you want the ship to face, then when you draw the image, you could choose the sprite that matches.
if(left == true) {baseImage.src='xwing3left.png';}
You could use the canvas rotate() method. This would make things more complicated, but it actually rotates the canvas and could give more opportunity to experiment.
It actually applies a transformation matrix to the canvas before it draws so you could do things like:
context.rotate(45);
context.fillRect(x,y,width,height);
Just be careful, because rotate always occurs around the origin, so you might need to use translate() as well to make it work the way you expect.
Hope this helps! :)

Variable does not go into local storage and does not appear on other page. (JavaScript/HTML)

I am trying to create a scoreboard for my game by using local storage to carry over the score variable after a game is finished by a user. However, this is not working for some reason. I am relatively new to coding so I did some research on local storage but couldn't get the code to work to no avail. Could someone help me with this code thanks.
Page 1:
<html>
<title>Level Selector</title>
<canvas id="myCanvas" width="750" height="400"></canvas>
<style type="text/css">
canvas { background: #eee; }
</style>
<script>
document.addEventListener('load', draw);
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();
}
/*************************************************************/
// NEW
const ballPowerupHalfWidth = 30;
const paddlePowerupHalfWidth = 30;
let ballPowerups = [];
let paddlePowerups = [];
// This function adds powerup to random position
function addPowerups() {
// I check only if none exist, you could
// add more than 1 powerup if you want
if (ballPowerups.length < 1) {
// otherwise half the triangle could be outside canvas
const padding = 50;
const xMin = 0 + padding;
const xMax = canvas.width - padding;
const yMin = 0 + padding;
const yMax = canvas.height - padding;
ballPowerups.push({
x: Math.floor(Math.random()*(xMax-xMin+1)+xMin),
y: Math.floor(Math.random()*(yMax-yMin+1)+yMin),
});
}
// I check only if none exist, you could
// add more than 1 powerup if you want
if (paddlePowerups.length < 1) {
// otherwise half the triangle could be outside canvas
const padding = 50;
const xMin = 0 + padding;
const xMax = canvas.width - padding;
const yMin = 0 + padding;
const yMax = canvas.height - padding;
paddlePowerups.push({
x: Math.floor(Math.random()*(xMax-xMin+1)+xMin),
y: Math.floor(Math.random()*(yMax-yMin+1)+yMin),
});
}
}
// NEW: do all collision detections
function doCollisionDetection() {
// ball powerups
ballPowerups.forEach((powerup, i) => {
rectangleCollisionDetection(
{x: powerup.x, y: powerup.y},
{w: ballPowerupHalfWidth, h: ballPowerupHalfWidth},
() => {
console.log('BALL POWERUP COLLISION');
// remove powerup
ballPowerups.splice(i, 1);
dy = dy/2
setTimeout(() => { dy=2 }, 5000)
// to make effect last 10 seconds:
// 1. add effect
// 2. and setTimeout(() => { /* code that removes effect */ }, 10000);
});
});
// paddle powerups
paddlePowerups.forEach((powerup, i) => {
rectangleCollisionDetection(
{x: powerup.x, y: powerup.y},
{w: ballPowerupHalfWidth, h: ballPowerupHalfWidth},
() => {
console.log('PADDLE POWERUP COLLISION');
// remove powerup
paddlePowerups.splice(i, 1);
paddleHeight = paddleHeight*1.5
paddleWidth = paddleWidth*1.5
setTimeout(() => { paddleHeight=10; }, 10000)
});
});
// bricks
for(var c=0; c<brickColumnCount; c++) {
for(var r=0; r<brickRowCount; r++) {
var b = bricks[c][r];
if(b.status == 1) {
rectangleCollisionDetection(b, {w: brickWidth, h: brickHeight}, () => {
console.log('BRICK COLLISION');
dy = -dy;
b.status = 0;
score++;
if(score == brickRowCount*brickColumnCount) {
alert("YOU WIN, CONGRATULATIONS!");
window.location = "Intro Screen.html";
}
});
}
}
}
// NEW: collision detection between ball and rectangle shaped
// collision boundary (only need center(x, y) and half width)
function rectangleCollisionDetection(center, size, callback) {
if(
x > center.x &&
x < center.x+size.w &&
y > center.y &&
y < center.y+size.h
) {
callback && callback();
}
}
function drawBallpowerup() {
ballPowerups.forEach(powerup => {
ctx.beginPath();
ctx.moveTo(powerup.x, powerup.y);
ctx.lineTo(powerup.x+ballPowerupHalfWidth, powerup.y+ballPowerupHalfWidth);
ctx.lineTo(powerup.x+ballPowerupHalfWidth*2, powerup.y);
ctx.fillStyle = "#42f445";
ctx.fill();
ctx.closePath();
});
}
function drawPaddlepowerup() {
paddlePowerups.forEach(powerup => {
ctx.beginPath();
ctx.moveTo(powerup.x, powerup.y);
ctx.lineTo(powerup.x+paddlePowerupHalfWidth, powerup.y+paddlePowerupHalfWidth);
ctx.lineTo(powerup.x+paddlePowerupHalfWidth*2, powerup.y);
ctx.fillStyle = "#ce6210";
ctx.fill();
ctx.closePath();
});
}
// my big changes end here
/*************************************************************/
//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() {
// clears canvas content from previous frame
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();//this code draws the ball onto the canvas
drawPaddle();//this code draws the paddle onto the canvas
drawBricks();//this code draws the bricks onto the canvas
addPowerups();
doCollisionDetection();
drawScore();//this code draws the score variable onto the canvas
drawLives();//this code draws the lives variable onto the canvas
drawBallpowerup();
drawPaddlepowerup();
//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");
localStorage.setItem("score", score);
}
window.location = "Intro Screen.html";
}
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 onload="draw();>
</body>
</html>
Page 2:
if (typeof(Storage) !== "undefined") {
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("score"));
}
When I run it and after playing the game, the score should be added onto the scoreboard in decending order (highest to lowest). I have trouble bringing over the variable.
While there are no standard specifications about it, most browsers will consider different pages served from the file:// protocol as being different-origin.
This means your two pages will be considered as different-origin and will thus have their own Storage Area that they won't be able to share, just like you won't be able to access the Storage Area from www.xxxxx.com from www.yyyyy.com.
To overcome this limitation, the easiest is to run a local web-server on your machine. Many OSes comes with preinstalled such server, and all it requires is to activate it, and for the ones that don't do it, there are many free and easy solutions.
And if you are planning to play with web standards, it's a must have anyway.

I'm trying to get a blue square to move around in the canvas by using arrow keys?

const WIDTH = 640;
const HEIGHT = 480;
const PLAYER_SIZE = 20;
const REPAINT_DELAY = 50;
const EASY_DELAY = 1750;
const MODERATE_DELAY = 1000;
const HARD_DELAY = 750;
const MAX_BLOCKS = 100;
var context;
var DX;
var DY;
DX and DY are the position of the blue square. What I'm trying to accomplish is that when using the arrow keys I am moving the Position of the blue square.
var rightKey = false;
var leftKey = false;
var upKey = false;
var downKey = false;
window.onload = init;
function init()
{
canvas = document.getElementById("myCanvas");
context = canvas.getContext("2d");
context.fillStyle = "#0000FF";
DX = WIDTH / 2 - PLAYER_SIZE / 2;
DY = HEIGHT / 2 - PLAYER_SIZE / 2;
setInterval('draw()', 25)
}
function clearCanvas()
{
context.clearRect(0,0,WIDTH,HEIGHT);
}
function draw()
{
clearCanvas();
if (rightKey) DX += 5;
else if (leftKey) DX -= 5;
if (upKey) DY -= 5;
else if (downKey) DY += 5;
if (DX <= 0) DX = 0;
if ((DX + DY) >= WIDTH) DX = WIDTH - DY;
if (DY <= 0) DY = 0;
if ((DY + DX) >= HEIGHT) DY = HEIGHT - DX;
context.fillRect(DX, DY, PLAYER_SIZE, PLAYER_SIZE);
}
function onKeyDown(evt) {
if (evt.keyCode == 39) rightKey = true;
else if (evt.keyCode == 37) leftKey = true;
if (evt.keyCode == 38) upKey = true;
else if (evt.keyCode == 40) downKey = true;
}
function onKeyUp(evt) {
if (evt.keyCode == 39) rightKey = false;
else if (evt.keyCode == 37) leftKey = false;
if (evt.keyCode == 38) upKey = false;
else if (evt.keyCode == 40) downKey = false;
}
I think here at the end I'm missing two lines of code that sort of call the two previous functions? That's where I'm getting confused.
This is what I have so far it isn't working for me at the moment. Any help would be appreciated!
The error in your code is this:
setInterval('draw()', 25)
when it should be
setInterval(draw, 25)
setInterval's first argument should be function, now it's a string.
Here's my simple
Updated demo with class based moving objects:
https://jsfiddle.net/mulperi/oh7n3Lx9/
Also, see here why requestAnimationFrame() is better than setTimeout() or setInterval():
Why is requestAnimationFrame better than setInterval or setTimeout
For keypresses I suggest you make an object that holds boolean values for all keys and then, on the update-functions of different objects like player for example, you just check if the keys it needs are being pressed.
And you don't need to use keyCode anymore, see here:
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key
I hope that helps you!
Here is the full code of my take on moving the player objects around the canvas. It may help you to think about the structure of your code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>World's BEstest Game</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1 style="font-family: Comic Sans MS; color: hotpink; text-shadow: 2px 2px 2px pink">2 Player Movement</h1>
<p>Class based player objects and keyboard controls</p>
<p>Use the arrow and WASD keys to move your balls</p>
<canvas id="canvas" style="border:1px solid black; border-radius: 5px;">
</canvas>
<script>
const c = document.getElementById("canvas");
const ctx = c.getContext("2d");
let settings = {
width: 100,
height: 100,
speed: 1
};
c.width = settings.width;
c.height = settings.height;
/*
Object holding boolean values for every keypress
*/
let keyPresses = {};
function listenKeyboard() {
document.addEventListener("keyup", keyUp);
document.addEventListener("keydown", keyDown);
};
const keyUp = e => {
keyPresses[e.key] = false;
};
const keyDown = e => {
// console.log(e.key)
keyPresses[e.key] = true;
};
class Player {
constructor(x, y, color, left, right, up, down, radius) {
this.x = x;
this.y = y;
this.color = color;
this.left = left;
this.right = right;
this.up = up;
this.down = down;
this.radius = radius;
}
draw() {
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
ctx.closePath();
ctx.fill();
}
update() {
if (keyPresses[this.left]) {
this.x -= settings.speed;
}
if (keyPresses[this.right]) {
this.x += settings.speed;
}
if (keyPresses[this.up]) {
this.y -= settings.speed;
}
if (keyPresses[this.down]) {
this.y += settings.speed;
}
// Screen bounds
if (this.x < 0 + this.radius) this.x = 0 + this.radius;
if (this.y < 0 + this.radius) this.y = 0 + this.radius;
if (this.x > settings.width - this.radius) this.x = settings.width - this.radius;
if (this.y > settings.height - this.radius) this.y = settings.width - this.radius;
}
}
/*
Creating the player objects
*/
let p1 = new Player(25, 25, "red", "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", 10);
let p2 = new Player(75, 75, "black", "a", "d", "w", "s", 5);
function draw() {
ctx.clearRect(0, 0, settings.width, settings.height);
p1.draw();
p2.draw();
};
function update() {
draw();
listenKeyboard();
p1.update();
p2.update();
requestAnimationFrame(update);
};
requestAnimationFrame(update);
</script>
</body>
</html>

Ping Pong in JavaScript?

I am trying to make a ping pong game. At the moment I got the ball moving and both paddles moving when keys pressed. But the ball does not bounce off the paddles. There is code to bounce off player2 paddle but it does not seem to work. It's a lot of code I know. Can you help me find out what is wrong?
"use strict";
// Variables
var c = document.getElementById("sCanvas");
var ctx = sCanvas.getContext("2d");
var cHeight = sCanvas.height;
var cWidth = sCanvas.width;
//Objects
//create paddle object
class Paddle {
constructor(x, y) {
this.colour = "red";
this.xPoss = x;
this.yPoss = y;
this.width = 12;
this.height = 60;
this.speed = 3;
}
drawMe() {
ctx.fillStyle = this.colour;
ctx.fillRect(this.xPoss, this.yPoss, this.width, this.height);
}
} // end paddle object
//create the sphere object
class Sphere {
constructor() {
this.radius = (10);
this.colour = "blue";
this.xPos = 65; //Math.random() * cWidth;
this.yPos = 100; //Math.random() * cHeight;
this.speedY = 5; //* Math.random();
this.speedX = 5; //* Math.random();
}
drawMe() {
//method to draw itself
ctx.beginPath();
ctx.arc(this.xPos, this.yPos, this.radius, 0, Math.PI * 2, true);
ctx.fillStyle = this.colour;
ctx.fill();
}
//method to move itself
moveMe() {
this.yPos += this.speedY;
this.xPos += this.speedX;
//bounce off the bottom wall
if (this.yPos > cHeight - this.radius) {
this.speedY = -this.speedY;
} //bounce off the top wall
else if (this.yPos < 0 + this.radius) {
this.speedY = -this.speedY;
}
//stop ball if hit right side
if (this.xPos > cWidth) {
this.speedX = 0;
this.speedY = 0;
}
//bounce off player 2 paddle
else if (this.xPos > player2.xPoss && (this.yPos > player2.yPoss && this.yPos < (player2.yPoss + player2.height))) {
this.speedX = -this.speedX;
}
}
//end moveMe function
} // end Sphere object
//******************
// create game objects
//******************
var ball = new Sphere();
var player1 = new Paddle(10, 150);
var player2 = new Paddle(580, 150);
//*********************
// Deal with key presses
// **********************
var keysDown = []; //empty array to store which keys are being held down
window.addEventListener("keydown", function(event) {
keysDown[event.keyCode] = true; //store the code for the key being pressed
});
window.addEventListener("keyup", function(event) {
delete keysDown[event.keyCode];
});
function checkKeys() {
if (keysDown[90]) {
if (player1.yPoss > 0) {
player1.yPoss = -player1.speed; //z
}
}
if (keysDown[88]) {
if (player1.yPoss < (cHeight - player1.height)) {
player1.yPoss += player1.speed; //x
}
}
if (keysDown[190]) {
if (player2.yPoss > 0) {
player2.yPoss = -player2.speed; //"."
}
}
if (keysDown[188]) {
if (player2.yPoss < (cHeight - player2.height)) {
player2.yPoss += player2.speed; //","
}
}
}
// your 2 new sets of code here for 2 more keys for player 2
//*********************
// Make the score board
// **********************
//*********************
// launch the ball from the centre, left and right, on space bar
// **********************
function render() {
requestAnimationFrame(render);
ctx.clearRect(0, 0, cWidth, cHeight);
ball.drawMe();
ball.moveMe();
player1.drawMe();
player2.drawMe();
checkKeys();
}
render(); //set the animation and drawing on canvas going
<canvas id="sCanvas" width="600" height="400" style="border: solid;"></canvas>
I added a simple hit box and detector and drawing the boxes in black to illustrate. Changed xPoss, yPoss to xPos, yPos for consistency. Changed = - to -= on the paddle movement (was snapping to top when moving up). Changed class and methods to JavaScript functions and prototype methods.
This should be enough to go on to see the how JavaScript does objects and how to do a simple hit detection. This isn't the only way to create objects but it is close to what you were trying to do.
update
Made some changes to hit/collision detection. Can now hit ball from bottom and top of paddle.
"use strict";
// Variables
var c = document.getElementById("sCanvas");
var ctx = sCanvas.getContext("2d");
var cHeight = sCanvas.height;
var cWidth = sCanvas.width;
//Objects
//create paddle object
function Paddle(x, y) {
this.colour = "red";
this.xPos = x;
this.yPos = y;
this.width = 12;
this.height = 60;
this.speed = 3;
}
Paddle.prototype.drawMe = function() {
ctx.fillStyle = this.colour;
ctx.fillRect(this.xPos, this.yPos, this.width, this.height);
}; // end paddle object
/***** BEGIN COLLISION DECTECTION FUNCTIONS *****/
// optimized collision of boxes - Does a hit b?
function hit(a, b) {
// Return immediately when the objects aren't touching.
if (
a.x2 < b.x || // a.right is before b.left
b.x2 < a.x || // b.right is before a.left
a.y2 < b.y || // a.bottom is before b.top
b.y2 < a.y // b.bottom is before a.top
) {
return false;
}
// The objects are touching. It is a hit or collision.
return true;
}
// does a hit the top of b?
function hitTop(a, b) {
return (a.y2 > b.y && a.y < b.y) ? true : false;
}
// does a hit the bottom of b?
function hitBottom(a, b) {
return (a.y < b.y2 && a.y2 > b.y2) ? true : false;
}
// Creates an obect of x, y, x2, y2 for hit detection.
function hitObj(obj) {
var h = {x:0, y:0, x2:0, y2:0};
if (obj.radius) {
h.x = obj.xPos - obj.radius;
h.x2 = obj.xPos + obj.radius;
h.y = obj.yPos - obj.radius;
h.y2 = obj.yPos + obj.radius;
} else {
h.x = obj.xPos;
h.x2 = obj.xPos + obj.width | (obj.radius * 2);
h.y = obj.yPos;
h.y2 = obj.yPos + obj.height | (obj.radius * 2);
}
// draw hit box - uncomment to see hit detection
/*
ctx.save();
ctx.strokeStyle = "#000000";
ctx.lineWidth = 5;
ctx.strokeRect(h.x, h.y, h.x2 - h.x, h.y2 - h.y);
ctx.restore();
*/
return h;
}
/***** END COLLISION DETECTION FUNCTIONS *****/
//create the sphere object
function Sphere() {
this.radius = (10);
this.colour = "blue";
this.xPos = 25; //Math.random() * cWidth;
this.yPos = 5; //Math.random() * cHeight;
this.speedY = 5; //* Math.random();
this.speedX = 5; //* Math.random();
}
Sphere.prototype.drawMe = function() {
//method to draw itself
ctx.beginPath();
ctx.arc(this.xPos, this.yPos, this.radius, 0, Math.PI * 2, true);
ctx.fillStyle = this.colour;
ctx.fill();
};
Sphere.prototype.moveMe = function() {
//method to move itself
// save start position. change back to start
// position when there's a hit so we don't
// get stuck in an object.
var pos = {
x: this.xPos,
y: this.yPos
};
// move
this.yPos += this.speedY;
this.xPos += this.speedX;
//bounce off the bottom wall
if (this.yPos > cHeight - this.radius) {
this.yPos = pos.y;
this.speedY = -this.speedY;
} //bounce off the top wall
else if (this.yPos < 0 + this.radius) {
this.yPos = pos.y;
this.speedY = -this.speedY;
}
/*
//stop ball if hit right side
if (this.xPos > cWidth) {
this.speedX = 0;
this.speedY = 0;
}
*/
// Bounce off left and right sides.
if ((this.xPos+this.radius) >= cWidth || this.xPos <= 0) {
this.xPos = pos.x;
this.speedX = -this.speedX;
}
//bounce off player paddle
else {
var pad1 = hitObj(player1);
var pad2 = hitObj(player2);
var ball = hitObj(this);
if (hit(ball, pad2)) {
// hit player2
this.xPos = pos.x;
this.speedX *= -1;
// if the ball travels down and hits top OR
// if the ball travels up and hits bottom then bounce back
if (
(this.speedY > 0 && hitTop(ball, pad2)) ||
(this.speedY < 0 && hitBottom(ball, pad2))
) {
this.yPos = pos.y;
this.speedY *= -1;
}
} else if (hit(ball, pad1)) {
// hit player1
this.xPos = pos.x;
this.speedX *= -1;
// if the ball travels down and hits top OR
// if the ball travels up and hits bottom then bounce back
if (
(this.speedY > 0 && hitTop(ball, pad1)) ||
(this.speedY < 0 && hitBottom(ball, pad1))
) {
this.yPos = pos.y;
this.speedY *= -1;
}
}
}
};
//end moveMe function
//******************
// create game objects
//******************
var ball = new Sphere();
var player1 = new Paddle(10, 150);
var player2 = new Paddle(580, 150);
//*********************
// Deal with key presses
// **********************
var keysDown = []; //empty array to store which keys are being held down
window.addEventListener("keydown", function(event) {
keysDown[event.keyCode] = true; //store the code for the key being pressed
});
window.addEventListener("keyup", function(event) {
delete keysDown[event.keyCode];
});
function checkKeys() {
if (keysDown[90]) {
if (player1.yPos > 0) {
player1.yPos -= player1.speed; //z
}
}
if (keysDown[88]) {
if (player1.yPos < (cHeight - player1.height)) {
player1.yPos += player1.speed; //x
}
}
if (keysDown[190]) {
if (player2.yPos > 0) {
player2.yPos -= player2.speed; //"."
}
}
if (keysDown[188]) {
if (player2.yPos < (cHeight - player2.height)) {
player2.yPos += player2.speed; //","
}
}
}
// your 2 new sets of code here for 2 more keys for player 2
//*********************
// Make the score board
// **********************
//*********************
// launch the ball from the centre, left and right, on space bar
// **********************
function render() {
requestAnimationFrame(render);
ctx.clearRect(0, 0, cWidth, cHeight);
ball.drawMe();
ball.moveMe();
player1.drawMe();
player2.drawMe();
checkKeys();
}
render(); //set the animation and drawing on canvas going
#sCanvas {
width: 300px;
height: 200px;
}
<canvas id="sCanvas" width="600" height="400" style="border: solid;"></canvas>

Categories