0 votes

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 moveandcollide() or moveandslide() 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).

Godot version 3.5
in Engine by (18 points)

1 Answer

+1 vote

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.

by (8,101 points)

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.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.