今回からは,
クラスでつくった点を放物線状に落とす
第24回
今回のアニメーションも,
まず,
- プロパティ
- x, y:オブジェクトの現在のxy座標。
- _oldX, _oldY:オブジェクトの前のxy座標。
- メソッド
- VerletPoint(x, y):コンストラクタ。xy座標値を引数に渡す。
- update():オブジェクトの座標のプロパティ値を,
速度にもとづいて更新する。 - constrain(rect):引数にRectangleオブジェクトを受取って,
オブジェクトの座標をその矩形領域内に収める。 - getVelocity():オブジェクトの新旧xy座標から速度を求めて返す。
- render(graphics):引数に受取ったGraphicsオブジェクトに,
オブジェクトの現行xy座標の点を描く。 - addCoordinates(x, y):引数に受取ったxyピクセル値を,
オブジェクトのxy座標に加える。
点のクラス
コンストラクタVerletPoint()の引数にはインスタンスのxy座標値を渡して,
update()メソッドは,
constrain()メソッドは,
render()メソッドは,
コード1 点を定めるクラスVerletPoint
function VerletPoint(x, y) {
this.x = this._oldX = x;
this.y = this._oldY = y;
}
VerletPoint.prototype.update = function() {
var tempX = this.x;
var tempY = this.y;
var velocity = this.getVelocity();
this.addCoordinates(velocity.x, velocity.y);
this._oldX = tempX;
this._oldY = tempY;
};
VerletPoint.prototype.constrain = function(rect) {
var left = rect.x;
var right = left + rect.width;
var top = rect.y;
var bottom = top + rect.height;
if (this.x < left) {
this.x = left;
} else if (this.x > right) {
this.x = right;
}
if (this.y < top) {
this.y = top;
} else if (this.y > bottom) {
this.y = bottom;
}
};
VerletPoint.prototype.getVelocity = function() {
var velocity = new createjs.Point(this.x - this._oldX, this.y - this._oldY);
return velocity;
};
VerletPoint.prototype.render = function(graphics) {
graphics.beginFill("black")
.drawCircle(this.x, this.y, 2.5)
.endFill();
};
VerletPoint.prototype.addCoordinates = function(x, y) {
this.x += x;
this.y += y;
};
このクラス
<body onLoad="initialize()">
<canvas id="myCanvas" width="400" height="300"></canvas>
</body>
初期化の関数
アニメーションのリスナー関数
点を動かす関数
コード2 点を放物線状に落とす
var stage;
var drawingGraphics;
var _point;
var _stageRect;
var velocityX = 5;
var velocityY = 0.25;
function initialize() {
var canvasElement = document.getElementById("myCanvas");
var shape = new createjs.Shape();
stage = new createjs.Stage(canvasElement);
stage.addChild(shape);
drawingGraphics = shape.graphics;
_stageRect = new createjs.Rectangle(
0,
0,
canvasElement.width,
canvasElement.height
);
_point = new VerletPoint(50, 50);
_point.x += velocityX;
createjs.Ticker.timingMode = createjs.Ticker.RAF;
createjs.Ticker.addEventListener("tick", draw);
}
function draw(eventObject) {
updatePoint();
drawingGraphics.clear();
_point.render(drawingGraphics);
stage.update();
}
function updatePoint() {
_point.y += velocityY;
_point.update();
_point.constrain(_stageRect);
}
実際の動きを確かめた方がよいので,
しかし,
アニメーションのリスナー関数
- ※1
- つまり,
点のオブジェクトの位置座標を動かすのは, 力つまり加速度を加えるのに等しい。ただ, 位置に足し込む値なので, 細かいことはいわず, 変数名には速度 (velocity) という語を用いた。