简体   繁体   中英

JavaScript/HTML5 Canvas Pathfinding Multiplexing Issue

I have a pathfinding script in JavaScript for HTML5 canvas that appears to have an issue with multiplexing.

jsFiddle Demo

The script has been taken and slightly adapted from the accepted SO answer here: A* Start path finding in HTML5 Canvas (which also has the same bug).

How to replicate the issue: Simply click quickly around the map while the red square is in motion, and you will see what appears to be the square splitting or branching off into each of the different paths.

I think what is happening is, as you should notice that the red squares start flickering during branching, it's actually just the same square trying to be in multiple places at the same time, causing the same square to "teleport" back and forth with the frame rate in alternating frames. This is just a theory though, but I don't think it's actually spawning more squares.

I'm not sure if it has to do with the movePlayer() function or the pathFinding() function. I think what I need to do is, if the object is moving and the target tile is updated, cancel any previous operation(s) instead of continuing to run them simultaneously - I have no idea how I would do this though.

As this will eventually be an enemy AI script, the target tile will always be updating in real-time as the player moves around the map, which will likely cause this issue to surface.

Thanks, and I appreciate any help in debugging this!

From what I can tell, the problem is with the timers being used. When you click, it's calculating the path between the current location and where you click, then it starts a timer that causes the square to move along that path, storing the information locally for that timer. When you click again, it starts another timer without clearing the old one, so it is now moving along two paths simultaneously from two different timers. It's drawing out every movement in each timer, and this can be seen as the flickering.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM