What collision objects to use in a snake game

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Akubra

Hi all, I’m trying to create a top-down snake game where the snake moves around horizontally and vertically over a grid of cells. It must eat food to grow and must not bump into walls or its own body. So as the snake moves collisions have to be detected between it and the food and walls, and between its head and its body.
Secondly, after the snake has eaten a food item, I have to spawn a new food item at a random position while the snake moves around. Food may not be spawned on top of walls or on top of the snake. So I have to detect collisions between the new food and the snake and walls.
I’m struggling to figure out what kind of collision objects I should use for the snake, the food and the walls.
I don’t want the snake to move in a continuous way, but rather jump from cell to cell. Before each new snake move I calculate to which cell its head should go and set its position and let the body follow. That works fine. But it means I cannot use a kinematic body2d because the docs say: “When moving a KinematicBody2D, you should not set its position property directly. Instead, you use the move_and_collide() or move_and_slide() methods.” I cannot use a static body2d either because when the head collides with the body, it should also be detected.
And what about the food and the walls? The food is a sprite. I could give it a kinematic body2d, but when it’s placed in an allowed spot, it doesn’t move anymore. The walls are completely fixed and given their position in code with the draw_rect() function. So, I think I should give them a static body2d, but I’m not sure.
What would be the best collision objects to use for those three objects?
Thanks in advance for your answer(s).

:bust_in_silhouette: Reply From: Inces

If You really want to use collisions for this, You should just use Area

However. since You already coded elegant grid movement, You can also detect collisions this way. Keep the data about objects in cells in a dictionary {tile : content } and update it every time a snake moves, so You can simply check what is inside of a tile snake is currently headed to.

Thanks for your answer. I think I’ll go for the dictionary solution, and try it with a Vector2 for the cell and an enum for the content.

Akubra | 2022-09-28 09:59