イベントのお知らせ
12月20日,
前回の第17回
Shapeクラスを継承する3次元座標のクラス定義
早速,
JavaScriptの継承は他の言語と少し変わっている。継承したいクラス
// サブクラスのコンストラクタ関数の定義
function クラス名() {
// インスタンスの初期化
}
// スーパークラスの継承
クラス名.prototype = スーパークラスのオブジェクト;
今回,
function Ball3D(radius, color) {
this.initialize();
this.radius = radius;
this.color = color;
this.realX = 0;
this.realY = 0;
this.realZ = 0;
this.velocityX = 0;
this.velocityY = 0;
this.velocityZ = 0;
this.drawBall(radius, color);
}
Ball3D.prototype = new createjs.Shape();
Ball3D.prototype.move = function(gravity) {
this.realX += this.velocityX;
this.realY += this.velocityY;
this.velocityY += gravity;
};
Ball3D.prototype.drawBall = function(radius, color) {
this.graphics.beginFill(color)
.drawCircle(0, 0, radius);
};
前掲クラス
なお,
function animate(eventObject) {
var count = stage.getNumChildren() - 1;
for (var i = count; i > -1; i--) {
var newY = child.y + child.velocityY;
child.x += child.velocityX;
child.y = newY;
child.velocityY += 2;
}
}
3次元空間のボールのオブジェクトを100個つくって,
アニメーションは,
コード1 Shapeのサブクラスのオブジェクトを100個つくって2次元平面でランダムな向きに落とす
function Ball3D(radius, color) {
this.initialize();
this.radius = radius;
this.color = color;
this.realX = 0;
this.realY = 0;
this.realZ = 0;
this.velocityX = 0;
this.velocityY = 0;
this.velocityZ = 0;
this.drawBall(radius, color);
}
Ball3D.prototype = new createjs.Shape();
Ball3D.prototype.move = function(gravity) {
this.realX += this.velocityX;
this.realY += this.velocityY;
this.velocityY += gravity;
};
Ball3D.prototype.drawBall = function(radius, color) {
this.graphics.beginFill(color)
.drawCircle(0, 0, radius);
};
var stage;
var balls = [];
var numBalls = 100;
var stageWidth;
var centerX;
var centerY;
var gravity = 0.2;
function initialize() {
var canvasElement = document.getElementById("myCanvas");
stage = new createjs.Stage(canvasElement);
stageWidth = canvasElement.width;
centerX = stageWidth / 2;
centerY = canvasElement.height / 2;
for (var i = 0; i < numBalls; i++) {
var color = createjs.Graphics.getRGB(getRandom(0, 0xFFFFFF));
var ball = new Ball3D(3, color);
balls.push(ball);
ball.realY = -50;
ball.velocityX = getRandom(-3, 3);
ball.velocityY = getRandom(-6, 0);
stage.addChild(ball);
}
createjs.Ticker.addEventListener("tick", animate);
}
function animate(eventObject) {
for (var i = balls.length - 1; i > -1; i--) {
var ball = balls[i];
move(ball);
}
stage.update();
}
function move(ball) {
ball.move(gravity);
ball.x = centerX + ball.realX;
ball.y = centerY + ball.realY;
}
function getRandom(min, max) {
var randomNumber = Math.random() * (max - min) + min;
return randomNumber;
}
これで,
- ※1
厳密には,
もちろんFunction. prototype プロパティの参照は,スーパークラスのオブジェクトで上書きされる。そして実は, すべてのオブジェクトにはObject.__ proto__ というプロパティが備わり,スーパークラスのプロトタイプオブジェクトはそのプロパティをたどって参照される (MDN 「Function. prototype」 の 「プロパティ」 の項参照)。 なお,
Function. prototype プロパティの上書きになるので,スーパークラスのオブジェクトは, サブクラスのプロトタイプオブジェクトにメソッドを定める前に代入しなければならない。