After trying a couple different HTML5 frameworks, I've always found pure JS the most appealing. However, I am uncertain about the way I'm structuring it.
Currently, I have been declaring different objects as global variables as such:
var titlescreen = new Titlescreen();
var fps = new FPSTracker();
var input = new Input();
var background = new Background();
var shops = new Shops();
var chunkhandler = new ChunkHandler();
var explosionhandler = new ExplosionHandler();
var ui = new UI();
var world = new World();
var player = new Player();
var joystick = new Joystick();
My main problem with this is how I have them communicate with each other. For example, the Player
class accesses some of world
's functions by simply using it's name ( world.functionINeedToUse();
). Coming from a Java background, this gives me a very bad vibe as it depends on the declaration of this global variable with the specific name. Though I've found JS to be a more forgiving language, this still does not feel right. I haven't found any problems with it, so far.
Are there more effective ways to structure a game? What about the problem with player/world?
If I understood you, you are seeking a way to have an OOP pattern, aren't you? In JS, you are able to define classes with constructors and prototypes.
However, if you are looking for more powerful tools, you should glance at supersets such as CoffeeScript (Ruby/Python syntax) or TypeScript (C#/Java syntax).
I'm using prototypes to declare "classes" as you would call that in Java.
Here is an article that describes how to use them: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
Additionally I organize my scene as a tree-structure. So World
would be the root and Player
would be a child of World
. In that way I don't have them all as global variables anymore. The communication between the Shapes (World and Player) is done via associations between them.
I create the tree by using the composite pattern. So I have defined a Shape-prototype and a Composite-prototype that extends Shape and has a list of child-shapes. World
and Player
would then extend from Composite
and Shape
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.