Indie game storeFree gamesFun gamesHorror games
Game developmentAssetsComics
SalesBundles
Jobs
Tags

Snippet: grid square highlighter

A topic by roadsidegravel created Jul 29, 2022 Views: 45
Viewing posts 1 to 1
Developer

github

Simple way to highlight the tile your mouse is hovering over on an infinite grid . 

If you have a tilebased game, then at some point you'll probably want to select a tile to interact with it. You could spawn a field of objects and use the Clicking on 3D Objects Panda3D manual page. But one of my current projects is a little map editor. I needed a way to align with the grid before placing the tiles down.

There's several ways you can approach this. This snippet uses a very simple solution that only requires three objects, the picker ray, a collision plane and a square highlighter object.

The picker ray code is nearly the same as in the Clicking on 3D Objects example. It collides with a CollisionPlane.  While the mouse is in the Panda3D window a continuously repeating task moves the picker to the mouse position. Collision Bitmasks ensure the picker ray only interacts with the collision plane. This allows it to highlight through buildings, in case you want to place something behind a tall building (looking at you They Are Billions).

The picker ray collides with the collision plane, resulting in a Collision Entry that holds all the collision information. Because this is a line going through a plane, the entry.getInteriorPoint(referenceNodepath) is the exact point where the mouse is hovering, transferred onto the plane in the 3D scene, in a coordinate system that relates to the refenceNodepath. That's quite neat.

The next step is aligning that collision point to a grid. If you want whole numbers, a simple round(...) does the trick. If you want halves, you can do round(... * 2 ) / 2. If you want to you can also align to a hexagonal grid, you just need to apply the right formula to the x and y coordinates.

The final step is moving the square highlighter to the grid aligned coordinates that were just calculated. It looks and feels like you're highlighting squares on a grid. As I said, I use this code in a simple map editor and it's quite nice for placing stuff down. If you want to then interact with things you've placed down, you can use another collider to select things that are currently on that square.

It's simpler and uses less resources than spawning and respawning endless rows of placeholder tiles.