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

2018/2/5

HEEELP

ORSODO ORSODO

2018/2/5

#
I want to make a Snake game, but I don't know how to make the tail move together with the head. I want to use an array but I don't know how to program it to move together with the head.
danpost danpost

2018/2/5

#
Add to the body class, the following field:
private Actor behind;
Add the field to the class of the head as well, if a different class. Then add the following method to the body class:
public void move(Actor ahead, boolean addBehind)
{
    if (behind != null) behind.move(this, addBehind);
    else if (addBehind) getWorld().addObject(behind = new Body(), getX(), getY());
    setLocation(ahead.getX(), ahead.getY());
}
With this the head can control both movement and adding length using:
behind.move(this, false); // moves body without adding length (false), in this case
setLocation(<<newX>>, <<newY>>); // moving the head to its next location
No other movement codes is required except for that which determines the new location coordinates of the head. The codes given were not tested, but I do not foresee any issues with them.
ORSODO ORSODO

2018/2/5

#
thx
You need to login to post a reply.