これがフィドルです
これは動作します
これはしません
申し訳ありませんが、できるだけ多くのコードを含めて、テストをできるだけ近づけたいと思っていました。
2つ目は、オブジェクトを使用してx値とy値を保持することです。最初のものはそうではありません。
これはおそらく関数バインディングの問題ですが、完全にはわかりません。
私はこのコードを持っています:
(function createClouds() {
var Cloud = Class.extend({
size: 0,
alpha: 0,
x: 0,
y: 0,
pos: {
x: 0,
y: 0
},
init: function (x, y, size, alpha) {
this.x = x;
this.y = y;
this.size = size;
this.alpha = alpha;
console.log(this.x) // this prints a random number. all good
},
update: function (time) {
},
draw: function (ctx) {
ctx.fillStyle = 'rgba(255, 255, 255, ' + this.alpha + ')';
ctx.beginPath();
ctx.fillRect(this.x, this.y, this.size, this.size);
ctx.closePath();
ctx.fill();
}
});
sg.Cloud = Cloud;
})();
次に、基本的に、キャンバス上のランダムなポイントを使用してこのオブジェクトを作成しています。
for (var i = 0; i < 20; i++) {
var x = sg.util.getRandomInt(0, sg.currentGame.width);
var y = sg.util.getRandomInt(0, sg.currentGame.height - 260);
var size = sg.util.getRandomInt(20, 200);
var alpha = sg.util.getRandomNumber(.1, .6);
sg.createEntity(new sg.Cloud(x, y, size, alpha));
}
sg.createEntityは、このエンティティを配列に追加します。
次に、メソッドを呼び出します。
for (var i = 0; i < sg.entities.length; i++) {
sg.entities[i].draw(this.context);
}
これですべてのエンティティが描画されます。
上記は問題なく動作します。ランダムなポイントを獲得します。
これを変更すると。
(function createClouds() {
var Cloud = Class.extend({
size: 0,
alpha: 0,
x: 0,
y: 0,
pos: {
x: 0,
y: 0
},
init: function (x, y, size, alpha) {
this.pos.x = x;
this.pos.y = y;
this.size = size;
this.alpha = alpha;
console.log(this.pos.x) //this prints a random number;
console.log(this.pos) //inspecting this object shows same points.
},
update: function (time) {
},
draw: function (ctx) {
ctx.fillStyle = 'rgba(255, 255, 255, ' + this.alpha + ')';
ctx.beginPath();
ctx.fillRect(this.pos.x, this.pos.y, this.size, this.size);
ctx.closePath();
ctx.fill();
}
});
sg.Cloud = Cloud;
})();