當身體碰到自己的身體
在body的inspector點選add component,再選circle collider,接著在上面的tag也給他obstacle
接著把物件大小調整到自己覺得合適的的大小就好了
讓角色在每一次開始的時候都在中心點
完整程式碼:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
public class Snack : MonoBehaviour
{
Vector3 direction;
public float speed;
public Transform bodyPrefab;
public List<Transform> bodies = new List<Transform>();
void Start()
{
Time.timeScale = speed;
ResetStage();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.W))
{
Debug.Log("W");
direction = Vector3.up;
}
if (Input.GetKeyDown(KeyCode.A))
{
Debug.Log("A");
direction = Vector3.left;
}
if (Input.GetKeyDown(KeyCode.S))
{
Debug.Log("S");
direction = Vector3.down;
}
if (Input.GetKeyDown(KeyCode.D))
{
Debug.Log("D");
direction = Vector3.right;
}
}
private void FixedUpdate()
{
for(int i = bodies.Count - 1; i > 0; i--)
{
bodies[i].position = bodies[i - 1].position;
}
transform.Translate(direction);
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Food"))
{
bodies.Add(Instantiate(bodyPrefab
, transform.position
, Quaternion.identity));
}
if (collision.CompareTag("Obstacle"))
{
Debug.Log("game over!");
ResetStage();
}
}
void ResetStage()
{
transform.position = Vector3.zero;
direction = Vector3.zero;
for (int i = 1; i < bodies.Count; i++)
{
Destroy(bodies[i].gameObject);
}
bodies.Clear();
bodies.Add(transform);
}
}