Following an assignment and just getting started with libGDX by building a small Snake clone I've run into an issue that I'll probably be ashamed for in a little while.
I currently have a snake's head (a simple rectangle at this stage) moving around the game's canvas. The most straight-forward way of building the rest of the snake was to have the head own a Java Collections LinkedList of SnakeElements which would in-/decrease in size according to what the player does.
Having this list of SnakeElements follow the head however has proven to not be trivial.
The current function doing this is as follows and is called every time the head updates its position:
private void moveTail (float x, float y, int direction) {
float tmpx, tmpy;
int tmpdirection;
int offset_x, offset_y;
for (SnakeSegment snse : tail) {
offset_x = 0;
offset_y = 0;
tmpx = snse.getX();
tmpy = snse.getY();
tmpdirection = snse.getDirection();
switch(direction) {
case 0:
offset_x = 0;
offset_y = -(2 + snse.width);
break;
case 1:
offset_x = -(2 + snse.width);
offset_y = 0;
break;
case 2:
offset_x = 0;
offset_y = (2 + snse.width);
break;
case 3:
offset_x = (2 + snse.width);
offset_y = 0;
break;
default:
System.out.println("wrong direction");
}
snse.setX(x + offset_x);
snse.setY(y + offset_y);
snse.setDirection(direction);
x = tmpx;
y = tmpy;
direction = tmpdirection;
}
}
which unfortunately results in this behavior:
Any tips on how to make a correctly working snake tail would be much appreciated :)