Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
</head>
<body>
<script>
var canvas = document.createElement("canvas");
var context = this.canvas.getContext("2d");
context.fillStyle = "black";
document.body.appendChild(this.canvas);
canvas.style = "border: 1px solid red;";
class Controller {
constructor(x, y, moves) {
this.x = x;
this.y = y;
this.moves = moves;
this.currentMoveIndex = 0;
}
currentMove() {
return(this.moves[this.currentMoveIndex]);
}
loadMove() {
if(this.currentMoveIndex > this.moves.length - 1) { this.stop(); return; }
this.moveIntervals = this.currentMove().intervals;
this.xDelta = this.currentMove().x - this.x;
this.yDelta = this.currentMove().y - this.y;
this.startingPosition = {x: this.x, y: this.y};
this.clock = 0;
}
step() {
if(this.currentMoveIndex > this.moves.length - 1) { return; }
this.clock += 1;
var movePercentCompleted = this.clock / this.moveIntervals;
var desiredPositionX = Math.round(this.startingPosition.x + (movePercentCompleted * this.xDelta));
if(desiredPositionX < this.x) { this.x += -1; }
if(desiredPositionX > this.x) { this.x += 1; }
var desiredPositionY = Math.round(this.startingPosition.y + (movePercentCompleted * this.yDelta));
if(desiredPositionY < this.y) { this.y += -1; }
if(desiredPositionY > this.y) { this.y += 1; }
context.fillRect( this.x, this.y, 1, 1 );
console.log(`Position: X${this.x} Y${this.y}`);
if(this.x === this.currentMove().x && this.y === this.currentMove().y) {
this.currentMoveIndex += 1;
this.loadMove();
}
}
start() {
this.loadMove();
this.timer = window.setInterval(this.step.bind(this), 1);
}
stop() {
window.clearInterval(this.timer);
}
}
window.onload = function() {
var controller = new Controller(0, 0, [
{x: 20, y: 20, intervals: 200},
{x: 100, y: 20, intervals: 200},
{x: 100, y: 100, intervals: 200},
{x: 80, y: 120, intervals: 200},
{x: 40, y: 120, intervals: 200},
{x: 20, y: 100, intervals: 200},
{x: 20, y: 20, intervals: 200}
]);
controller.start();
console.log("DONE");
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment