這一篇我們要讓貪吃蛇吃掉一顆蘋果後,身體變長一節
新增身體部分
在hieracky中新增一個circle,並改變它的顏色,接著把他拉到底下project的部分
在snack的腳本中新增這一行:public Transform bodyPrefab;
完整程式碼:
using UnityEngine;
public class Snack : MonoBehaviour
{
Vector3 direction;
public float speed;
public Transform bodyPrefab;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
Debug.Log(transform.position);
Time.timeScale = speed;
}
// Update is called once per frame
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;
}
}
void FixedUpdate()
{
transform.Translate(direction);
}
}
儲存好後,unity的頁面會多一個body prefab變數,再將body拖曳進去
打開apple,inspector介面有一個tag選項,打開後按add tag,接著按+,輸入Food,出去後再按tag,選擇剛剛新增的Food

最後,在Snack的腳本裡輸入這串完整程式碼:
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;
bodies.Add(transform);
}
// Update is called once per frame
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));
}
}
}