JavaScript game not working, freezes after initialization - javascript

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.

Related

Add a counter of the number of objets clicked

I just made this animation using canvas. Shows a number of bubbles scrolling from top to bottom. Clicking on any bubble starts it moving top to bottom again.
I plan to add a counter of the number of bubbles clicked/picked with a localStorage but I have difficulties implementing it.
Here is how I implemented it.
Each bubble now has id property.
Every time you run the script, it puts empty array to localStorage.clickedBubbles.
When a bubble is clicked, the array is checked if it contains the id. If not, the id is pushed to local storage.
Also, each click the count is logged to console.
const INITIALIZATION = 100;
const STEP1 = 200;
const BUBBLES = 10;
const SPEED = 10;
let counter = 0;
localStorage.setItem("clickedBubbles", "[]");
function Bubble(x, y, radio) {
this.id = counter++;
this.x = x;
this.y = y;
this.radio = radio;
this.color = "blue";
this.speed = 5;
this.getId = function () {
return this.id;
};
this.getX = function () {
return this.x;
};
this.getY = function () {
return this.y;
};
this.getRadio = function () {
return this.radio;
};
this.getColor = function () {
return this.color;
};
this.getspeed = function () {
return this.speed;
};
this.setX = function (x) {
this.x = x;
};
this.setY = function (y) {
this.y = y;
};
this.setRadio = function (radio) {
this.radio = radio;
};
this.setColor = function (color) {
this.color = color;
};
this.setSpeed = function (speed) {
this.speed = speed;
};
this.draw = function (ctx) {
ctx.save();
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.radio, 0, Math.PI * 2, true);
ctx.fill();
ctx.fillStyle = "white";
ctx.beginPath();
ctx.arc(
this.x + this.radio / 3,
this.y - this.radio / 3,
this.radio / 4,
0,
Math.PI * 2,
true
);
ctx.fill();
ctx.restore();
};
this.coordinates = function (x, y) {
var ax = this.getX() - this.getRadio();
var ay = this.getY() - this.getRadio();
return (
x >= ax &&
x <= ax + 2 * this.getRadio() &&
y >= ay &&
y <= ay + 2 * this.getRadio()
);
};
}
function animationBubbles() {
var bubbles = [];
var arrayColors;
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var status = INITIALIZATION;
var app = this;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
this.click = function (e) {
var x = e.x || e.pageX || e.clientX;
var y = e.y || e.clientY || e.pageY;
const clickedArr = JSON.parse(localStorage.getItem("clickedBubbles"));
for (var i = 0; i < bubbles.length; i++) {
var aux = bubbles[i];
if (aux.coordinates(x, y)) {
if (!clickedArr.includes(aux.getId())) {
clickedArr.push(aux.getId());
localStorage.setItem("clickedBubbles", JSON.stringify(clickedArr));
}
aux.setY(0);
break;
}
}
console.log("Clicked count: " + clickedArr.length);
};
canvas.addEventListener("mousedown", this.click, false);
this.realizeAnimation = function () {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < bubbles.length; i++) {
var aux = bubbles[i];
if (aux.getY() < canvas.height) {
aux.setY(aux.getY() + aux.getspeed());
} else {
aux.setY(0);
aux.setColor(arrayColors[Math.floor(Math.random() * 4)]);
}
aux.draw(ctx);
}
setTimeout(app.realizeAnimation, 100);
};
this.createBubbles = function () {
for (var i = 1; i <= BUBBLES; i++) {
var burbuja = new Bubble(
canvas.width * (i / BUBBLES),
0,
this.generateRandom(Math.floor(canvas.width / 20))
);
burbuja.setSpeed(SPEED);
burbuja.setColor(arrayColors[this.generateRandom(4)]);
bubbles.push(burbuja);
}
};
this.generateRandom = function (num) {
return Math.floor(Math.random() * num);
};
this.initColor = function () {
arrayColors[0] = "#C923C9";
arrayColors[1] = "#FAEF20";
arrayColors[2] = "#20ECFA";
arrayColors[3] = "#FA209C";
};
this.machineStates = function () {
if (status === INITIALIZATION) {
arrayColors = [];
this.initColor();
this.createBubbles();
status = STEP1;
setTimeout(app.machineStates, 100);
} else {
app.realizeAnimation();
}
};
this.machineStates();
}
new animationBubbles();

