在unity中導入標準資源包,可以拖拽一個FPSController到場景中漫遊,十分方便,但是調整方向是靠鼠標滑動的,到了手機端沒有鼠標,對於新手的我不知道怎麼處理,最後是通過在屏幕上放置四個按鈕控制方向
1.修改MouseLook.cs
這個腳本里有一個LookRotation()方法,是用於根據鼠標移動距離控制視圖旋轉角度的,在它的代碼基礎上,我們寫一個MyLookRotation()方法,通過傳入的參數代替鼠標移動
public void MyLookRotation(Transform character, Transform camera,int flag,float angle) {
//傳入flag和q的值,flag=1是旋轉x軸,flag=2旋轉y軸,angle爲旋轉量,正爲右、上,負爲左、下
float yRot = CrossPlatformInputManager.GetAxis("Mouse X") * XSensitivity;
float xRot = CrossPlatformInputManager.GetAxis("Mouse Y") * YSensitivity;
if (flag == 1)
{
yRot = angle;
}
else {
xRot = angle;
}
m_CharacterTargetRot *= Quaternion.Euler(0f, yRot, 0f);
m_CameraTargetRot *= Quaternion.Euler(-xRot, 0f, 0f);
if (clampVerticalRotation)
m_CameraTargetRot = ClampRotationAroundXAxis(m_CameraTargetRot);
if (smooth)
{
character.localRotation = Quaternion.Slerp(character.localRotation, m_CharacterTargetRot,
smoothTime * Time.deltaTime);
camera.localRotation = Quaternion.Slerp(camera.localRotation, m_CameraTargetRot,
smoothTime * Time.deltaTime);
}
else
{
character.localRotation = m_CharacterTargetRot;
camera.localRotation = m_CameraTargetRot;
}
UpdateCursorLock();
}
2.修改FirstPersonController.cs
這個腳本里有一個RotateView()方法調用MouseLook.cs的LookRotation()方法,那我們也寫一個MyRotateView()方法,調用上面的MyLookRotation()方法
public void MyRotateView(int flag, float angle) {
m_MouseLook.MyLookRotation(transform, m_Camera.transform,flag,angle);
}
3.添加button
我們在unity創建四個button,分別代表上下左右,設置好樣式。然後分別寫一個腳本,比如說向下的按鈕
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using UnityStandardAssets.Characters.FirstPerson;
public class Button_down : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
public Button button;
private bool isCanRotate = false; //判斷是否可以旋轉
void Start()
{
}
void Update() {
if (isCanRotate)
{
//每個button不同之處就是調用MyRotateView()時傳入的參數,
//GameObject.Find("物體名").GetComponent<腳本名>().方法名(參數)
GameObject.Find("FPSController").GetComponent<FirstPersonController>().MyRotateView(2, -0.8f);
}
}
//當按下按鈕
public void OnPointerDown(PointerEventData eventData)
{
isCanRotate = true;
}
//當擡起
public void OnPointerUp(PointerEventData eventData)
{
isCanRotate = false;
}
}