I have followed this tutorial on making a 2D snake game. It works and also works in 3D with same controls meaning it is still a 2D game. I would like to make a 3D snake game and have tried changing controls to 3D like this
private void FixedUpdate()
{
transform.Translate(Vector3.forward * Time.deltaTime * speed);
horizontalInput = Input.GetAxis("Horizontal");
transform.Rotate(Vector3.up * Time.deltaTime * rotationSpeed * horizontalInput);
verticalInput = Input.GetAxis("Vertical");
transform.Rotate(Vector3.right * Time.deltaTime * rotationSpeed * verticalInput);
}
So the full snake script looks like this.
public class Snake : MonoBehaviour
{
Vector2 direction = Vector2.right;
private List<Transform> segments = new List<Transform>();
public Transform segmentPrefab;
public float speed = 20;
private float forwardInput;
private float verticalInput;
public int initialSize = 4;
// Start is called before the first frame update
void Start()
{
ResetState();
}
private void FixedUpdate()
{
transform.Translate(Vector3.forward * Time.deltaTime * speed);
horizontalInput = Input.GetAxis("Horizontal");
transform.Rotate(Vector3.up * Time.deltaTime * rotationSpeed * horizontalInput);
verticalInput = Input.GetAxis("Vertical");
transform.Rotate(Vector3.right * Time.deltaTime * rotationSpeed * verticalInput);
}
private void Grow()
{
Transform segment = Instantiate(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(transform);
for (int i = 1; i < initialSize; i++)
{
segments.Add(Instantiate(segmentPrefab));
}
transform.position = Vector3.zero;
}
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Food")
{
Grow();
}
if(other.tag == "Obstacle")
{
ResetState();
}
}
}
Using this script the controls work but the new segments won’t join onto the snake tho they do spawn in one place and don’t move. Yet if I change to 2D control with this in update it works as it should.
void Update()
{
if (Input.GetKeyDown(KeyCode.UpArrow))
{
direction = Vector2.up;
}
if (Input.GetKeyDown(KeyCode.DownArrow))
{
direction = Vector2.down;
}
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
direction = Vector2.left;
}
if (Input.GetKeyDown(KeyCode.RightArrow))
{
direction = Vector2.right;
}
}
private void FixedUpdate()
{
for(int i = segments.Count - 1; i > 0; i--)
{
segments[i].position = segments[i - 1].position;
}
transform.position = new Vector3(
Mathf.Round(transform.position.x) + direction.x,
Mathf.Round(transform.position.y) + direction.y
);
}
I can’t understand why the segments spawn on the snake in 2D version but not 3D version. All the scrips are being used in a 3D game.
Also is there anywhere I could learn better how for loops work as I’m guessing it could help me with this.