MenuController.cs 代码如下:
using UnityEngine;
using UnityEngine.SceneManagement;
public class MenuController : MonoBehaviour {
void Start () {
//垂直同步数(VSyncs数值需要在每帧之间传递,使用0为不等待垂直同步。值必须是0,1或2。) :让显卡的运算和显示器刷新率一致以稳定输出的画面质量
QualitySettings.vSyncCount = 0;
Application.targetFrameRate = 60;
}
public void Start3DGame() {
//保存数据到内存中
PlayerPrefs.SetInt("3dMode", 1);
PlayerPrefs.SetInt("AppleCount", 10);
//加载到游戏场景
SceneManager.LoadScene("Main");
}
public void ExitGame() {
//退出游戏
Application.Quit();
}
}
4.菜单按钮关联类相关的方法。
5.到这一步为止,我们的UI菜单简单完成,然后需要开始我们游戏的主体。新建一个Main.unity 作为贪食蛇的游戏场景。
GridCube.cs 代码如下:
using UnityEngine;
using System.Collections;
using System;
public class GridCube : MonoBehaviour {
private CubeState currentState = CubeState.EMPTY;
public CubeSide cubeSide = 0;
[Flags]
public enum CubeSide {
FRONT = 1,
BACK = 2,
TOP = 4,
BOTTOM = 8,
LEFT = 16,
RIGHT = 32
}
public enum Direction {
UP, DOWN, LEFT, RIGHT, NONE
}
public enum CubeState {
SNAKE, APPLE, EMPTY, HOLE
}
public void AddCubeSide(CubeSide s) {
cubeSide |= s;
}
public bool SameSideAs(GridCube other) {
return (other.cubeSide & cubeSide) != 0;
}
public void SetCubeState(CubeState state) {
Renderer ren = GetComponent();
currentState = state;
switch (state) {
case CubeState.SNAKE:
ren.material.color = Color.blue;
break;
case CubeState.APPLE:
ren.material.color = Color.red;
break;
case CubeState.HOLE:
ren.material.color = Color.black;
break;
case CubeState.EMPTY:
default:
ren.material.color = Color.grey;
break;
}
}
public bool IsApple() {
return currentState == CubeState.APPLE;
}
public bool IsHole() {
return currentState == CubeState.HOLE;
}
public bool IsSnake() {
return currentState == CubeState.SNAKE;
}
public bool isEmpty() {
return currentState == CubeState.EMPTY;
}
public GridCube GetNextCube(Direction dir, out bool changedSide) {
changedSide = false;
Vector3 direction;
switch (dir) {
case Direction.UP:
direction = new Vector3(0, 1, 0);
break;
case Direction.DOWN:
direction = new Vector3(0, -1, 0);
break;
case Direction.LEFT:
direction = new Vector3(-1, 0, 0);
break;
case Direction.RIGHT:
direction = new Vector3(1, 0, 0);
break;
default:
return null;
}
GridCube neighbour = GetNeighbourAt(direction);
if (neighbour == null) {
// Get neighbour on the other side of the cube (back)
changedSide = true;
return GetNeighbourAt(new Vector3(0, 0, 1));
}
return neighbour;
}
private GridCube GetNeighbourAt(Vector3 direction) {
RaycastHit hit;
Ray ray = new Ray(transform.position, direction);
if (Physics.Raycast(ray, out hit)) {
GameObject go = hit.collider.gameObject;
return go.GetComponent();
}
return null;
}
// Update is called once per frame
void Update () {
}
}