animation

This commit is contained in:
James Turk 2024-07-09 03:14:22 -05:00
parent 2356cf43d7
commit cf054b01d9
5 changed files with 72 additions and 6 deletions

View File

@ -12,6 +12,7 @@ export class Drawable {
this._strokeWeight = parent ? parent._strokeWeight : null;
this._z_index = parent ? parent._z_index : null;
this._posVec = new Vector2(0, 0);
this._animations = [];
if (this._parent) {
this._parent.addChild(this);
}
@ -26,8 +27,16 @@ export class Drawable {
throw new Error("draw() must be implemented on child class");
}
// do nothing by default
update() {}
animate(setter, func, args) {
this._animations.push({ setter, func, args });
return this;
}
update(t) {
for (let anim of this._animations) {
this[anim.setter](anim.func(t), anim.args);
}
}
// setters

View File

@ -33,6 +33,10 @@ export class Vector2 {
);
}
get magnitude() {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
static random(x, y) {
let theta = Random.radians();
// if neither specified, use (1, 1)

View File

@ -206,11 +206,11 @@ export class Polygon extends Drawable {
point(vector, to_modify = null) {
if (to_modify !== null) {
self._points[to_modify] = vector;
this._points[to_modify] = vector;
} else {
self._points.push(point);
this._points.push(point);
}
return self;
return this;
}
// TODO
// contains(x, y) {

View File

@ -9,6 +9,7 @@ export class World {
this.targetFrameRate = 60;
this.stepSize = 1000 / this.targetFrameRate;
this.lastTick = this.timer.time();
this.numTicks = 0;
}
bindCanvas(id) {
@ -39,8 +40,9 @@ export class World {
}
tick() {
this.numTicks++;
for (let d of this.drawables) {
d.update();
d.update(this.numTicks);
}
}

51
examples/clock.html Normal file
View File

@ -0,0 +1,51 @@
<html>
<head> </head>
<body>
<canvas id="mainCanvas" width="500" height="500"></canvas>
<script type="module">
import {
artworld,
Color,
Pico8,
Group,
Rect,
Random,
Vector2,
Line,
Circle,
degToRad,
} from "../artworld/index.js";
artworld.bindCanvas("mainCanvas");
window.artworld = artworld;
function colorFunc(t) {
return [Pico8.RED, Pico8.ORANGE, Pico8.GREEN, Pico8.BLUE][
Math.floor(t / 60) % 4
];
}
function sizeFuncFactory(minSize, factor) {
return (t) => Math.sin(t / 100) * factor + minSize;
}
function timeAngle(t) {
return (t / 6000) * Math.PI * 2;
}
let g = new Group().pos(new Vector2(250, 250));
new Circle(g)
.fill(Pico8.BLACK)
.z(1)
.animate("radius", sizeFuncFactory(200, 50));
new Circle(g)
.z(10)
.animate("fill", colorFunc)
.animate("radius", sizeFuncFactory(190, 50));
new Circle(g).radius(20).fill(Pico8.BLACK).z(50);
new Line(g).to(Vector2.polar(200, 0)).z(100).animate("angle", timeAngle);
artworld.loopStep();
</script>
</body>
</html>