Question by
valenreswara7 · 4 days ago ·
movementcollision2dsnake
How do I make my snake stop moving after colliding with obstacles?
This is my first time programming/making a game. I followed a tutorial on youtube on how to make the snake game, so I just followed what he did in the video. For the most part, it works.
But after colliding with the snake or the walls it just kept on respawning.
How do I make the snake to stop moving, and then respawn a few moments later?
using System.Collections.Generic;
using UnityEngine;
public class Snake : MonoBehaviour
{
private Vector2 _direction = Vector2.right;
public List<Transform> _segments = new List<Transform>();
public Transform segmentPreFab;
public int initialSize = 4;
private void Start()
{
ResetState();
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.W) && _direction != Vector2.down)
{
_direction = Vector2.up;
}
else if (Input.GetKeyDown(KeyCode.S) && _direction != Vector2.up)
{
_direction = Vector2.down;
}
else if (Input.GetKeyDown(KeyCode.A) && _direction != Vector2.right)
{
_direction = Vector2.left;
}
else if (Input.GetKeyDown(KeyCode.D) && _direction != Vector2.left)
{
_direction = Vector2.right;
}
}
private void FixedUpdate()
{
for (int i = _segments.Count - 1; i> 0; i--)
{
_segments[i].position = _segments[i - 1].position;
}
this.transform.position = new Vector3(
Mathf.Round(this.transform.position.x) + _direction.x,
Mathf.Round(this.transform.position.y) + _direction.y,
0.0f
);
}
private void Grow()
{
Transform segment = Instantiate(this.segmentPreFab);
segment.position = _segments[_segments.Count - 1].position;
_segments.Add(segment);
}
private void ResetState()
{
for (int i = 1; i < _segments.Count; i++)
{
Destroy(_segments[i].gameObject);
}
_segments.Clear();
_segments.Add(this.transform);
for (int i = 1; i < this.initialSize; i++) {
_segments.Add(Instantiate(this.segmentPreFab));
}
this.transform.position = Vector3.zero;
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Food")
{
Grow();
} else if (other.tag == "Obstacle")
{
FindObjectOfType<Food>().RandomizePosition();
ResetState();
}
}
}
Comment
Your answer
Follow this Question
Related Questions
Snake movement from Snake VS Block 0 Answers
Snake following mouse and moves faster when the mouse is further away 1 Answer
How to cancel the force caused by collision? So the player is not pushed away when it hits a corner? 0 Answers
Make an object follow another object's path (Snake game) 0 Answers