I am currently writing some simple snake game in java. The snake objects has an array full of bodyparts. these bodyparts all contain a rectangle.
the snake's update method is like that:
public void update() {
if(isMoving) {
if(System.currentTimeMillis() - moveTimer > moveSpeed) {
if(parts.get(0).getX()+dx*size >= 0+GameView.GRID_PADDING_LEFT && parts.get(0).getY()+dy*size >= 0+GameView.GRID_PADDING_TOP && parts.get(0).getX()+dx*size <= ((GameView.GRID_WIDTH-1)*size)+GameView.GRID_PADDING_LEFT && parts.get(0).getY()+dy*size <= ((GameView.GRID_HEIGHT-1)*size)+GameView.GRID_PADDING_TOP) {
for(int i = parts.size()-1; i > 0; i--) {
parts.get(i).setLocation((int)(parts.get(i-1).getX()), (int)(parts.get(i-1).getY()));
}
parts.get(0).setLocation(parts.get(0).getRect().left+dx*size, parts.get(0).getRect().top+dy*size);
moveTimer = System.currentTimeMillis();
}else {
die();
}
}
}
}
All in one, the snake moves it's head into dx direction times one cellspace (size) --> dx*size and dy*size. Then the rest of the body moves, the part behind the head gets the coordinates of the head, the part behind that part gets the coodrinates from the part in front of him etc.
Now I am trying to achieve some collision with the snake itself. I've tried several methods, e.g.:
if(parts.size() > 2) {
for(int i = 3; i < parts.size(); i++) {
if(parts.get(0).getRect().intersect(parts.get(i).getRect())) {
die();
}
}
}
But as soon as the bodypart array reaches the limit of 2 parts, the die() method gets called. I don't know why, because the 2nd part should sit two bodyparts behind the head, which makes it impossible to intersect with the head-rectangle.
Where's my problem?