unity3d之3D貪吃蛇
阿新 • • 發佈:2019-02-15
原始碼如下:
public class SnakeManager : MonoBehaviour { [SerializeField] private List<GameObject> snakeBodys = new List<GameObject>(); [SerializeField] private GameObject snakePrefab; [SerializeField] private GameObject foodGo; [SerializeField] private float randomRange = 9.6f; private const float moveRate = 0.1f; private const float cellSize = 0.3f; private Vector3 lastOnePostion = new Vector3(0 , 0.15f , -0.9f); private int winCount = 300; private bool canRun = true; // Use this for initialization void Start () { StartCoroutine(move()); createFood(); } // Update is called once per frame void Update () { if(Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow)) { snakeBodys[0].transform.rotation = Quaternion.Euler(0, 0, 0); }else if(Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.LeftArrow)) { snakeBodys[0].transform.rotation = Quaternion.Euler(0, -90, 0); } else if(Input.GetKeyDown(KeyCode.S) || Input.GetKeyDown(KeyCode.DownArrow)) { snakeBodys[0].transform.rotation = Quaternion.Euler(0, 180, 0); } else if(Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.RightArrow)) { snakeBodys[0].transform.rotation = Quaternion.Euler(0, 90, 0); } } IEnumerator move() { while(canRun) { lastOnePostion = snakeBodys[snakeBodys.Count - 1].transform.position; for(int i = snakeBodys.Count - 1; i >= 1; i--) { snakeBodys[i].transform.position = snakeBodys[i - 1].transform.position; snakeBodys[i].transform.rotation = snakeBodys[i - 1].transform.rotation; } snakeBodys[0].transform.Translate(Vector3.forward * cellSize); yield return new WaitForSeconds(moveRate); } } public void eatFood() { if(snakeBodys.Count > winCount) GameOver(true); GameObject go = Instantiate(snakePrefab) as GameObject; go.transform.SetParent(transform , false); go.transform.position = lastOnePostion; snakeBodys.Add(go); createFood(); } void createFood() { float x = Random.Range(-randomRange, randomRange); float z = Random.Range(-randomRange, randomRange); Vector3 v3 = foodGo.transform.position; v3.x = x; v3.z = z; Collider[] hitColliders = Physics.OverlapSphere(v3, 0.5f); if(hitColliders.Length > 1) { createFood(); return; } foodGo.SetActive(true); foodGo.transform.position = v3; } public void GameOver(bool isWin) { Debug.Log("gameover:" + isWin); canRun = false; } public void LeftTouchValueChange(Vector2 v2) { Vector2 inputV2 = v2.MinusOneToOne(); snakeBodys[0].transform.LookAt(new Vector3(snakeBodys[0].transform.position.x + inputV2.x, snakeBodys[0].transform.position.y, snakeBodys[0].transform.position.z + inputV2.y)); } }
搖桿問題我弄了兩個,一個是虛擬搖桿,還有一個就是wsad電腦控制,這取決於個人。