Javascript make the ball move - javascript

I am trying to make the ball move when I press space, but I can't seem to figure out how to do it.
It is vanilla Javascript with createjs libary. Can anybody help me and give me a little hint?
window.addEventListener('load', preload);
var canvas = document.getElementById('myCanvas');
var stage, queue;
var ball;
var paddle;
var settings = {
lives: 3,
points: 0,
speed: 3,
ballMovingSpeed: 7
}
var fingerDown = false;
var keys = {
left: false,
right: false,
shoot: false
}
var ballSettings = {
ballRadius: 10,
dx: 2,
dy: -2
}
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
function preload() {
"use strict";
stage = new createjs.Stage("myCanvas");
queue = new createjs.LoadQueue(true);
createjs.Ticker.setFPS(60);
createjs.Ticker.addEventListener("tick", tickHappened);
drawPaddle();
drawBall();
window.addEventListener('keydown', keyDown);
window.addEventListener('keyup', keyUp);
}
function drawBall() {
"use strict"
ball = new createjs.Shape();
ball.graphics.beginFill('red').drawCircle(0, 0, 10);
stage.addChild(ball);
ball.x = 400;
ball.y = 535;
canvasHeight += ballSettings.dy;
canvasWidth += ballSettings.dx;
}
// paddle Movement
//--------------------------------*
function keyDown(e) {
"use strict";
console.log(e.keyCode);
switch (e.keyCode) {
case 37:
keys.left = true;
break;
case 39:
keys.right = true;
break;
case 32:
keys.shoot = true;
break;
}
}
function keyUp(e) {
"use strict";
switch (e.keyCode) {
case 37:
keys.left = false;
break;
case 39:
keys.right = false;
break;
case 32:
keys.shoot = false;
break;
}
}
function movePaddle() {
"use strict";
if (keys.left) {
paddle.x -= settings.speed;
if (paddle.x < 0 + paddle.regX) {
paddle.x = 0 + paddle.regX;
}
} else if (keys.right) {
paddle.x += settings.speed;
if (paddle.x > canvasWidth - paddle.width + paddle.regX) {
paddle.x = canvasWidth - paddle.width + paddle.regX;
}
} else if (keys.shoot) {
console.log("shoot ball");
if (canvasWidth + ballSettings.dx > canvas.width - ballSettings.ballRadius || canvasWidth + ballSettings.dx < ballSettings.ballRadius) {
ballSettings.dx = -ballSettings.dx;
}
if (canvasHeight + ballSettings.dy > canvas.height - ballSettings.ballRadius || canvasHeight + ballSettings.dy < ballSettings.ballRadius) {
ballSettings.dy = -ballSettings.dy;
}
}
}
function tickHappened(e) {
"use strict";
movePaddle();
stage.update(e);
}

So in order to have your object move, you need a few things. First, you need to re-draw it, which you seem to have set to re-draw 60 times per second. Next, you have to update the position of your object. Your ball needs two things for that, a velocity X and a velocity Y. With each tick, you'll set the ball.x += ball.velX so that each time it'll move it's position along with it's moving velocity, and once it hits something just set the ball.velX = -ball.velX.
I'm not sure what project you're working on but I'm assuming it is somewhat similar to pong, if you'd like to review or use some of the code I used on my own pong game feel free - http://pongio.bitballoon.com/

Related

How to fix the direction and body problems?

