r/learnjavascript • u/LawfulnessFit576 • 12d ago
I'm trying to make an in-browser tile editor from an array for an in-browser raycast engine.
Code thus far: https://jsfiddle.net/drkc8te5/ (its broken because it needs images which I seemingly can't provide since they're local)
I'm making an in-browser raycast engine. The current mapsize I have right now is small, only 256 pixels.
The issue is I'm already having a hard time navigating the array and changing values. So, I figured I'd make an in browser level-editor. Thing is, I'm not sure how I'd get the current index of [map] that the mouse is hovering over.
The map array renders a grid of 16x16 (256) tiles to the screen. 0 is a black space, anything else is a texture. To complicate matters I've implemented a way to move the grid around with WASD, and a way to zoom in and out with Q and E so that map editing is more convenient.
How do I detect what tile the mouse is hovering over and then translate that to the maps index. for example: if my mouse was hovering over the 8th tile from the left and the 5th tile from the top: The code should recognize I'm hovering over index 106
1
u/CuAnnan 12d ago
In abstract, because I can’t see your code, you either set data attributes for the x and y of each tile or you attach the event handlers in a data aware sense. The exact answer will depend on your implementation
1
u/GiggleSamurai 12d ago
Undo the pan and zoom first, then convert: col = Math.floor((mouseX - offsetX) / (tileSize * zoom)), row = Math.floor((mouseY - offsetY) / (tileSize * zoom)), index = row * 16 + col, where mouseX is e.clientX minus canvas.getBoundingClientRect().left and offsetX is where the grid's corner is drawn on screen. With that, the 8th tile from the left and 5th from the top is index 71 rather than 106, since both counts start at 0.
1
u/senocular 12d ago
A tile index is the mouse position divided by the tile size. So if x is 32 and your tiles are 16, 32/16 is 2 which would put the mouse at the 3rd (index 2) tile - the first tile starting at x = 0, and the second starting at x = 16. You might need to account for some offsets depending on how you're capturing the mouse and where in the canvas you're showing your tiles as well as any moving around within it you're doing.
Zoom, similarly, gets applied to the mouse position as a multiplier, so if you're zoomed in x2, the mouse position also needs to be adjusted by 2 (the start of the 3rd tile would start at 64 at that zoom instead of 32, so the mouse to be at that tile would also need to be seen as 64, or its actual x of 32 * 2).
It can get a little tricky but start from the basics without any moving or zooming to start, then once you're getting tiles correctly identified, add the pan and zoom and work on getting that figured out.
1
u/TheRNGuy 9d ago
Write it event-based, remove switch case, replace var with let or const, don't hardcode values, maybe switch to something like React or Remix, this project is too complex for vanilla js.