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

4

1 回答 1

1

您在 Javascript 中将“类”创建为函数。this.x在函数内部使用就像创建一个名为的成员变量x

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

这些不是像 Java 这样的面向对象语言意义上的类或类型,只是通过使用 Javascript 的范围规则来模仿它们的一种方式。

到目前为止,这里并没有太多用处——一个简单的对象映射也可以。但是,如果您在 Blood“类”中需要更多逻辑,例如成员函数等,这种方法可能会很有用。您可以通过修改对象的原型来创建它们:

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

(小提琴)

有关 Javascript 类的更多详细信息,我建议查看CoffeeScript 语法(向下滚动到“类、继承和超级”)。他们有一些简化的 CS 语法和 JS 翻译中的类的并排示例。

于 2013-10-16T17:51:05.057 回答