Hello guys. I am a beginner and I was making a snake game in unity after following some tutorials. I have no problem with getting the snake moving but when I add new segments to the snake using a list, they all get instantiated on the head of the snake instead of behind it.
Here is my code:
public class SnakeMovement : MonoBehaviour
{
private Vector2Int gridPos;
private Vector2Int moveDirection;
private float moveTimer;
public float moveTimerMax = 1f;
public Transform bodySegment;
private readonly List<Transform> segments = new List<Transform>();
void Start()
{
gridPos = new Vector2Int(0,0);
moveTimer = moveTimerMax;
moveDirection = new Vector2Int(0, 1);
segments.Add(this.transform);
}
void Update()
{
GetInput();
MovePlayer();
for (int i = segments.Count - 1; i > 0; i--)
{
segments[i].position = segments[i - 1].position;
}
}
private void GetInput()
{
if (Input.GetKeyDown(KeyCode.W))
{
if (moveDirection.y != -1)
{
moveDirection.y = 1;
moveDirection.x = 0;
}
}
if (Input.GetKeyDown(KeyCode.S))
{
if (moveDirection.y != 1)
{
moveDirection.y = -1;
moveDirection.x = 0;
}
}
if (Input.GetKeyDown(KeyCode.D))
{
if (moveDirection.x != -1)
{
moveDirection.y = 0;
moveDirection.x = 1;
}
}
if (Input.GetKeyDown(KeyCode.A))
{
if (moveDirection.x != 1)
{
moveDirection.y = 0;
moveDirection.x = -1;
}
}
}
private void MovePlayer()
{
moveTimer += Time.deltaTime;
if (moveTimer > moveTimerMax)
{
gridPos += moveDirection;
moveTimer -= moveTimerMax;
}
transform.position = new Vector3(gridPos.x, gridPos.y);
}
void GrowSnake()
{
Transform segmentIncrease = Instantiate(this.bodySegment);
segmentIncrease.position = segments[^1].position; //^ is short form of segments.Count - 1
segments.Add(segmentIncrease);
}
private void OnTriggerEnter2D(Collider2D col)
{
if(col.CompareTag("Food"))
{
GrowSnake();
}
}
}
I don’t understand why this happening and I hope someone sees this and helps me out. Thanks in advance