I'm trying to create a simple game loop and trying to use OOP paradigm in JS. Here is my code:
HTML
<body onload="Game.OnLoad('gameField')" onkeydown="Game.KeyDown(event)">
<p id="info">1</p>
<p id="info2">2</p>
<canvas id="gameField"
width="896px"
height="717px"
class="game-field"
style="border: 4px solid aqua"
onclick="Game.MouseClick(event)"></canvas>
</body>
JavaScript
// class Timer
// version: 1
// only tick() functionality available
// right now
function Timer() {
var date = new Date();
var prevTick = 0;
var currTick = 0;
// update timer with tick
this.tick = function() {
prevTick = currTick;
currTick = date.getTime();
}
// get time between two ticks
this.getLastTickInterval = function() {
return currTick - prevTick;
}
}
// global object Game
// which handles game loop
// and provide interfaces for
var Game = new function() {
// variables:
this.canvas = 0;
var gameLoopId = 0;
this.timer = new Timer();
// events:
this.KeyDown = function(e) {}
// game loop:
this.Run = function() {
this.timer.tick();
this.Update(this.timer.getLastTickInterval());
this.Draw();
}
this.Update = function(dt) {
document.getElementById("info").innerHTML = dt;
}
this.Draw = function() {}
this.StopGameLoop = function() {
clearInterval(gameLoopId);
}
this.OnLoad = function(canvasName) {
this.canvas = document.getElementById(canvasName);
this.timer.tick();
// start game loop
setInterval(this.Run, 1000);
}
}
(Fiddle)
I'm trying to make Game class global. Other classes must be instantinated using new.
Classes Game and Timer are placed in different files called Game.js and Timer.js. When I run this code in Chrome I got an error in DevTools: "Uncaught TypeError: Cannot call method 'tick' of undefined" in Game.Run function at the line this.timer.tick();
So I wonder, what is the problem with my code? Thanks for reply.
Your problem is with the context. When you're calling tick this is window, not Game.
You can handle this, for example, by setting:
var self = this;
this.Run = function() {
self.timer.tick();
self.Update(self.timer.getLastTickInterval());
self.Draw();
}
Few things to consider in your code :
Concerning your issue, methode like setInterval or setTimeout loose the context. Easiest solution is to bind a context to the callback :
setInterval(this.Run.bind(this), 1000);
Secondly, avoid adding private methode inside an object function. In that case, every instance of Game will have its own set of functions (memory leak).
Prefer using prototypes :
function Game () {
this.canvas = null;
}
Game.prototype = {
init: function() {}
render: function () {}
};
Lastly, I see you redraw every seconds, which is ok. But if you want 60fps, you can use requestAnimationFrame for drawing oriented loops.
ps: just to be very nitpicking, functions' name should be camelCase so starting with lower case.
Related
I'm not sure what's wrong here, but testing in the chromium and firefox, I find that I'm doing it wrong with respect to removing an EventListener from an element in javascript.
The context is a canvas game. At first, there's a splash screen shown where you click to begin the game. After you click to begin, I want to remove the listener.
The main point of interest is the removeEventListener in the startGame function. It doesn't throw an error. And the code executes (I see the game starting message in the console and I can see that "this" is the Game instance). I'm totally confused why if I keep on clicking on the canvas runs startGame each time. The expected behavior is that clicking there does nothing once the EventListener is removed.
Help!
function Game(canvas) {
this.c = canvas;
this.ctx = this.c.getContext("2d");
this.c.width = CANVAS_WIDTH;
this.c.height = CANVAS_HEIGHT;
// Background image
this.bgReady = false;
this.bgImage = new Image();
this.bgImage.onload = function () {
window.g.bgReady = true;
};
this.bgImage.src = MAIN_BACKGROUND;
}
Game.prototype.setSplash = function() {
if (this.bgReady) {
this.ctx.drawImage(window.g.bgImage, 0, 0);
this.ctx.font="48px Helvetica";
this.ctx.textAlign = "center";
this.ctx.fillStyle="rgb(0,0,255)";
this.ctx.fillText("Click To Start",310,240);
document.getElementById("cnvs").addEventListener(
'click',this.startGame.bind(this),true);
} else {
// since setSplash is an early function
// wait a bit for the background image and then try again
setTimeout(this.setSplash.bind(this),100);
console.log("bgImage not ready...");
}
}
Game.prototype.startGame = function() {
console.log("game starting ...");
console.log(this);
// step 1, remove the click listener for this function
// why isn't this working?!
document.getElementById("cnvs").removeEventListener(
'click',this.startGame,true);
}
...
// other stuff ...
function initialize() {
// Get the canvas
var c = document.getElementById("cnvs");
// Create a game object
window.g = new Game(c);
// Set the splash page
g.setSplash();
}
window.onload=initialize;
Further info:
I also had a version where the non-working removal was written as:
this.c.removeEventListener('click',this.startGame,true);
Same behavior as the code referenced above.
EDIT: in reply to the first answer by mczepiel
I'm trying to implement your answer like this:
Typer.prototype.setSplash = function() {
if (this.bgReady) {
this.ctx.drawImage(window.t.bgImage, 0, 0);
this.ctx.font="48px Helvetica";
this.ctx.textAlign = "center";
this.ctx.fillStyle="rgb(0,0,255)";
this.ctx.fillText("Click To Start",310,240);
var boundFunction = this.startGame.bind(this);
document.getElementById("cnvs").addEventListener(
'click',boundFunction,true,boundFunction);
} else {
// since setSplash is an early function
// wait a bit for the background image and then try again
setTimeout(this.setSplash.bind(this),100);
console.log("bgImage not ready...");
}
}
Typer.prototype.startGame = function(boundFunction) {
console.log("game starting ...");
console.log(this); // strangely, now this is an Object rather
// than Game, it still has the properties of
// Game tho
// step 1, remove the click listener for this function
// still isn't working...
document.getElementById("cnvs").removeEventListener(
'click',boundFunction,true);
}
I think I understood your suggestion, but perhaps not. The code above still doesn't remove the listener. Any help appreciated.
You'll need to store a reference to the result of calling this.startGame.bind(this) and pass that same value to both addEventListener and removeEventListener
The remove call is expecting to remove the exact same object that was added as a listener.
Likely duplicate of removeEventListener is not working and others if you want to see the same issue in various flavors.
EDIT untested off-the-cuff suggestion:
Typer.prototype.setSplash = function() {
if (this.bgReady) {
// draw stuff
var canvasElement = document.getElementById("cnvs");
var dismissSplash = function (evt) {
canvasElement.removeEventListener('click', dismissSplash, true);
this.startGame();
}.bind(this);
canvasElement.addEventListener('click', dismissSplash, true);
} else {
// try to show splash later
}
}
Typer.prototype.startGame = function() {
// start game
}
[RESOLVED]
Was calling the newGame function from an event listener so this would then refer to the event caller
I'm having this annoying issue with JS at the moment, I'm creating a game where all the variables for a particular game are stored in the Game() class/function/object and have a GameManager which creates the initial game and has a function to create a new one.
The problem is, I cannot overwrite the initial game in the newGame function, here it is:
var GameManager = {};
GameManager.currentGame = null;
GameManager.init = function() {
this.newGame();
}
GameManager.newGame = function() {
this.currentGame = new Game();
}
GameManager.init();
After running the newGame function, the result:
GameManager.currentGame == the original game, NOT the new one.
To put things in a simpler form, I've used int's here:
var GameManager = {};
GameManager.currentGame = null;
GameManager.init = function() {
this.currentGame = 12;
}
GameManager.newGame = function() {
this.currentGame = 0;
}
GameManager.init();
After running the newGame function, the result:
GameManager.currentGame == 12 (NOT 0, as expected)
I have a feeling this is an obvious issue with object referencing or something similar, I'd appreciate all responses!
Thanks
I'm using code from a JSFiddle to implement a count up feature on my site. I like it because it allows me to target a number displayed in a specific div, and I don't need to specify that number in the javascript, which means I can use it on any page for any number I choose.
See the code here:
// basic class implementation
function myCounter() {
// privileged property for iteration
this.i = 0;
// privileged init method
this.init();
}
// defining init method
myCounter.prototype.init = function () {
// reassign this
var _this = this;
setInterval(function () {
// call this.countUp() using our new created variable.
// this has to be done as this would normally call something
// inside this function, so we have to pass it as own
// variable over
_this.countUp();
}, 500);
clearInterval(function () {
this.i ==
};
};
// defining the counter method
myCounter.prototype.countUp = function () {
this.i++;
document.getElementById('counter').innerHTML = this.i;
};
// create a new instance of our counter class
var counter = new myCounter();
The only problem is that it doesn't stop counting. I'd love to add some code for that myself, except I'm not familiar enough with javascript and have no idea where to start.
Is there a way to tell javascript to stop counting at the number specified in the targeted div?
Thanks so much!
// basic class implementation
function myCounter() {
// privileged property for iteration
this.i = 0;
// privileged init method
this.init();
}
// defining init method
myCounter.prototype.init = function () {
// reassign this
var _this = this;
this.timer = setInterval(function () {
// call this.countUp() using our new created variable.
// this has to be done as this would normally call something
// inside this function, so we have to pass it as own
// variable over
_this.countUp();
}, 500);
};
// defining the counter method
myCounter.prototype.countUp = function () {
this.i++;
document.getElementById('counter').innerHTML = this.i;
// stop the timer
if(this.i == 8){
clearInterval(this.timer)
}
};
// create a new instance of our counter class
var counter = new myCounter();
Hello this is my first attempt at trying to write a JavaScript application so I'm new to writing OOP code using it.
The following code runs without any errors in the console:
// Main file for the application
$(document).ready( function()
{
var app = new application;
setInterval( app.run, 50 );
});
function application()
{
var canvas = Raphael(10,0,400,400);
this.molecule = new molecule( new Vec2(50,50),new Vec2(1,0),canvas );
this.molecule.update(10);
this.run = function()
{
}
}
However, this piece of code does not work:
// Main file for the application
$(document).ready( function()
{
var app = new application;
setInterval( app.run, 50 );
});
function application()
{
var canvas = Raphael(10,0,400,400);
this.molecule = new molecule( new Vec2(50,50),new Vec2(1,0),canvas );
this.run = function()
{
this.molecule.update(10);
}
}
It gives the following error in the console:
Uncaught TypeError: Object function molecule( pos,vel,canvas )
{
this.radius = 5;
this.color = "red";
this.canvas = canvas;
this.pos = pos;
this.vel = vel;
this.circle = canvas.circle( this.pos.x,this.pos.y,this.radius );
this.circle.attr("fill", this.color );
} has no method 'update'
Here is the source file containing the molecule object.
// This 'class' handles a molecule, including movement and drawing.
function molecule( pos,vel,canvas )
{
this.radius = 5;
this.color = "red";
this.canvas = canvas;
this.pos = pos;
this.vel = vel;
this.circle = canvas.circle( this.pos.x,this.pos.y,this.radius );
this.circle.attr("fill", this.color );
}
// Updates the molecule
molecule.prototype.update = function( deltaTime )
{
this.pos += this.vel * deltaTime;
this.setPosition(this.pos);
}
// Accepts a Vec2
molecule.prototype.setPosition = function( pos )
{
this.circle.translate( pos.x-this.pos.x, pos.y-this.pos.y );
}
I'm sorry for the large amount of code I've posted, but I'm stumped why the first piece of code works while the second won't. Could anybody shed some light on it for me? Thanks a lot.
A common mistake, and it requires a good understanding of JavaScript to see what's happening here. The problem is this line:
setInterval( app.run, 50 );
This causes app.run to be called when the interval runs out without a proper this context. To ensure that run gets called with app as its this context, you need something like:
setInterval( function() {
app.run();
}, 50 );
or with the latest JavaScript (only in very modern browsers):
setInterval( app.run.bind(app), 50 );
The this context of a function in JavaScript is determined by how the function is called. Basically, it gets determined by what object it is called on. For example, in app.run(), the run method is called on app and it'll work as expected. However, in a slightly different scenario
var fn = app.run;
fn();
the function is called on no object and thus this will not be set, leading to unexpected results. This is exactly what's happening in your case. The solution is to make sure that you pass a function which can be called on any object, and make that function call run on the right object.
You've detached the run method from the app. Pass a function that keeps them together.
setTimeout(function() { app.run(); }, 50);
Now the value of this in .run() will be the app object.
Also, there's no need to make a new run method for every application() object. You can put run on the application.prototype.
function application() {
var canvas = Raphael(10,0,400,400);
this.molecule = new molecule( new Vec2(50,50),new Vec2(1,0),canvas );
this.molecule.update(10);
}
application.prototype.run = function() {
this.molecule.update(10);
}
Although if you did keep run in the constructor, you could then have it close over a variable that references the object, and so you could safely detach it.
function application() {
var canvas = Raphael(10,0,400,400);
this.molecule = new molecule( new Vec2(50,50),new Vec2(1,0),canvas );
this.molecule.update(10);
var self = this;
this.run = function() {
self.molecule.update(10);
}
}
setTimeout(app.run, 50)
I have always had trouble working with time events. Could someone please explain why A doesn't work and B does? The only difference is in A I put the event binding in a function. Don't worry about the function close, it has nothing to do with the question. When I test A, there is no js errors but timer is not cleared.
A ->
Test.Navigation = (function() {
var openTimer = null;
var closeTimer = null;
var addListeners = function() {
$('.hover_container').on('mousemove', function(e) {
clearTimeout(closeTimer);
});
$('.hover_container').on('mouseleave', function(e) {
// set the close timer
var container = this;
closeTimer = setTimeout(function() {
//has the mouse paused
close(container);
}, 750);
});
};
return {
init : function() {
addListeners();
}
};
})();
B ->
Test.Navigation = (function() {
var openTimer = null;
var closeTimer = null;
$('.hover_container').on('mousemove', function(e) {
clearTimeout(closeTimer);
});
$('.hover_container').on('mouseleave', function(e) {
// set the close timer
var container = this;
closeTimer = setTimeout(function() {
//has the mouse paused
close(container);
}, 750);
});
var addListeners = function() {
// nothing here
};
return {
init : function() {
addListeners();
}
};
})();
Edit: Please ignore the container part, it has nothing to dow ith the question it is simply part of the full code that I did not take out
A is binded before the object exists where the init is called. Because your return a new object. If you are using, 2 objects are created. 1 with the vars en binds. and 1 with the returns.
B is working because you create a function where the elements are initialized and use the right scope. A is not working because the bindings are on the wrong scope because your create 2 objects:
new Test.Navigation(); // Create 1 object
// Create second object.
return {
init : function() {
addListeners();
}
};
Youd better get a structure like this, then it should work aswell:
Test.Navigation = (function() {
// Private vars. Use underscore to make it easy for yourself so they are private.
var _openTimer = null,
_closeTimer = null;
$('.hover_container').on('mousemove', function(e) {
clearTimeout(_closeTimer );
});
$('.hover_container').on('mouseleave', function(e) {
// set the close timer,
// use $.proxy so you don't need to create a exta var for the container.
_closeTimer = setTimeout(
$.proxy(function() {
//has the mouse paused
close(this);
}, this)
, 750);
});
this.addListeners = function() {
// nothing here
};
this.init = function() {
this.addListeners();
}
// Always call the init?
this.init();
return this; // Return the new object Test.Navigation
})();
And use it like
var nav = new Test.Navigation();
nav.init();
Also as you can see I upgraded your code a bit. Using $.proxy, _ for private vars.
Your use of this is in the wrong scope for the first approach.
Try
var openTimer = null;
var closeTimer = null;
var self = this;
and then later
var container = self;
In your code for example A,
$('.hover_container').on('mouseleave', function(e) {
// set the close timer
var container = this;
this is actually referring to the current $('.hover_container') element.
Also, since setTimeout will wait before the previous setTimeout finishes to start again, you can get discrepancies. You may want to switch to setInterval because it will issue its callback at every interval set regardless of if the previous callback has completed.
My guess is that in the calling code, you have a statement new Test.Navigation() which, for B, addListeners is called at the time of new Test.Navigation(). In A, you return an object ref that calls an init function. Can you verify that init() is called?
I.e. in A, init() has to be called before the handlers are added. In B, the handlers are added everytime you instantiate Test.Navigation --- which, depending on the calling code, could be bad if you intend to instantiate more than one Test.Navigation() at a time.