Game components won't draw after adding if/else statement

My game components won't draw onto the canvas after adding if/else statement.
The statement only checks if the game piece hit the game obstacle.
I tried changing attributes and rewrite some functions but it seems the problem hasn't been fixed.
Whenever I remove the if/else function, the components draw.
Here is part of the code that holds that if/else function:
if(gamePieceBorder.crashGame(gameObstacle) || gamePieceRed.crashGame(gameObstacle))
{
gameArea.stop();
}
else
{
obstacle.update();
gamePieceBorder.pos();
gamePieceBorder.move();
gamePieceBorder.update();
gamePieceRed.pos();
gamePieceRed.move();
gamePieceRed.update();
gameArea.clear();
}
For me not pasting an entire code, here is the pastebin link to the code: https://pastebin.com/HuiR7r7D
How can I get the components to draw? If someone fixes the code, what was the issue? I am not an expert at javascript but only a beginner.
There are several problems:
window.EventListener should be window.addEventListener
keyup and keydown should have no upper case letters
gameObstacle in that if is undefined (should be obstacle probably)
clear method should be called before drawing, not after it
Here is the corrected script: https://pastebin.com/bXpQ2qvB
//-----------------------------------------Variables
var gamePieceRed;
var gamePieceBorder;
var gameObstacle;
//-----------------------------------------
//-----------------------------------------Main game function
function startGame()
{
gamePieceRed = new component(22, 22, "rgb(255, 132, 156)", 10, 120);
gamePieceBorder = new component(24, 24, "black", 9, 119);
obstacle = new component(10, 200, "rgb(64, 0 ,12)", 300, 120)
gameArea.start();
}
//-----------------------------------------
//-----------------------------------------Creating game area and applying controls
var gameArea =
{
canvas : document.createElement("canvas"), start : function()
{
this.canvas.width = 510;
this.canvas.height = 280;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(gameUpdate, 20);
window.addEventListener("keydown", function (e)
{
gameArea.keys = (gameArea.keys || []);
gameArea.keys[e.keyCode] = true;
}, true)
window.addEventListener("keyup", function (e)
{
gameArea.keys[e.keyCode] = false;
}, true)
},
clear : function()
{
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop : function()
{
clearInterval(this.interval);
},
keyboard: function() {
if (this.keys) {
if (this.keys[37]) {gamePieceBorder.speedX = gamePieceRed.speedX = -2;}
else if (this.keys[39]) {gamePieceBorder.speedX = gamePieceRed.speedX = 2;}
else {gamePieceBorder.speedX = gamePieceRed.speedX = 0;}
if (this.keys[38]) {gamePieceBorder.speedY = gamePieceRed.speedY = -2;}
else if (this.keys[40]) {gamePieceBorder.speedY = gamePieceRed.speedY = 2;}
else {gamePieceBorder.speedY = gamePieceRed.speedY = 0;}
}
}
}
//-----------------------------------------
//-----------------------------------------Game component
function component(width, height, color, x, y)
{
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.speedX = 0;
this.speedY = 0;
this.update = function()
{
ctx = gameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height)
}
this.move = function()
{
this.x += this.speedX;
this.y += this.speedY;
}
this.crashGame = function(obj)
{
var left = this.x;
var right = this.x + (this.width);
var top = this.y;
var bottom = this.y + (this.height);
var otherLeft = obj.x;
var otherRight = obj.x + (obj.width);
var otherTop = obj.y;
var otherBottom = obj.y + (obj.height);
var crash = true;
if (bottom < otherTop || top > otherBottom || right < otherLeft || left > otherRight)
{
crash = false;
}
return crash;
}
}
//-----------------------------------------
//-----------------------------------------Game area updater
function gameUpdate()
{
if(gamePieceBorder.crashGame(obstacle) || gamePieceRed.crashGame(obstacle))
{
gameArea.stop();
}
else
{
gameArea.clear();
obstacle.update();
gameArea.keyboard();
gamePieceBorder.move();
gamePieceBorder.update();
gamePieceRed.move();
gamePieceRed.update();
}
}
//-----------------------------------------
<html>
<style>
canvas
{
border: 1px solid #d3d3d3;
background-image: url("https://ak0.picdn.net/shutterstock/videos/22492090/thumb/1.jpg");
}
</style>
<body onload = "startGame()">
</body>
</html>

