// 定义人物对象
let character = {
x: 120, // 初始位置x轴坐标
y: 110, // 初始位置y轴坐标
speed: 2, // 移动速度
flipping: false, // 是否翻转贴图
// 贴图数组
walkLeft: [],
walkRight: [],
curFrame: 0, // 当前贴图帧
totalFrames: 4, // 总共的贴图帧数
// 加载贴图
loadImages: function() {
// 加载向左走的贴图
for (let i = 1; i <= this.totalFrames; i++) {
this.walkLeft.push(loadImage(`assets/walkleft${i}.png`));
}
// 加载向右走的贴图
for (let i = 1; i <= this.totalFrames; i++) {
this.walkRight.push(loadImage(`assets/walkright${i}.png`));
}
},
// 更新帧数
updateFrame: function() {
this.curFrame = (this.curFrame + 1) % this.totalFrames;
},
// 绘制当前帧的贴图
display: function() {
if (this.flipping) {
// 向右翻转绘图
push();
translate(this.x, this.y);
scale(-1.0, 1.0);
image(this.walkRight[this.curFrame], 0, 0);
pop();
} else {
// 向左绘图
image(this.walkLeft[this.curFrame], this.x, this.y);
}
},
// 移动方法
move: function(dir) {
if (dir === 'left') {
this.x -= this.speed;
this.flipping = false; // 往左移动时不需要翻转贴图
} else if (dir === 'right') {
this.x += this.speed;
this.flipping = true; // 往右移动时需要翻转贴图
}
this.updateFrame(); // 更新帧数
}
}
function setup() {
// 创建画布
createCanvas(240, 135);
background(255); // 设置背景为白色
character.loadImages(); // 加载贴图
}
function draw() {
background(255); // 重绘背景
character.display(); // 绘制人物
}
// 键盘按键事件
function keyPressed() {
if (keyCode === LEFT_ARROW) {
character.move('left');
} else if (keyCode === RIGHT_ARROW) {
character.move('right');
}
}