PACMAN P5js - JSFiddle
by Dominic Myers
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.22/p5.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/sakura.css/css/sakura.css">
<p>
Link to trinket.io workings <a href="https://trinket.io/html/8d0a0b3be4" target="_blank">here</a>.
</p>
JavaScript
"use strict";
class Pacman {
constructor(r, x, y) {
this.r = r;
this.x = x;
this.y = y;
this.speed = [0, 0];
this.jawWidth = 45;
this.opening = false;
this.increment = 4.5;
}
draw(){
fill('#FFFF00');
noStroke();
if(this.jawWidth === 0){
ellipse(this.x, this.y, this.r * 2, this.r * 2);
} else {
push();
translate(this.x, this.y);
if(this.speed.every((e, i) => e === [0,-1][i])){
rotate(270);
}
if(this.speed.every((e, i) => e === [0,1][i])){
rotate(90);
}
if(this.speed.every((e, i) => e === [-1,0][i])){
rotate(180);
}
arc(0, 0, this.r * 2, this.r * 2, this.jawWidth, -Math.abs(this.jawWidth), PIE);
pop();
}
this.update();
}
update(){
if(this.jawWidth === 0){
this.opening = false;
}
if(this.jawWidth === 45){
this.opening = true;
}
if(this.opening){
this.jawWidth -= this.increment;
}else{
this.jawWidth += this.increment;
}
this.x = this.x + this.speed[0];
this.y = this.y + this.speed[1];
}
dir(x, y) {
this.speed = [x, y];
}
}
let pacman = null;
function setup() {
createCanvas(600, 400);
angleMode(DEGREES);
frameRate(4);
pacman = new Pacman(40, 80, 80);
}
function draw() {
background(51);
pacman.draw();
}
function keyPressed() {
if (keyCode === UP_ARROW) {
pacman.dir(0, -1);
} else if (keyCode === DOWN_ARROW) {
pacman.dir(0, 1);
} else if (keyCode === RIGHT_ARROW) {
pacman.dir(1, 0);
} else if (keyCode === LEFT_ARROW) {
pacman.dir(-1, 0);
}
}