1

I'm working on a simple 2d game in JS using canvs.

The game consists of a knight who runs around to kill goblins, the goblin once touched, resets to a rangom location. I want to leave bloodsplatters for every goblin killed.

Currently, before I redraw the canvas, I use the previous X and Y co-ordinates from where the goblin died to paint my blood splatter image.

I want to do it for all goblins though. In a traditional language like Java, I would define a type, for example "blood" with two properties, X and Y.

I'd then create a new instance of this type each round using the goblins current co-ords and then add this type to an array, I'd loop and print all the objects in this array then.

I'm quite new to JS and since it's a functional language, things are a bit different. How exactly would I define a type like this that I could "new" into an array every iteration of the game?

var blood = {
    x: 0,
    y: 0        
};

Here's the current blood object I have

Eogcloud
  • 1,335
  • 4
  • 19
  • 44

1 Answers1

1

You create "classes" in Javascript as functions. Using this.x inside the function is like creating a member variable named x:

var Blood = function() {
    this.x = 0;
    this.y = 0;
}
var blood = new Blood()
console.log(blood.x);

These aren't classes or types in the sense of OO languages like Java, just a way of mimicking them by using Javascript's scoping rules.

So far there isn't really much useful here -- a simple object map would work just as well. But this approach may be useful if you need more logic in the Blood "class", like member functions, etc. You create those by modifying the object's prototype:

Blood.prototype.createSplatter = function() {
    return [this.x-1, this.y+1]; // (idk, however you create a splatter)
};
blood.createSplatter();

(Fiddle)

For more details on Javascript classes, I suggest taking a look at CoffeeScript syntax (scroll down to "Classes, Inheritance, and Super"). They have some side-by-side examples of classes in the simplified CS syntax, and the JS translation.

McGarnagle
  • 101,349
  • 31
  • 229
  • 260
  • because you can't efficiently add a `.splatter` method to the object returned by `createBlood`? ;-) – Alnitak Oct 16 '13 at 17:55
  • @Alnitak but then `.splatter` wouldn't be shared across instances of the object ... – McGarnagle Oct 16 '13 at 18:03
  • that was my point - if it's on the prototype it's shared, but if you `return {x: , y: , splatter: function(...) }` it wouldn't be. – Alnitak Oct 16 '13 at 18:05