cannot read property of undefined javascript and OOP

I have an object (a function) called 'Game' which has a prototype method called 'gameLoop.' I need this loop to be called in an interval, so I attempt to do this:
setInterval(game.gameLoop,setIntervalAmount);
but receive a "TypeError: Cannot read property 'clearRect' of undefined(…)"
Here is the prototype method:
Game.prototype.gameLoop = function()
{
this.context.clearRect(0,0,this.canvas.width, this.canvas.height);
this.context.save();
this.context.translate(this.canvas.width/2, this.canvas.height/2);
this.context.scale(this.camera.scale,this.camera.scale);
this.context.rotate(this.camera.rotate);
this.context.translate(this.camera.x,this.camera.y);
for(var i=0;i<this.objects.length;i++)
{
this.objects[i].updateSprite();
this.objects[i].drawSprite(this.context);
}
this.context.restore();
}
I am still having difficulty understanding Object Oriented Programming in Javascript. I had a working version where the function was just a regular function and I passed in a game object. Any ideas?
By the way, here is some additional code that may be helpful.
function Sprite(imgg,w,h)
{
this.img = imgg;
this.x = 350;//Math.random()*700;
this.y = 350;//Math.random()*700;
this.vx = 0;//Math.random()*8-4;
this.vy = 0;//Math.random()*8-4;
this.width = w;
this.height = h;
this.rotatespeed = 0.01;
this.rotate = 40;
}
Sprite.prototype.drawSprite = function(ctx)
{
ctx.save();
ctx.translate(this.x,this.y);
ctx.rotate(this.rotate);
ctx.drawImage(this.img,0,0,this.img.width,this.img.height,-this.width/2,-this.height/2,this.width,this.height);
ctx.restore();
}
Sprite.prototype.updateSprite = function()
{
this.x += this.vx;
this.y += this.vy;
this.rotate += this.rotatespeed;
if(this.x > 700)
this.vx = -this.vx;
if(this.x < 0)
this.vx = -this.vy;
if(this.y > 700)
this.vy = -this.vy;
if(this.y < 0)
this.vy = -this.vy;
}
Sprite.prototype.mouseEventListener = function(evt, type)
{
console.log("Hello");
}
//------------------------------------------
//GLOBAL VARIALBES
var setIntervalAmount = 30;
var scrollAmount = 0.5;
var game;
function Game()
{
this.camera = new Object();
this.camera.x = -350;
this.camera.y = -350;
this.camera.scale = 1;
this.camera.rotate = 0;
this.canvas = document.createElement("canvas");
document.body.appendChild(this.canvas);
this.canvas.id="mycanvas";
this.canvas.width = 700;
this.canvas.height = 700;
this.context = this.canvas.getContext("2d");
var ctx = this.context;
ctx.canvas.addEventListener('mousemove', function(event){
var mouseX = event.clientX - ctx.canvas.offsetLeft;
var mouseY = event.clientY - ctx.canvas.offsetTop;
var canvasX = mouseX * ctx.canvas.width / ctx.canvas.clientWidth;
var canvasY = mouseY * ctx.canvas.height / ctx.canvas.clientHeight;
//console.log(canvasX+" | "+canvasY);
});
this.objects = new Array();
}
Game.prototype.handleMouse = function(evt,type)
{
for(var i=0;i<this.objects.length;i++)
{
this.objects[i].mouseEventListener(evt,type);
}
};
Game.prototype.gameLoop = function()
{
this.context.clearRect(0,0,this.canvas.width, this.canvas.height);
this.context.save();
this.context.translate(this.canvas.width/2, this.canvas.height/2);
this.context.scale(this.camera.scale,this.camera.scale);
this.context.rotate(this.camera.rotate);
this.context.translate(this.camera.x,this.camera.y);
for(var i=0;i<this.objects.length;i++)
{
this.objects[i].updateSprite();
this.objects[i].drawSprite(this.context);
}
this.context.restore();
}
/*Game.prototype.drawGame = function()
{
var gameLoop = setInterval(function(){
this.context.clearRect(0,0,this.canvas.width, this.canvas.height);
this.context.save();
this.context.translate(this.canvas.width/2, this.canvas.height/2);
this.context.scale(this.camera.scale,this.camera.scale);
this.context.rotate(this.camera.rotate);
this.context.translate(this.camera.x,this.camera.y);
for(var i=0;i<this.objects.length;i++)
{
this.objects[i].updateSprite();
this.objects[i].drawSprite(this.context);
}
this.context.restore();
},setIntervalAmount);
}*/
function mouseWheelListener()
{
var evt = window.event;
console.log(evt.wheelDelta);
if(evt.wheelDelta < 0)
game.camera.scale /= (1+scrollAmount);
else
game.camera.scale *= (1+scrollAmount);
}
function mouseDownListener()
{
var evt = window.event;
var type = "down"
game.handleMouse(evt,type);
}
function mouseUpListener()
{
var evt = window.event;
var type = "up"
game.handleMouse(evt,type);
}
function mouseMoveListener()
{
var evt = window.event;
var type = "move"
game.handleMouse(evt,type);
}
//------------------
window.addEventListener('load',function(event){startgame();});
var dog = new Image();
dog.src = "grid.gif";
function startgame()
{
game = new Game();
for(var i=0;i<1;i++)
game.objects.push(new Sprite(dog,250,250));
setInterval(game.gameLoop,setIntervalAmount);
document.getElementById("mycanvas").addEventListener("wheel", mouseWheelListener);
document.getElementById("mycanvas").addEventListener("mousedown", mouseDownListener);
document.getElementById("mycanvas").addEventListener("mouseup", mouseUpListener);
document.getElementById("mycanvas").addEventListener("mousemove", mouseMoveListener);
}
Only issue, with your code is the context on which you are executing the gameloop method.
usually setInterval, setTimeout functions are executed under the global / window context. Hence, if you specify this inside the method, you are technically referring to global context, even though you are executing it on an object.
So, just to make sure you don't run into issues, always have a method as a first argument to setInterval, that would execute the necessary functions, instead of a method reference, something like
setInterval(function(){/*
game.gameLoop()
*/}, 1000);
This way you are executing the setInterval function in the global context but you are calling a method on game object explicitly.
function Sprite(imgg, w, h) {
this.img = imgg;
this.x = 350; //Math.random()*700;
this.y = 350; //Math.random()*700;
this.vx = 0; //Math.random()*8-4;
this.vy = 0; //Math.random()*8-4;
this.width = w;
this.height = h;
this.rotatespeed = 0.01;
this.rotate = 40;
}
Sprite.prototype.drawSprite = function(ctx) {
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.rotate);
ctx.drawImage(this.img, 0, 0, this.img.width, this.img.height, -this.width / 2, -this.height / 2, this.width, this.height);
ctx.restore();
}
Sprite.prototype.updateSprite = function() {
this.x += this.vx;
this.y += this.vy;
this.rotate += this.rotatespeed;
if (this.x > 700)
this.vx = -this.vx;
if (this.x < 0)
this.vx = -this.vy;
if (this.y > 700)
this.vy = -this.vy;
if (this.y < 0)
this.vy = -this.vy;
}
Sprite.prototype.mouseEventListener = function(evt, type) {
//console.log("Hello");
}
//------------------------------------------
////GLOBAL VARIALBES
var setIntervalAmount = 200;
var scrollAmount = 0.5;
var game;
function Game() {
this.camera = new Object();
this.camera.x = -350;
this.camera.y = -350;
this.camera.scale = 1;
this.camera.rotate = 0;
this.canvas = document.createElement("canvas");
document.body.appendChild(this.canvas);
this.canvas.id = "mycanvas";
this.canvas.width = 700;
this.canvas.height = 700;
this.context = this.canvas.getContext("2d");
var ctx = this.context;
ctx.canvas.addEventListener('mousemove', function(event) {
var mouseX = event.clientX - ctx.canvas.offsetLeft;
var mouseY = event.clientY - ctx.canvas.offsetTop;
var canvasX = mouseX * ctx.canvas.width / ctx.canvas.clientWidth;
var canvasY = mouseY * ctx.canvas.height / ctx.canvas.clientHeight;
//console.log(canvasX+" | "+canvasY);
});
this.objects = new Array();
}
Game.prototype.handleMouse = function(evt, type) {
for (var i = 0; i < this.objects.length; i++) {
this.objects[i].mouseEventListener(evt, type);
}
};
Game.prototype.gameLoop = function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.context.save();
this.context.translate(this.canvas.width / 2, this.canvas.height / 2);
this.context.scale(this.camera.scale, this.camera.scale);
this.context.rotate(this.camera.rotate);
this.context.translate(this.camera.x, this.camera.y);
for (var i = 0; i < this.objects.length; i++) {
this.objects[i].updateSprite();
this.objects[i].drawSprite(this.context);
}
this.context.restore();
}
/*Game.prototype.drawGame = function()
{
var gameLoop = setInterval(function(){
this.context.clearRect(0,0,this.canvas.width, this.canvas.height);
this.context.save();
this.context.translate(this.canvas.width/2, this.canvas.height/2);
this.context.scale(this.camera.scale,this.camera.scale);
this.context.rotate(this.camera.rotate);
this.context.translate(this.camera.x,this.camera.y);
for(var i=0;i<this.objects.length;i++)
{
this.objects[i].updateSprite();
this.objects[i].drawSprite(this.context);
}
this.context.restore();
},setIntervalAmount);
}*/
function mouseWheelListener() {
var evt = window.event;
console.log(evt.wheelDelta);
if (evt.wheelDelta < 0)
game.camera.scale /= (1 + scrollAmount);
else
game.camera.scale *= (1 + scrollAmount);
}
function mouseDownListener() {
var evt = window.event;
var type = "down"
game.handleMouse(evt, type);
}
function mouseUpListener() {
var evt = window.event;
var type = "up"
game.handleMouse(evt, type);
}
function mouseMoveListener() {
var evt = window.event;
var type = "move"
game.handleMouse(evt, type);
}
//------------------
window.addEventListener('load', function(event) {
startgame();
});
var dog = new Image();
dog.src = "https://i.stack.imgur.com/W0mIA.png";
function startgame() {
game = new Game();
for (var i = 0; i < 1; i++)
game.objects.push(new Sprite(dog, 250, 250));
setInterval(function() {
game.gameLoop();
}, setIntervalAmount);
document.getElementById("mycanvas").addEventListener("wheel", mouseWheelListener);
document.getElementById("mycanvas").addEventListener("mousedown", mouseDownListener);
document.getElementById("mycanvas").addEventListener("mouseup", mouseUpListener);
document.getElementById("mycanvas").addEventListener("mousemove", mouseMoveListener);
}
setInterval will call game.gameloop at the global scope which means the value of this inside the function is not what you expect it to be. This can be fixed by binding the function to the desired object.
E.g. change setInterval(game.gameLoop,setIntervalAmount); to setInterval(game.gameLoop.bind(game),setIntervalAmount);.
This example from MDN may provide some clarity for your code's current behaviour:
this.x = 9;
var module = {
x: 81,
getX: function() { return this.x; }
};
module.getX(); // 81
var retrieveX = module.getX;
retrieveX();
// returns 9 - The function gets invoked at the global scope
// Create a new function with 'this' bound to module
// New programmers might confuse the
// global var x with module's property x
var boundGetX = retrieveX.bind(module);
boundGetX(); // 81

