Nik*_*hov 7 javascript game-development
我正在编写一种算法,以给定的速度遍历数组的元素。我用它来遍历我发现的一系列路径中的游戏地图上的单元格。
我需要用新数组调用新函数时,最后一个函数调用停止工作。
单击鼠标,即可沿路径移动。现在,如果我们调用第一个函数,它将沿着该路径运行,但是,如果在该路径的末尾之前,使用新路径再次调用该函数,则这两个函数将继续更改当前坐标。
对象必须在第一次调用该函数时所到达的位置中断其路径,并在第二个函数调用中继续其路径。
这是它现在如何工作的示例代码:
let coord = {x:0,y:0}
let goByPath = (path=[],coord={})=>{
let i = 0;
pathIteration(i,path,coord)
}
let pathIteration = (i,path,coord)=>{
if(i++<path.length){
setTimeout(()=>{
coord = path[i-1];
console.log(coord);
pathIteration(i,path,coord);
},500);
}
return i;
};
path1 = [{x:0,y:1},{x:1,y:1},{x:1,y:2},{x:2,y:2}];
path2 = [{x:1,y:3},{x:1,y:4},{x:1,y:5}];
goByPath(path1, coord);
setTimeout(()=>{
goByPath(path2, coord);
},900);Run Code Online (Sandbox Code Playgroud)
现在输出到控制台:
{
"x": 0,
"y": 1
}
{
"x": 1,
"y": 1
}
{
"x": 1,
"y": 3
}
{
"x": 1,
"y": 2
}
{
"x": 1,
"y": 4
}
{
"x": 2,
"y": 2
}
{
"x": 1,
"y": 5
}
Run Code Online (Sandbox Code Playgroud)
所需的输出:
{
"x": 0,
"y": 1
}
{
"x": 1,
"y": 1
}
{
"x": 1,
"y": 3
}
{
"x": 1,
"y": 4
}
{
"x": 1,
"y": 5
}
Run Code Online (Sandbox Code Playgroud)
你只需要clearTimeout https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout
let coord = { x: 0, y: 0 };
let myTimeout;
let goByPath = (path = [], coord = {}) => {
let i = 0;
clearTimeout(myTimeout); // stop previous calls
pathIteration(i, path, coord);
}
let pathIteration = (i, path, coord) => {
rect(coord);
if (i++ < path.length) {
myTimeout = setTimeout(() => { // store reference to timeout
coord = path[i - 1];
pathIteration(i, path, coord);
}, 500);
}
return i;
};
/* canvas grid for display purposes */
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var n = 10;
var size = Math.min(innerWidth, innerHeight);
var u = size / n;
var draw = function() {
size = Math.min(innerWidth, innerHeight);
u = size / n;
canvas.width = size;
canvas.height = size;
for (var y = 0; y < n; y++) {
for (var x = 0; x < n; x++) {
ctx.strokeStyle = '#000';
ctx.strokeRect(x * u, y * u, u, u);
}
}
};
draw();
var rect = (coord) => {
ctx.fillStyle = '#888';
ctx.fillRect(coord.x * u, coord.y * u, u, u);
};
/* example */
var path1 = [{x:0,y:1},{x:1,y:1},{x:1,y:2},{x:2,y:2}];
goByPath(path1, coord);
var path2 = [{x:1,y:3},{x:1,y:4},{x:1,y:5}];
setTimeout(() => { goByPath(path2, coord); }, 1600);Run Code Online (Sandbox Code Playgroud)
body {
margin: 0;
display: grid;
place-content: center;
}Run Code Online (Sandbox Code Playgroud)
<canvas></canvas>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
58 次 |
| 最近记录: |