I’m remaking the game Snake to learn unity. Right now I’m stuck trying to make the body appear without ovelapping the head, basically atthaching the body to the head. Since all the tutorials use grid I can’t think of a way to make this work. Here is the part of code related to this,
using System.Collections;
using System.Collections.Generic;
using System.Net.WebSockets;
using UnityEngine;
public class Snake : MonoBehaviour
{
public Rigidbody2D myRigidbody;
public float SVelocity;
private List<Transform> _segments;
public Transform segmentPreFab;
public Vector3 SnakePosition;
public Vector3 SnakeVelocity;
public Vector3 SnakeHead;
void Start()
{
_segments = new List<Transform>();
_segments.Add(this.transform);
myRigidbody.velocity = Vector2.down * SVelocity;
}
// Update is called once per frame
void Update()
{
if (myRigidbody.velocity == Vector2.up * SVelocity)
{
if (Input.GetKeyDown(KeyCode.D))
myRigidbody.velocity = Vector2.right * SVelocity;
SnakePosition = myRigidbody.position;
if (Input.GetKeyDown(KeyCode.A))
myRigidbody.velocity = Vector2.left * SVelocity;
SnakePosition = myRigidbody.position;
}
if (myRigidbody.velocity == Vector2.down * SVelocity)
{
if (Input.GetKeyDown(KeyCode.D))
myRigidbody.velocity = Vector2.right * SVelocity;
SnakePosition = myRigidbody.position;
if (Input.GetKeyDown(KeyCode.A))
myRigidbody.velocity = Vector2.left * SVelocity;
SnakePosition = myRigidbody.position;
}
if (myRigidbody.velocity == Vector2.right * SVelocity)
{
if (Input.GetKeyDown(KeyCode.W))
myRigidbody.velocity = Vector2.up * SVelocity;
SnakePosition = myRigidbody.position;
if (Input.GetKeyDown(KeyCode.S))
myRigidbody.velocity = Vector2.down * SVelocity;
SnakePosition = myRigidbody.position;
}
if (myRigidbody.velocity == Vector2.left * SVelocity)
{
if (Input.GetKeyDown(KeyCode.W))
myRigidbody.velocity = Vector2.up * SVelocity;
SnakePosition = myRigidbody.position;
if (Input.GetKeyDown(KeyCode.S))
myRigidbody.velocity = Vector2.down * SVelocity;
SnakePosition = myRigidbody.position;
}
}
private void FixedUpdate()
{
for (int i = _segments.Count - 1; i > 0; i--)
{
_segments[i].position = _segments[i - 1].position;
}
SnakeVelocity = myRigidbody.velocity;
}
private void Grow()
{
Transform segment = Instantiate(this.segmentPreFab);
segment.position = _segments[_segments.Count - 1].position;
_segments.Add(segment);
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Food")
{
Grow();
}
}
}
I tried to adapt the code of a tutorial that is making the Snake the normal way (with a grid).
New contributor
João Pestana Teixeira is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.