我为玩家模拟了一个交互式视图。只要游戏的组件在视图宽度内,就应该可以与其交互。使用我的代码,播放不同方向不是问题,但只能播放 180°。我可以进一步限制视图,使其成为一个可变的数字,正如您在我的草图中看到的那样?
蓝色是玩家的碰撞区域。 红色是当前视图宽度。 灰色是所需的视图宽度。
https://i.imgur.com/cyNYpv3.png
与画布交互以聚焦窗口并使用 WASD 或箭头键改变方向。
const canvas = document.querySelector('canvas')
const context = canvas.getContext('2d');
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
const keymap = [];
const player = {
x: window.innerWidth / 2 - 50,
y: window.innerHeight / 2 - 50,
size: 100,
range: 200,
view: {
start: 0,
end: Math.PI
}
};
const draw = () => {
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = 'rgba(0, 0, 255, .6)';
context.fillRect(
player.x,
player.y,
player.size,
player.size,
);
context.fillStyle = 'rgba(0, 0, 0, .6)';
context.beginPath();
context.arc(
player.x + player.size / 2,
player.y + player.size / 2,
player.range,
player.view.start,
player.view.end,
false
);
context.fill();
};
const change = () => {
let tempChange = { x: 0, y: 0 };
keymap.forEach(direction => {
if (direction === 'KeyS' || direction === 'ArrowDown') {
tempChange.y = 1;
}
if (direction === 'KeyA' || direction === 'ArrowLeft') {
tempChange.x = -1;
}
if (direction === 'KeyW' || direction === 'ArrowUp') {
tempChange.y = -1;
}
if (direction === 'KeyD' || direction === 'ArrowRight') {
tempChange.x = 1;
}
});
const actions = {
'1_1': () => {
// Down Right
player.view.start = 1.75 * Math.PI;
player.view.end = 0.75 * Math.PI;
},
'1_-1': () => {
// Up Right
player.view.start = 1.25 * Math.PI;
player.view.end = 0.25 * Math.PI;
},
'1_0': () => {
// Right
player.view.start = 1.5 * Math.PI;
player.view.end = 0.5 * Math.PI;
},
'-1_1': () => {
// Down Left
player.view.start = 0.25 * Math.PI;
player.view.end = 1.25 * Math.PI;
},
'-1_-1': () => {
// Up Left
player.view.start = 0.75 * Math.PI;
player.view.end = 1.75 * Math.PI;
},
'-1_0': () => {
// Left
player.view.start = 0.5 * Math.PI;
player.view.end = 1.5 * Math.PI;
},
'0_1': () => {
// Down
player.view.start = 0;
player.view.end = Math.PI;
},
'0_-1': () => {
// Up
player.view.start = Math.PI;
player.view.end = 0;
},
'0_0': () => {},
};
const dir = tempChange.x + '_' + tempChange.y;
const func = actions[dir];
func();
};
const loop = () => {
change();
draw();
requestAnimationFrame(loop);
};
const setup = () => {
window.addEventListener('keydown', event => {
const key = event.code;
const index = keymap.indexOf(key);
if (index > -1)
keymap.splice(index, 1);
keymap.push(key);
});
window.addEventListener('keyup', event => {
const key = event.code;
const index = keymap.indexOf(key);
if (index > -1)
keymap.splice(index, 1);
});
};
setup();
requestAnimationFrame(loop);
<canvas></canvas>
看起来您已经以从 0 到 pi (180°) 的弧度声明了视场,将其更改为您想要的弧度可以修复它