貪喫蛇—藍鷗遊戲/AR/VR在線公開課小項目Dome(一)
1、首先我們要分析一下貪喫蛇這個遊戲的需求!
2、利用Unity的提供的素材,簡單的模擬一下貪喫蛇這個遊戲!
3、給蛇頭添加一個剛體
4、給蛇頭添加一個腳本,創建兩個方法 Turn ();Move ();用腳本控制蛇頭移動方向和用戶鍵盤監聽事件。
5、接下來請觀看貪喫蛇—遊戲/AR/VR在線公開課小項目Dome(二)
如果想要零基礎學習遊戲/AR/VR在線課程,歡迎到CSDN學院搜索“unity3D-遊戲/AR/VR在線就業班”免費視頻進行學習!
using UnityEngine;
using System.Collections;
//枚舉表示蛇頭移動的方向
public enum HeadDir{
Up,// 上
Down,//下
Left,//左
Right,//右
}
public class HeadCtrl : MonoBehaviour {
//移動速度,米/秒
public float speed;
//計時器用來記錄移動的時間
private float _Timer=0f;
//蛇頭當前移動的方向
private HeadDir _CurrentDir=HeadDir.Up;
//接下來蛇頭移動的方向
private HeadDir _NextDir=HeadDir.Up;
private void Update()
{
Turn ();
Move ();
}
private void Turn(){
//監聽用戶按鍵事件W
if (Input.GetKey (KeyCode.W))
{
//設定接下來蛇頭移動的方向
_NextDir= HeadDir.Up;
//檢測按鍵是否有效
if(_CurrentDir==HeadDir.Down)
{
//如果按鍵無效,修正接下來移動的方向
_NextDir = _CurrentDir;
}
}
//監聽用戶按鍵事件S
if (Input.GetKey (KeyCode.S))
{
//設定接下來蛇頭移動的方向
_NextDir =HeadDir.Down;
//檢測按鍵是否有效
if(_CurrentDir==HeadDir.Up)
{
//如果按鍵無效,修正接下來移動的方向
_NextDir = _CurrentDir;
}
}
//監聽用戶按鍵事件A
if (Input.GetKey (KeyCode.A))
{
//設定接下來蛇頭移動的方向
_NextDir =HeadDir.Left;
//檢測按鍵是否有效
if(_CurrentDir==HeadDir.Right)
{
//如果按鍵無效,修正接下來移動的方向
_NextDir = _CurrentDir;
}
}
//監聽用戶按鍵事件D
if (Input.GetKey (KeyCode.D))
{
//設定接下來蛇頭移動的方向
_NextDir = HeadDir.Right;
//檢測按鍵是否有效
if(_CurrentDir==HeadDir.Left)
{
//如果按鍵無效,修正接下來移動的方向
_NextDir = _CurrentDir;
}
}
}
private void Move()
{
//將計時器累加時間增量
_Timer += Time.deltaTime;
//判斷當前幀是否應該移動
if(_Timer>=(1/speed))
{
//向前移動一個單位
transform.Translate (Vector3.forward);
//重置計時器
_Timer=0f;
}
}
}