# Day 21 | 3D蛇走迷宮AR遊戲開發Part2 -角色蛇移動 ###### tags: `Unity` `AR手遊` > **目錄** > 移動機制說明 > 變數宣告 > 介面按鈕設定 > 前進 > 旋轉 ## 移動機制說明 介面中會有上、下、左、右四個按紐,觸控哪個按鈕,角色肥遺就會往那個方向旋轉然後前進。  ## 變數宣告 在開始寫肥遺的一切移動之前,要先寫按鈕如何控制肥遺。因為會有4個方向,所以這邊寫了一個class來為方向方向,這樣在之後要判別方向比較方便。 ``` static class Dir { public const int Top = 0; public const int Right = 1; public const int Down = 2; public const int Left = 3; public const int no = -1; } ``` 再來是宣告幾個變數在之後會用到的變數 儲存按鈕按下的方向 ``` int inputDir = Dir.no; ``` 儲存目前的方向 ``` int Direction = Dir.Right; ``` 用來儲存不同按鈕前進的方向 ``` Vector3 movement; ``` 是否要旋轉 ``` bool rotating = false; ``` 用來判斷順時鐘逆時鐘 ``` bool turntoright = false; ``` 累積旋轉度數 ``` float rotateangle = 0; ``` 用來儲存原本的角度 ``` float oriAngle = 90; ``` ## 介面按鈕設定 先為按鈕增加Trigger Event,PointDown跟PointUp,決定當按鈕壓下以及放開時,物件要發生的動作。根據按下的按鈕更改inputDir變數。 ### 不同按鈕,不同方向旋轉、移動 以**向上**按鈕來說,需要注意的是在按下這顆按鈕之前,原方向可能是向右或向左,用if else去判斷之前可能的方向,來決定要順時鐘還是逆時鐘旋轉,並且把rotating變數設為true(準備旋轉)。 在不同按鈕按下的函式中,改變movement變數,例如按下**向上**按鈕,movement.z = 1f ,根據座標以此類推。  ## 前進 在FixedUpdate中,判斷如果有輸入方向,就用rigibody的MovePosition函式來移動肥遺。 ``` void FixedUpdate(){ if(inputDir != Dir.no) { rb.MovePosition(rb.position + movement * movespeed * Time.fixedDeltaTime); } } ``` ## 旋轉 也是在FixedUpdate()中進行: * 先判斷是否需要旋轉(以rotating作為flag) * 開始累積rotateangle * 用rotateangle判斷有沒有轉超過90度了 * 如果還沒超過,就再繼續判斷式順時針還是逆時針,並使用localRotation做旋轉 * 如果超過了,就判斷旋轉方向,旋轉到由原本的角度再旋轉90度,並停止旋轉,歸零選轉角度 ``` if (rotating){//判斷有沒有旋轉 rotateangle += rotatespeed * Time.deltaTime; if (rotateangle < 90f){ //還沒轉玩90度 if (turntoright) { transform.localRotation = Quaternion.Euler(0, transform.localEulerAngles.y + rotatespeed * Time.deltaTime, transform.localEulerAngles.z); } else { transform.localRotation = Quaternion.Euler(0, transform.localEulerAngles.y - rotatespeed * Time.deltaTime, transform.localEulerAngles.z); } } else { if (turntoright) { transform.localRotation = Quaternion.Euler(0, oriAngle - 90f, transform.localEulerAngles.z); oriAngle = oriAngle + 90f; } else { transform.localRotation = Quaternion.Euler(0, oriAngle + 90f, transform.localEulerAngles.z); oriAngle = oriAngle - 90f; } rotating = false; rotateangle = 0; } } ``` --- 以上就是比較簡單的旋轉以及移動,那肥移走迷宮的這個系列就到這邊,我們明天下一個系列見~
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up