您的位置:首页 > 移动开发 > Unity3D

Unity第一人称和第三人称视角脚本

2015-07-29 15:02 661 查看

Unity第一人称和第三人称视角

第一人称视角

public class FirstView : MonoBehaviour
{
//要相机跟随的GameObject
public Transform m_target;
//鼠标敏度
public float mousesSensity = 10F;

//上下最大视角(Y视角)
public float minYLimit = -20F;
public float maxYLimit = 80F;

Vector3 m_camRotation;
void Update()
{
//根据鼠标的移动,获取相机旋转的角度

m_camRotation.x = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * mousesSensity;

m_camRotation.y += Input.GetAxis("Mouse Y") * mousesSensity;
//角度限制
m_camRotation.y = Mathf.Clamp(m_camRotation.y, minYLimit, maxYLimit);

//相机角度随着鼠标旋转
transform.localEulerAngles = new Vector3(-m_camRotation.y, m_camRotation.x, 0);
transform.position = m_target.position;
}

void Start()
{
// Make the rigid body not change rotation
if (rigidbody)
rigidbody.freezeRotation = true;
}
}


使用方法:摄像机添加改脚本
target:要相机跟随的GameObject(主角Player)
minYLimit方向最小视角

minXLimit方向最大视角

mousesSensity:水平方向和垂直方向鼠标移动速度

第三人称视角

using UnityEngine;
using System.Collections;

public class ThirdView : MonoBehaviour {

public Transform target;
public float distance = 10.0f;

public float xSpeed = 250.0f;
public float ySpeed = 120.0f;

public float yMinLimit = -20.0f;
public float yMaxLimit = 80.0f;

private float x = 0.0f;
private float y = 0.0f;

// Use this for initialization
void Start () {

Vector3 angles = transform.eulerAngles;
x = angles.y;
y = angles.x;

// Make the rigid body not change rotation
if (rigidbody)
rigidbody.freezeRotation = true;

}
void LateUpdate () {
if (target) {
x += Time.deltaTime * Input.GetAxis("Mouse X") * xSpeed;
y -= Time.deltaTime * Input.GetAxis("Mouse Y") * ySpeed;

y = ClampAngle(y, yMinLimit, yMaxLimit);

// var rotation = Quaternion.EulerAngles(y * Mathf.Deg2Rad, x * Mathf.Deg2Rad, 0);
var rotation=Quaternion.Euler(y,x,0);
Vector3 vec = new Vector3(0.0f, 0.0f, -distance);
var position = rotation * vec + target.position;

transform.rotation = rotation;
transform.position = position;
}
}

static float ClampAngle ( float angle, float  min , float max ) {
if (angle < -360)
angle += 360;
if (angle > 360)
angle -= 360;
return Mathf.Clamp (angle, min, max);

}
// Update is called once per frame
void Update () {

}
}


使用方法:摄像机添加改脚本
target:要相机跟随的GameObject(主角Player)
distance:相机距离Tatget的距离(远近镜头调整)
yMinLimit:Y方向最小视角

yMaxLimit:Y方向最大视角

xSpeed:水平方向鼠标移动速度

ySpeed:垂直方向鼠标移动速度
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: