代码:
var player = [0, 0, 1, 90]
var raycast = [0, 0]
do {
raycast[1] = raycast[1] + (Math.sin(player[3]) * 2)
raycast[2] = raycast[2] + (Math.cos(player[3]) * 2)
ctx.fillRect(Math.floor(raycast[1]), Math.floor(raycast[2]), 50, 50)
} while (blocks[Math.floor(raycast[1]*raycast[2])] == 0);
我尝试了floor这些值,如代码所示。 我期望能工作,但结果什么也没有。
如果有什么问题,有人可以告诉我吗,抱歉,我没有更多信息。
您什么也得不到,因为矩形正在接收
NaN
作为其坐标之一。
在这个稍微修改过的代码中:
var player = [0, 0, 1, 90]
var raycast = [0, 0]
//do {
raycast[1] = raycast[1] + (Math.sin(player[3]) * 2)
raycast[2] = raycast[2] + (Math.cos(player[3]) * 2)
console.log('raycast:', raycast);
console.log
({
0: raycast[0],
1: raycast[1],
2: raycast[2],
});
console.log('Rect?', Math.floor(raycast[1]), Math.floor(raycast[2]), 50, 50);
//ctx.fillRect(Math.floor(raycast[1]), Math.floor(raycast[2]), 50, 50)
//} while (blocks[Math.floor(raycast[1]*raycast[2])] == 0);
.as-console-wrapper { min-height: 100%; }
更改为
raycast
的正确索引或尝试以下操作:
const players =
[
[10, 10, 1, 90],
[100, 40, 1, 45],
];
players[0].raycast = [0, 0];
players[1].raycast = [-10, -10]
const canvas = document.querySelector('#myCanvas');
{
animateCanvas();
}
function animateCanvas ()
{
const context = canvas.getContext('2d');
const measurements = canvas.getBoundingClientRect();
const { width, height } = measurements;
context.fillStyle = '#000';
context.fillRect(0, 0, width, height);
for ( const player of players )
{
// Extract your variables instead of accessing indexes...
const [playerX, playerY, playerSomething, playerAngle] = player;
let [ rayX, rayY ] = player.raycast;
// Should those positions be relative to player positions?
rayX = ( playerX + rayX ) + ( Math.sin(playerAngle) * 2 );
rayY = ( playerY + rayY ) + ( Math.cos(playerAngle) * 2 );
// I slightly modified the calculations...
// Drawing the ray at the back as red...
context.fillStyle = '#F00';
context.fillRect(rayX, rayY, 50, 50);
context.fillRect(rayX, rayY, 50, 50);
// Drawing the player at the front as yellow...
context.fillStyle = '#FF0';
context.fillRect(playerX, playerY, 10, 10);
}
// Updating angles for animation sake...
players[0][3] += 1;
players[1][3] -= 1;
// Updating player 2 position for animation sake.
players[1][0] += 2 * Math.sin(players[1][1] / Math.PI);
players[1][1] += 2 * Math.cos(players[1][0] / Math.PI);
requestAnimationFrame(animateCanvas);
}
canvas
{
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
<canvas id="myCanvas"></canvas>
注意:我是通过猜测来做出这个的。