Unity3D 用按鈕控制人物行走
阿新 • • 發佈:2019-01-01
//動畫陣列 private var animUp:Object[]; private var animDown:Object[]; private var animLeft:Object[]; private var animRight:Object[]; //地圖 private var map:Texture2D; //當前人物的動畫 private var tex:Object[]; //人物的x座標 private var x: int; //人物的y座標 private var y: int; //幀序列 private var nowFram :int; //動畫幀的總數量 private var mframeCount:int; //每秒更新多少幀 private var fps:float = 3; private var time:float = 0; function Start () { //獲取圖片資源 animUp = Resources.LoadAll("up"); animDown = Resources.LoadAll("down"); animLeft = Resources.LoadAll("left"); animRight = Resources.LoadAll("right"); //地圖的圖片 map = Resources.Load("map/map"); //設定預設動畫 tex = animUp; } function OnGUI() { //繪製貼圖 GUI.DrawTexture(Rect(0,0,Screen.width,Screen.height),map,ScaleMode.StretchToFill,true,0); //繪製幀動畫 DrawAnimation(tex,Rect(x,y,32,48)); //點選按鈕移動人物 if(GUILayout.RepeatButton("Up")) { y -= 2; tex = animUp; } if(GUILayout.RepeatButton("down")) { y += 2; tex = animDown; } if(GUILayout.RepeatButton("Left")) { x -= 2; tex = animLeft; } if(GUILayout.RepeatButton("right")) { x += 2; tex = animRight; } } function DrawAnimation(tex:Object[],rect:Rect) { //繪製當前幀 GUI.DrawTexture(rect,tex[nowFram],ScaleMode.StretchToFill,true,0); //計算幀時間 time += Time.deltaTime; //超過限制幀則切換圖片 if(time >= 1.0 / fps) { nowFram++; time = 0; if(nowFram >= tex.Length) { nowFram = 0; } } }