【unity】标准资源包里的第一人称角色控制器FPSController在手机端旋转视图
在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;
}
}