i'm a rookie and i try to learn by myself from different sources html css and now i'm on the block of JS
I'm actually doing a snake game but i have differents issues , the body of my snake supposed to be 3 blocks width , and he is also supposed to move with the arrow key !!
I'm kind stuck and request your knowledge to let me find the light again :)
//* I'm french and hope my english is correct *//
window.onload = function()
{
var canvasWidth = 900;
var canvasHeight = 600;
var blockSize = 30;
var ctx;
var delay = 100;
var snakee;
init();
function init()
{
var canvas = document.createElement('canvas')
canvas.width = canvasWidth;
canvas.height = canvasHeight;
canvas.style.border = "1px solid"
document.body.appendChild(canvas);
ctx = canvas.getContext('2d');
snakee = new Snake([[6,4],[5,4],[4,4],[3,4],[2,4]], "right");
refreshCanvas();
}
function refreshCanvas()
{
ctx.clearRect (0,0,canvasWidth, canvasHeight);
snakee.draw();
snakee.advance();
setTimeout(refreshCanvas, delay);
}
function drawBlock(ctx, position)
{
var x = position[0] * blockSize;
var y = position[1] * blockSize;
ctx.fillRect(x ,y , blockSize , blockSize );
}
function Snake(body, _direction)
{
this.body = body;
this.direction = "right";
this.draw = function ()
{
ctx.save();
ctx.fillStyle = "#ff0000";
for(var i = 0; i < this.body.lenght; i++);
{
drawBlock(ctx, this.body[i]);
}
ctx.restore();
};
this.advance = function()
{
var nextPosition = this.body[0].slice();
switch(this.direction)
{
case "left":
nexPosition[0] -= 1;
break;
case "right":
nextPosition[0] += 1;
break;
case "down":
nextPosition[1] -= 1;
break;
case "up":
nextPosition[1] += 1;
break;
default:
throw("Invalid Direction");
}
this.body.unshift(nextPosition);
this.body.pop();
};
this.setDirection = function(newDirection)
{
var allowedDirections;
switch(this.direction)
{
case "left":
case "right":
allowedDirections = ["up", "donw"];
break;
case "down":
case "up":
allowedDirections = ["left","right"]
break;
default:
throw("Invalid Direction");
}
if(allowedDirections.indexOf(newDirection) > -1 )
{
this.direction = newDirection;
}
};
}
}
document.addEventListener = function handleKeyDown(e)
{
const key = e.keyCode;
var newDirection;
switch(key)
{
case 37:
newDirection = "left";
break;
case 38:
newDirection = "right";
break;
case 39:
newDirection = "up";
break;
case 40:
newDirection = "down";
break;
default:
return;
}
snakee.setDirection(newDirection);
}
addEventListener is a function and takes at least two arguments
it should be:
document.addEventListener('keydown', (e) => {
let code = e.keyCode;
})
Where the first arg is the type of event to handle and the second is the callback - handling the event.
I've noticed a few bugs in your code:
for(var i = 0; i < this.body.*lenght*; i++); << remove semicolon, lenght is typo
case "down":
nextPosition[1] -= 1; << should incrementing
break;
case "up":
nextPosition[1] += 1; << should decrementing
break;
Also the addEventListener code should be inside the window.onload statement
or else it will not see the snakee object.
This code simply won't work for a full blown snake program, because
each block of the snake can have a separate direction, but it's a start.

If statement inside requestanimationframe continues even if parameters aren't met

