Skip to content

Commit

Permalink
tests: Add coroutine examples
Browse files Browse the repository at this point in the history
  • Loading branch information
eonarheim committed Jul 15, 2024
1 parent 321d9f6 commit 963ab8b
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
13 changes: 13 additions & 0 deletions sandbox/tests/coroutine/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Coroutine Animation Example</title>
</head>
<body>
<script src="../../lib/excalibur.js"></script>
<script src="./index.js"></script>
</body>
</html>
54 changes: 54 additions & 0 deletions sandbox/tests/coroutine/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
var game = new ex.Engine({
width: 600,
height: 400,
displayMode: ex.DisplayMode.FitScreenAndFill
});

var actor = new ex.Actor({
pos: ex.vec(300, 300),
width: 100,
height: 100,
color: ex.Color.Red
});

var fadeBy = (actor: ex.Actor, fadeChange: number, durationSeconds: number) => {
// coroutines start automatically
return ex.coroutine(function* () {
let duration = durationSeconds * 1000; // milliseconds
let fadeChangeRate = fadeChange / duration;
let targetOpacity = actor.graphics.opacity + fadeChange;
while (duration > 0) {
const elapsed = yield;
duration -= elapsed;
actor.graphics.opacity += fadeChangeRate * elapsed;
}
actor.graphics.opacity = targetOpacity;
});
};

var moveByVec = (actor: ex.Actor, change: ex.Vector, durationSeconds: number) => {
// coroutines start automatically
return ex.coroutine(function* () {
let duration = durationSeconds * 1000; // milliseconds
let rateOfChange = change.scale(1 / duration);
let dest = actor.pos.add(change);
while (duration > 0) {
const elapsed = yield;
duration -= elapsed;
actor.pos.addEqual(rateOfChange.scale(elapsed));
}
actor.pos = dest;
});
};

actor.onInitialize = async () => {
await moveByVec(actor, ex.vec(100, -100), 0.5);
await moveByVec(actor, ex.vec(-100, -100), 0.5);
await moveByVec(actor, ex.vec(-100, 100), 0.5);
await moveByVec(actor, ex.vec(100, 100), 0.5);
await fadeBy(actor, -1.0, 2);
};

game.currentScene.add(actor);

game.start();

0 comments on commit 963ab8b

Please sign in to comment.