今天要來加入玩家角色,以及用鍵盤來控制角色
// 玩家
var player_x;
var player_y;
resetPlayer = () => {
player_x = 660;
player_y = 440;
}
這邊要先定義一下按按鍵的事件
const KEY_LEFT_ARROW = 37;
const KEY_UP_ARROW = 38;
const KEY_RIGHT_ARROW = 39;
const KEY_DOWN_ARROW = 40;
var keyLeft = false;
var keyRight = false;
var keyTop = false;
var keyDown = false;
initInput = () => {
document.addEventListener("keydown", keyPressed);
document.addEventListener("keyup", keyReleased);
}
keyPressed = (evt) => {
setKeyState(evt.keyCode, true);
evt.preventDefault();
}
keyReleased = (evt) => {
setKeyState(evt.keyCode, false);
}
setKeyState = (key, to) => {
if (key == KEY_LEFT_ARROW) {
keyLeft = to;
}
if (key == KEY_RIGHT_ARROW) {
keyRight = to;
}
if (key == KEY_UP_ARROW) {
keyTop = to;
}
if (key == KEY_DOWN_ARROW) {
keyDown = to;
}
}
然後持續監聽事件
window.onload = () => {
canvas = document.getElementById('playground');
canvasContext = canvas.getContext('2d');
initInput();
//一秒更新幾次畫面
var timesPerSec = 30;
setInterval(drawAll, 1000 / timesPerSec);
resetPlayer();
}
監聽事件後就可以移動玩家角色了
playerMove = () => {
var next_x = player_x;
var next_y = player_y;
if (keyLeft) {
next_x -= MOVE_SPEED;
}
if (keyRight) {
next_x += MOVE_SPEED;
}
if (keyTop) {
next_y -= MOVE_SPEED;
}
if (keyDown) {
next_y += MOVE_SPEED;
}
if (checkMapBrick(next_x, next_y) == false) {
player_x = next_x;
player_y = next_y;
}
}
記得加入到move中
// 負責處理動作
move = () => {
map_x = player_x - canvas.width / 2;
map_y = player_y - canvas.height / 2;
playerMove();
}
OK 那明天就來做個收尾吧