一、实现效果
二、核心功能
void CreateFood() { float x = Random.Range(-500f, 500f); float y = Random.Range(-260f, 260f); float z = 0; GameObject food=Instantiate< GameObject>(FoodPrefab, new Vector3(x, y, z), Quaternion.identity); food.transform.SetParent(canv.transform, false);//再将它设为canvas的子物体 Debug.Log(“位置:” + food.transform.position + “父节点:” + food.transform.parent); }
private void OnTriggerEnter2D(Collider2D collision) { if (collision.tag.Equals(“Food”)) { Destroy(collision.gameObject); GameObject newbodynext = Instantiate(body, snakeBody[snakeBody.Count - 1].transform.position, Quaternion.identity); newbodynext.transform.SetParent(canv.transform, false);//再将它设为canvas的子物体 snakeBody.Add(newbodynext); CreateFood(); } else if (collision.tag.Equals(“Wall”)) { Debug.Log(“游戏结束”); } }
三、挂在蛇头上的代码
ps:需要用到上上章的挂在“中心圆”节点上CenterCircle脚本里的thlta变量。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Plane : MonoBehaviour
{
float timer = 0f;
float interval = 0.2f;
float speed = 1.5f;
public GameObject FoodPrefab;
public GameObject body;
List<GameObject> snakeBody = new List<GameObject>();
GameObject canv;
void Start()
{
canv= GameObject.Find("Canvas");
for (int i = 0; i < 3; ++i)
{
Vector3 SnakeHeadPos = transform.position;
SnakeHeadPos.z = 0;
GameObject newbodynext = Instantiate<GameObject>(body,
SnakeHeadPos - (i + 1) * new Vector3(0, 40f, 0f), Quaternion.identity);
newbodynext.transform.SetParent(canv.transform, false);
snakeBody.Add(newbodynext);
}
CreateFood();
CreateFood();
}
void Update()
{
timer += speed * Time.deltaTime;
if (timer > interval)
{
timer = 0;
Vector3 tmpPosition = transform.position;
List<Vector3> tmpList = new List<Vector3>();
for (int i = 0; i < snakeBody.Count; ++i)
{
tmpList.Add(snakeBody[i].transform.position);
}
transform.Translate(0, 0.5f, 0);
snakeBody[0].transform.position = tmpPosition;
for (int i = 1; i < snakeBody.Count; ++i)
{
snakeBody[i].transform.position = tmpList[i - 1];
}
}
float thlta_z = GameObject.Find("中心圆").GetComponent<CenterCircle>().thlta;
transform.rotation = Quaternion.Euler(0, 0, thlta_z);
}
void CreateFood()
{
float x = Random.Range(-500f, 500f);
float y = Random.Range(-260f, 260f);
float z = 0;
GameObject food=Instantiate<GameObject>(FoodPrefab, new Vector3(x, y, z), Quaternion.identity);
food.transform.SetParent(canv.transform, false);
Debug.Log("位置:" + food.transform.position + "父节点:" + food.transform.parent);
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag.Equals("Food"))
{
Destroy(collision.gameObject);
GameObject newbodynext = Instantiate<GameObject>(body,
snakeBody[snakeBody.Count - 1].transform.position,
Quaternion.identity);
newbodynext.transform.SetParent(canv.transform, false);
snakeBody.Add(newbodynext);
CreateFood();
}
else if (collision.tag.Equals("Wall"))
{
Debug.Log("游戏结束");
}
}
}
|