xxxxxxxxxx
47
let sprite, sPose ;
function setup() {
createCanvas(200, 200);
sprite = new Sprite(loadImage("Christmas_Snowman_Red.png"));
sprite = new Sprite(loadImage("avatar.png"));
sPose = 0;
noSmooth();
textSize(18);
textAlign(LEFT,TOP);
}
function draw() {
background(204);
sprite.draw();
text(sprite.x+","+sprite.y,5,5);
}
function keyPressed() {
if (keyCode === LEFT_ARROW) sprite.o = 3;
else if (keyCode === RIGHT_ARROW) sprite.o = 9;
else if (keyCode === UP_ARROW) sprite.o = 6;
else if (keyCode === DOWN_ARROW) sprite.o = 0;
}
class Sprite {
constructor(img) {
this.img = img;
this.x = width / 2;
this.y = height / 2;
this.o = 0;
this.dx = [0, -5, 0, 5];
this.dy = [5, 0, -5, 0];
}
draw() {
if ((frameCount % 2 == 0) && (keyIsPressed === true)) {
sPose = (sPose + 1) % 3;
this.x += this.dx[this.o / 3];
this.y += this.dy[this.o / 3];
this.y = constrain(this.y, 30, height - 30);
this.x = constrain(this.x, 30, width - 30);
}
imageMode(CENTER);
image(this.img.get(32 * (this.o + sPose), 0, 32, 64), this.x, this.y, 64, 128);
}
}