I'm making a little video game, where the background (platform) moves down with my character (square) jumps. On line 113 I have tried different strategies to implement this thought, and that is the closest it has gotten to work. The issue is that even when the square velocity is 0, the platform velocity isn't. I have been stuck for a week now, and feels like javascript is the problem (even though I know it isn't).
canvasmain.width = window.innerWidth;
canvasmain.height = window.innerHeight;
//CHARACTER:
const square = {
height: 75,
jumping: true,
width: 75,
x: canvasmain.width / 2,
xVelocity: 0,
y: canvasmain.height / 2,
yVelocity: 0
};
//floor
const platform = {
height: 30,
width: 100,
x: square.x,
xVelocity: 0,
y: square.y + square.height,
yVelocity:0
}
//MOVEMENT:
const controller = {
left: false,
right: false,
up: false,
keyListener: function (event) {
let key_state = (event.type == "keydown") ? true : false;
switch (event.keyCode) {
case 37: // left arrow
controller.left = key_state;
break;
case 38: // up arrow
controller.up = key_state;
break;
case 39: // right arrow
controller.right = key_state;
break;
}
}
};
const loop = function () {
if (controller.up && square.jumping == false) {
square.yVelocity -= 30;
square.jumping = true;
}
if (controller.left) {
square.xVelocity -= 0.5;
}
if (controller.right) {
square.xVelocity += 0.5;
}
square.yVelocity += 1.5;// gravity
square.x += square.xVelocity;
square.y += square.yVelocity;
square.xVelocity *= 0.9;// friction
square.yVelocity *= 0.9;// friction
// if square is falling below floor line
if (square.y > canvasmain.height - 75) {
square.jumping = false;
square.y = canvasmain.height - 75;
square.yVelocity = 0;
}
// if square is going off the left of the screen
if (square.x < 0) {
square.x = 0;
} else if (square.x > canvasmain.width - 75) {// if square goes past right boundary
square.x = canvasmain.width - 75;
}
// Creates the backdrop for each frame
context.fillStyle = "#394129";
context.fillRect(0, 0, canvasmain.width, canvasmain.height); // x, y, width, height
// Creates and fills the cube for each frame
context.fillStyle = "#8DAA9D"; // hex for cube color
context.beginPath();
context.rect(square.x, square.y, square.width, square.height);
context.fill();
// Creates the "ground" for each frame
context.fillStyle = "#202020";
context.beginPath();
context.rect(platform.x, platform.y, platform.width, platform.height)
context.fill();
// call update when the browser is ready to draw again
window.requestAnimationFrame(loop);
//platform
platform.y += platform.yVelocity;
console.log(square.yVelocity)
if (square.yVelocity > 0.1 ) {
platform.yVelocity = 1.5
};
if (square.yVelocity < 0 ) {
platform.yVelocity = -1.5
};
}
window.addEventListener("keydown", controller.keyListener)
window.addEventListener("keyup", controller.keyListener);
window.requestAnimationFrame(loop);
You're not reseting the value of yVelocity.
Got it guys, thx #Teemu, I just needed to set it to 0 if it wasn't the if's. Dang, really took a while. if (square.yVelocity > 0 ) {platform.yVelocity = 1.5} else{ platform.yVelocity = 0}; if (square.yVelocity < 0 ) {platform.yVelocity = -1.5} else { platform.yVelocity = 0} }
edit: frick, it only moves the platform when the cube is going up, not down ;-;

Make player stop in front of invisible platform

so I have a 2d platformer in the works, and I'd like to add walls and platforms to it, but when I try to make a platform, it doesn't stop the player in front of it if they just walk forward, and instead it makes it sort of like a step/stairs.
Here's what I have so far:
var ctx, controller, rectangle, loop;
ctx = document.querySelector("canvas").getContext("2d");
// Screen size
ctx.canvas.height = 200;
ctx.canvas.width = 400;
// Position of Player
rectangle = {
height: 25,
jumping: true,
width: 25,
x: 10,
x_velocity: 0,
y: 0,
y_velocity: 0
};
controller = {
left: false,
right: false,
up: false,
keyListener: function(event) {
var key_state = (event.type == "keydown") ? true : false;
switch (event.keyCode) {
case 37: // Left
controller.left = key_state;
break;
case 39: // Right
controller.right = key_state;
break;
case 38: // Up
controller.up = key_state;
break;
};
}
};
loop = function() {
if (controller.up && rectangle.jumping == false) {
rectangle.y_velocity -= 25;
rectangle.jumping = true;
};
if (controller.left) {
rectangle.x_velocity -= 0.75;
};
if (controller.right) {
rectangle.x_velocity += 0.75;
};
// Gravity
rectangle.y_velocity += 1.5;
rectangle.x += rectangle.x_velocity;
rectangle.y += rectangle.y_velocity;
// Friction
rectangle.x_velocity *= 0.75;
rectangle.y_velocity *= 0.75;
// Floor
if (rectangle.y > 150 - 25) {
rectangle.jumping = false;
rectangle.y = 150 - 25;
rectangle.y_velocity = 0;
};
// Platform
if (rectangle.y > 145 - 25 && rectangle.x > 150 - 25) {
rectangle.jumping = false;
rectangle.y = 145 - 25;
rectangle.y_velocity = 0;
};
// Background
var bg = new Image;
bg.src = "https://i.imgur.com/He3uld9.png";
bg.onload = function() {
ctx.drawImage(bg, 0, 0);
};
// Player
var ply = new Image;
ply.src = "https://i.imgur.com/G4UUkIl.png";
ply.onload = function() {
ctx.drawImage(ply, rectangle.x, rectangle.y);
};
// Floor
var fl = new Image;
fl.src = "https://i.imgur.com/OoKP4Mm.png";
fl.onload = function() {
ctx.drawImage(fl, 0, 150);
};
window.requestAnimationFrame(loop);
};
window.addEventListener("keydown", controller.keyListener);
window.addEventListener("keyup", controller.keyListener);
window.requestAnimationFrame(loop);
<canvas style="border: 1px solid black;"></canvas>
The commented part that says Platform under the JS section is where my code for the platform currently is. As of now, it doesn't have an image or object for you to see it, but if you play the game, it is an invisible platform right above the floor.
What if you try to maintain a blockedRight and a blockedLeft property on the rectangle according to the zone you're in ? For instance, I have implemented a blockedRight boolean in the below where for Platform region, I turn it to true and for a Valid Region , I turn it back to false. Also I add this condition check in controller.right check as well.
So for an obstacle region that comes , you can make a condition that if the person is blockedRight and it tries to jump, you will set the blockedRight again to false. I am assuming the obstacles will be always taken care by jumping unless you have those which are greater than your jump height where more checks come in place.
var ctx, controller, rectangle, loop;
ctx = document.querySelector("canvas").getContext("2d");
// Screen size
ctx.canvas.height = 200;
ctx.canvas.width = 400;
// Position of Player
rectangle = {
height: 25,
jumping: true,
width: 25,
x: 10,
x_velocity: 0,
y: 0,
y_velocity: 0,
blockedRight:false
};
controller = {
left: false,
right: false,
up: false,
keyListener: function(event) {
var key_state = (event.type == "keydown") ? true : false;
switch (event.keyCode) {
case 37: // Left
controller.left = key_state;
break;
case 39: // Right
controller.right = key_state;
break;
case 38: // Up
controller.up = key_state;
break;
};
}
};
loop = function() {
if (controller.up && rectangle.jumping == false) {
rectangle.y_velocity -= 25;
rectangle.jumping = true;
};
if (controller.left) {
rectangle.x_velocity -= 0.75;
};
if (controller.right && !rectangle.blockedRight) {
rectangle.x_velocity += 0.75;
};
// Gravity
rectangle.y_velocity += 1.5;
rectangle.x += rectangle.x_velocity;
rectangle.y += rectangle.y_velocity;
// Friction
rectangle.x_velocity *= 0.75;
rectangle.y_velocity *= 0.75;
// Floor
if (rectangle.y > 150 - 25) {
rectangle.jumping = false;
rectangle.y = 150 - 25;
rectangle.y_velocity = 0;
};
// Valid ground
if(rectangle.x <= 150 - 25){
rectangle.blockedRight = false;
}
// Platform
if (rectangle.y > 145 - 25 && rectangle.x > 150 - 25) {
rectangle.blockedRight = true;
rectangle.jumping = false;
rectangle.y = 145-25;
rectangle.y_velocity = 0;
};
// Background
var bg = new Image;
bg.src = "https://i.imgur.com/He3uld9.png";
bg.onload = function() {
ctx.drawImage(bg, 0, 0);
};
// Player
var ply = new Image;
ply.src = "https://i.imgur.com/G4UUkIl.png";
ply.onload = function() {
ctx.drawImage(ply, rectangle.x, rectangle.y);
};
// Floor
var fl = new Image;
fl.src = "https://i.imgur.com/OoKP4Mm.png";
fl.onload = function() {
ctx.drawImage(fl, 0, 150);
};
window.requestAnimationFrame(loop);
};
window.addEventListener("keydown", controller.keyListener);
window.addEventListener("keyup", controller.keyListener);
window.requestAnimationFrame(loop);
<canvas style="border: 1px solid black;"></canvas>

How do I stop the screen flickering when moving my character by pressing the arrow keys in JavaScript?

Can anybody help me with my problem please? I've managed to clear the canvas before redrawing my game character, but was wondering how to stop the screen from flickering as the character moves in JavaScript. Thank you for your help. Help much appreciated. Here's my code.
var avatarX = 0;
var avatarY = 267;
var avatarImage;
var counter = 1;
var XWIDTH = 0;
var WIDTH = 400;
var dx = 5;
var tt;
window.addEventListener('keydown', KeyDown);
function setUpGame() { //This is the function that is called from the html document.
var gameCanvas = document.getElementById("gameCanvas"); //Declare a new variable & assigns it the id of the CANVAS from the html document.
avatarImage = new Image(); //Declaring a new variable. This is so that we can store the image at a later date.
avatarImage.src = "img/avatar.png"; //Ditto from above.
gameCanvas.getContext("2d").drawImage(avatarImage, Math.random() * 100, avatarY);
var tt = setInterval(function(){counTer()},1000);
setInterval(handleTick, 25);
}
function KeyDown(evt) {
switch (evt.keyCode) {
case 39: /*Arrow to the right*/
if(avatarX + dx <WIDTH && avatarX + dx >XWIDTH) {
avatarX += dx;
gameCanvas.width = gameCanvas.width;
}
break;
case 37: /*Arrow to the left*/
if(avatarX - dx >XWIDTH) {
avatarX -= dx;
gameCanvas.width = gameCanvas.width;
}
break;
}
}
function counTer() {
if(counter == 60) {
clearInterval(tt);
} else {
counter++;
gameCanvas.width = 400;
gameCanvas.getContext("2d").font = "18px Iceland";
gameCanvas.getContext("2d").textBaseline = "top";
gameCanvas.getContext("2d").fillText("Seconds: " + counter, 5, 5);
}
}
function handleTick() {
gameCanvas.getContext("2d").drawImage(avatarImage, avatarX, avatarY);
}
Some observations:
Create the context once at the top of your code instead of every time you use it.
Set the font and textBaseline once at the top of your code instead of every time you use it.
Clear the canvas only when needed (only in handleTick).
Draw the clock-timer at the same time you draw the avatar (saves 1 canvas clearing).
Attach an onload function to avatarImage so you know the image is ready to drawImage
Here's modified code -- it's untested so you'll need to review it ;)
Good luck with your project!
var avatarX = 0;
var avatarY = 267;
var avatarImage;
var counter = 1;
var XWIDTH = 0;
var WIDTH = 400;
var dx = 5;
var tt;
var gameCanvas;
var context;
window.addEventListener('keydown', KeyDown);
function setUpGame() { //This is the function that is called from the html document.
gameCanvas = document.getElementById("gameCanvas"); //Declare a new variable & assigns it the id of the CANVAS from the html document.
context=gameCanvas.getContext("2d");
context.font = "18px Iceland";
context.textBaseline = "top";
avatarImage = new Image(); //Declaring a new variable. This is so that we can store the image at a later date.
avatarImage.onload=function(){
// avatarImage is now fully loaded and ready to drawImage
context.drawImage(avatarImage, Math.random() * 100, avatarY);
// start the timer
tt = setInterval(function(){counTer()},1000);
setInterval(handleTick, 25);
}
avatarImage.src = "img/avatar.png"; //Ditto from above.
}
function KeyDown(evt) {
switch (evt.keyCode) {
case 39: /*Arrow to the right*/
if(avatarX + dx <WIDTH && avatarX + dx >XWIDTH) {
avatarX += dx;
}
break;
case 37: /*Arrow to the left*/
if(avatarX - dx >XWIDTH) {
avatarX -= dx;
}
break;
}
}
function counTer() {
if(counter == 60) {
clearInterval(tt);
} else {
counter++;
}
}
function handleTick() {
context.clearRect(0,0,canvas.width,canvas.height);
context.drawImage(avatarImage, avatarX, avatarY);
context.fillText("Seconds: " + counter, 5, 5);
}

JavaScript game not working, freezes after initialization

I have the following problem: I'am trying to make a simple game in JavaScript. The idea of the game is to have a canvas, a ball bouncing inside and small pad going left to right to hit the ball. I've done it like this, and it works fine:
var canvasBg;
var contextBg;
var canvasBall;
var contextBall;
function Drawable() {
this.initialize = function(x,y) {
this.x = x;
this.y = y;
};
this.draw = function() {
};
}
function Ball() {
var dx = 2;
var dy = 2;
var radius = 5;
this.draw = function() {
contextBall.beginPath();
contextBall.clearRect(0,0,canvasBall.width,canvasBall.height);
contextBall.closePath();
contextBall.beginPath();
contextBall.fillStyle = "#0000ff";
contextBall.arc(this.x, this.y, radius, 0, Math.PI*2, true);
contextBall.closePath();
contextBall.fill();
// the code seems to stop here
if(this.x<0 || this.x>300)
dx = -dx;
if(this.y<0 || this.y>150)
dy = -dy;
if((this.x+radius)>pad.x && (this.x-radius)<(pad.x+50) && (this.y+radius)>pad.y && (this.y-radius)<(pad.y+10)) {
dy = -dy;
}
if(this.y>(pad.y-2) && this.y<(pad.y+12) && (this.x+radius)>pad.x && (this.x-radius)<(pad.x+50)) {
dx = -dx;
}
this.x += dx;
this.y += dy;
};
}
Ball.prototype = new Drawable();
KEY_CODES = {
37: 'left',
39: 'right',
};
KEY_STATUS = {};
for (code in KEY_CODES) {
KEY_STATUS[ KEY_CODES[ code ]] = false;
}
document.onkeydown = function(e) {
var keyCode = (e.keyCode) ? e.keyCode : e.charCode;
if (KEY_CODES[keyCode]) {
e.preventDefault();
KEY_STATUS[KEY_CODES[keyCode]] = true;
}
};
document.onkeyup = function(e) {
var keyCode = (e.keyCode) ? e.keyCode : e.charCode;
if (KEY_CODES[keyCode]) {
e.preventDefault();
KEY_STATUS[KEY_CODES[keyCode]] = false;
}
};
function Pad() {
var hSpeed = 5;
this.padWidth = 50;
this.padHeight = 10;
this.draw = function() {
contextBg.clearRect(0,0,canvasBg.width,canvasBg.height);
contextBg.fillStyle = "#ffffff";
contextBg.fillRect(this.x,this.y,this.padWidth,this.padHeight);
};
this.move = function() {
if(KEY_STATUS.left || KEY_STATUS.right) {
contextBg.clearRect(0,0,canvasBg.width,canvasBg.height);
if(KEY_STATUS.left) {
this.x -= hSpeed;
if (this.x <= 0)
this.x = 0;
} else if (KEY_STATUS.right) {
this.x += hSpeed;
if (this.x >= 300-this.padWidth)
this.x = 300 - this.padWidth;
}
this.draw();
}
};
}
Pad.prototype = new Drawable();
function init() {
canvasBg = document.getElementById('display');
contextBg = this.canvasBg.getContext('2d');
canvasBall = document.getElementById('ball');
contextBall = this.canvasBall.getContext('2d');
ball = new Ball();
ball.initialize(10,10);
pad = new Pad();
pad.initialize(120,80);
setInterval(function(){animate();},30);
}
function animate() {
ball.draw();
pad.draw();
pad.move();
};
However, I decided to try to improve my code a bit, and i made a class GamePlay:
var game = new GamePlay();
function Drawable() {
this.initialize = function(x,y) {
this.x = x;
this.y = y;
};
this.draw = function() {
};
}
function Ball() {
var dx = 2;
var dy = 2;
var radius = 5;
this.draw = function() {
this.context.beginPath();
this.context.clearRect(0,0,this.canvas.width,this.canvas.height);
this.context.closePath();
this.context.beginPath();
this.context.fillStyle = "#0000ff";
this.context.arc(this.x, this.y, radius, 0, Math.PI*2, true);
this.context.closePath();
this.context.fill();
if(this.x<0 || this.x>300)
dx = -dx;
if(this.y<0 || this.y>150)
dy = -dy;
if((this.x+radius)>pad.x && (this.x-radius)<(pad.x+50) && (this.y+radius)>pad.y && (this.y-radius)<(pad.y+10)) {
dy = -dy;
}
if(this.y>(pad.y-2) && this.y<(pad.y+12) && (this.x+radius)>pad.x && (this.x-radius)<(pad.x+50)) {
dx = -dx;
}
this.x += dx;
this.y += dy;
};
}
Ball.prototype = new Drawable();
KEY_CODES = {
37: 'left',
39: 'right',
};
KEY_STATUS = {};
for (code in KEY_CODES) {
KEY_STATUS[ KEY_CODES[ code ]] = false;
}
document.onkeydown = function(e) {
var keyCode = (e.keyCode) ? e.keyCode : e.charCode;
if (KEY_CODES[keyCode]) {
e.preventDefault();
KEY_STATUS[KEY_CODES[keyCode]] = true;
}
};
document.onkeyup = function(e) {
var keyCode = (e.keyCode) ? e.keyCode : e.charCode;
if (KEY_CODES[keyCode]) {
e.preventDefault();
KEY_STATUS[KEY_CODES[keyCode]] = false;
}
};
function Pad() {
var hSpeed = 5;
this.padWidth = 50;
this.padHeight = 10;
this.draw = function() {
this.context.clearRect(0,0,this.canvas.width,this.canvas.height);
this.context.fillStyle = "#ffffff";
this.context.fillRect(this.x,this.y,this.padWidth,this.padHeight);
};
this.move = function() {
if(KEY_STATUS.left || KEY_STATUS.right) {
this.context.clearRect(0,0,this.canvas.width,this.canvas.height);
if(KEY_STATUS.left) {
this.x -= hSpeed;
if (this.x <= 0)
this.x = 0;
} else if (KEY_STATUS.right) {
this.x += hSpeed;
if (this.x >= 300-this.padWidth)
this.x = 300 - this.padWidth;
}
this.draw();
}
};
}
Pad.prototype = new Drawable();
function GamePlay() {
var ball;
var pad;
this.setUpGame = function() {
this.canvasBg = document.getElementById('display');
this.contextBg = this.canvasBg.getContext('2d');
this.canvasBall = document.getElementById('ball');
this.contextBall = this.canvasBall.getContext('2d');
Ball.prototype.canvas = this.canvasBall;
Ball.prototype.context = this.contextBall;
Pad.prototype.canvas = this.canvasBg;
Pad.prototype.context = this.contextBg;
ball = new Ball();
ball.initialize(10,10);
pad = new Pad();
pad.initialize(120,80);
};
var animate = function() {
ball.draw();
pad.draw();
pad.move();
};
this.startGame = function() {
setInterval(function(){animate();},30);
};
}
function init() {
game.setUpGame();
game.startGame();
}
BUT, it only draws a ball on its initializing coordinates and then seems to stop there. I tried to do some manual testing by putting alert() on certain points in code and I found out that it seems to stop in the middle of ball's draw method and skips calling pad.draw() and pad.move() in animate(). I don't know what is wrong, my guess that is something with prototypes. I am new to JavaScript and this prototype-based OOP is still a bit confusing to me. Thanks.
I've tried code and found next problems:
function init - hope it is called after html is fully loaded
Ball.draw function refers object pad, which is not defined in its context, use game.pad
var animate = function creates local "private" variable, change it to this.animate = function
in setInterval call proper function setInterval(function(){game.animate();},30);
var game = new GamePlay(); is called before GamePlay is defined, move this string below
after these changes it works without errors in console
I believe this is because of your miss-use of paths in your draw method.
First, you don't need to wrap .clearRect with .beginPath and .closePath.
Second, and what is likely causing your script to error is that you are using .fill after .closePathwhen you draw the circle. .fill should be used before .closePath and actually after using .fill you don't need to use .closePath as it will already close your path for you.

Categories

Resources