This site requires JavaScript, please enable it in your browser!
Greenfoot back
Osso
Osso wrote ...

2014/6/10

How do I let new snake circles follow the first one?

Osso Osso

2014/6/10

#
This is my code and I have no idea where to start ( description is Dutch ) A new snake needs to be created and it needs to follow the snake ahead of it everytime an apple is eaten import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * De slang, de hoofdrolspeler in het spel. * * @author * @version (a version number or a date) */ public class Snake extends Actor { private boolean leftPressed; private boolean rightPressed; /** * Act - do whatever the Snake wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { move(1); /* int dx = 0; // local field to hold movement along the x-axis int dy = 0; // local field to hold movement along the y-axis if (Greenfoot.isKeyDown("up")) { dy -= 1; }// wijzig y-as beweging naar boven if (Greenfoot.isKeyDown("down")) { dy += 1; }// wijzig y-as beweging naar beneden */ // als links is ingedrukt if (Greenfoot.isKeyDown("left")) { // als dat net niet zo was if(!leftPressed) { setRotation(getRotation()-90); } leftPressed = true; } else { leftPressed = false; } // als rechts is ingedrukt if (Greenfoot.isKeyDown("right")) { // als dat net niet zo was if(!rightPressed) { setRotation(getRotation()+90); } rightPressed = true; } else { rightPressed = false; } // if (dx * dy == 0) setLocation(getX()+dx, getY()+dy); // if not diagonal movement, move (or stay, if no movement at all) Actor apple1; apple1 = getOneObjectAtOffset(0, 0, Apple.class); if (apple1 != null) { World SnakeWorld; SnakeWorld = getWorld(); SnakeWorld.removeObject(apple1); SnakeWorld.addObject( new Apple(), Greenfoot.getRandomNumber(SnakeWorld.getWidth()) - 205, Greenfoot.getRandomNumber(SnakeWorld.getHeight()) ); } } }
danpost danpost

2014/6/10

#
One thing, first. In the act method, you are using both 'move' and 'setLocation'. You need to use one or the other, but not both; and, the preceding code should be geared toward that end. You should get the movement right for the head of the snake before moving on to trying to move an entire 'multiple section' snake. Since you are using only NORTH, SOUTH, EAST and WEST directions, using 'setLocation' with 'dx' and 'dy' would be the way to go.
You need to login to post a reply.