Processing js jump system

I`m trying to make a jump system in processing.js and its done, but not quite what I wanted. The thing is that like this, the jump height depends on how long the key is pressed. What I wanted is the same height regardless how long the key is pressed.
Here is my code:
var keys = [];
void keyPressed() {
keys[keyCode] = true;
};
void keyReleased() {
keys[keyCode] = false;
};
var Player = function(x, y) {
this.x = x;
this.y = y;
this.g = 0;
this.vel = 2;
this.jumpForce = 7;
this.jump = false;
};
Player.prototype.draw = function() {
fill(255,0,0);
noStroke();
rect(this.x, this.y, 20, 20);
};
Player.prototype.move = function() {
if(this.y < ground.y) {
this.y += this.g;
this.g += 0.5;
this.jump = false;
}
if(keys[RIGHT]) {
this.x += this.vel;
}
if(keys[LEFT]) {
this.x -= this.vel;
}
//preparing to jump
if(keys[UP] && !this.jump) {
this.jump = true;
}
// if jump is true, than the ball jumps... after, the gravity takes place pulling the ball down...
if(this.jump) {
this.y -= this.jumpForce;
}
};
Player.prototype.checkHits = function() {
if(this.y+20 > ground.y) {
this.g = 0;
this.y = ground.y-20;
jump = false;
}
};
Var Ground = function(x, y, label) {
this.x = x;
this.y = y;this.label = label;
};
Ground.prototype.draw = function() {
fill(0);
rect(0, 580, width, 20);
};
var player = new Player(width/2, height/2);
var ground = new Ground(0, 580, "g");
void draw() {
background(255,255,255);
player.draw();
player.move();
player.checkHits();
ground.draw();
}
Any help would be aprreciated.
What are you doing here is like: "If this(the Player) isn't touching the ground then, if (in addition) key UP is pressed, jump!". So it will allow the player jumping even if he is in the air... increasing the jump height
You should do something like: "if player is touching the ground allow to jump (if key UP pressed), otherwise you are already jumping!".
Something like this:
if(this.y < ground.y) {
this.y += this.g;
this.g += 0.5;
this.jump = true;
}
else{
this.jump = false;
}
if(keys[UP] && !this.jump) {
this.jump = true;
this.y -= this.jumpForce;
}

Javascript - Creating multiple objects with the same parameter

I'm trying to create multiple "bullets" in a shooting game.
For some reason I can only create one, I assume its because I am not properly creating more than one bullet object.
Below is my code I've used to produce the shooting feature. Can someone point me in the right direction on how I can recreate multiple bullets onclick?
bullet = {
x: null,
y: null,
width: 10,
height: 10,
direction: null,
update: function(){
if(this.direction == null){
if(lastKeyPress == null){
lastKeyPress = up;
}
this.direction = lastKeyPress;
}
if(this.direction == up){ this.y -=7; }
if(this.direction == down){ this.y +=7; }
if(this.direction == left){ this.x -=7; }
if(this.direction == right){ this.x +=7; }
},
draw: function() {
if(this.x == null){
this.x = player.x + (player.width/4);
}
if(this.y == null){
this.y = player.y + (player.height/4);
}
cContext.fillRect(this.x, this.y, this.width, this.height);
}
}
function main(){
canvas = document.getElementById("mainCanvas");
cContext = canvas.getContext("2d");
keystate = {};
document.addEventListener("keydown", function(evt) {
keystate[evt.keyCode] = true;
});
document.addEventListener("keyup", function(evt) {
delete keystate[evt.keyCode];
});
document.addEventListener("click", function(evt) {
bullets[bulletNum] = bullet;
bullets[bulletNum].draw();
bulletNum++;
});
init();
var loop = function(){
update();
draw();
window.requestAnimationFrame(loop, canvas);
}
window.requestAnimationFrame(loop, canvas);
}
function update() {
for (i = 0; i < bullets.length; i++) {
bullets[i].update();
}
player.update();
ai.update();
}
function draw() {
cContext.clearRect(0, 0, WIDTH, HEIGHT);
cContext.save();
for (i = 0; i < bullets.length; i++) {
bullets[i].draw();
}
player.draw();
ai.draw();
cContext.restore();
}
The issue is that once you shoot one bullet you cannot shoot after anymore.
I know there is alot of code here, any help would be fantastic.
You want to use the Prototype Pattern:
var Bullet = function() {
this.x = null;
this.y = null;
this.width = 10;
this.height = 10;
this.direction = null;
};
Bullet.prototype.update = function() {...};
Bullet.prototype.draw = function() {...};
var bullet = new Bullet();
Another way to define objects in javascript is using prototype eg:
function Person(name){
this.name = name;
}
Person.prototype.sayHello = function(){
var res = "Hello i am "+ this.name;
return res;
}
var jhon = new Person('Jhon');
var rose = new Person('Rose');
document.getElementById('jhon').innerHTML = jhon.sayHello();
document.getElementById('rose').innerHTML = rose.sayHello();
<html>
<head>
<title>
</title>
</head>
<body>
<h1 id="jhon"></h1>
<h1 id="rose" ></h1>
</body>
</html>

Categories

Resources