100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > 基于Unity实现第三人称移动旋转以及视角控制

基于Unity实现第三人称移动旋转以及视角控制

时间:2019-08-02 00:10:52

相关推荐

基于Unity实现第三人称移动旋转以及视角控制

罗老师的代码:

主角控制代码

using System.Collections;using System.Collections.Generic;using UnityEngine;public class ThirdPlayerMove : MonoBehaviour{float h; //水平轴系数float v; //垂直轴系数public float speed = 6;//速度public float turnSpeed = 15;//旋转速度public Transform camTransform; //相机Vector3 camForward; //临时三维坐标// Update is called once per framevoid Update(){Move();}void Move(){h = Input.GetAxis("Horizontal");v = Input.GetAxis("Vertical");transform.Translate(camTransform.right * h * speed * Time.deltaTime + camForward * v * speed * Time.deltaTime , Space.World);//水平垂直方向系数不为0表示需要进行旋转if (h != 0 || v != 0){Rotating(h, v);}}//旋转void Rotating(float hh, float vv){camForward = Vector3.Cross(camTransform.right, Vector3.up);Vector3 targetDir = camTransform.right * hh + camForward * vv;Quaternion targetRotation = Quaternion.LookRotation(targetDir, Vector3.up);transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, turnSpeed * Time.deltaTime);}}

镜头移动代码

using System.Collections;using System.Collections.Generic;using UnityEngine;public class Camera360 : MonoBehaviour{public Transform target; //相机追随目标public float xSpeed = 200; //X轴方向拖动速度public float ySpeed = 200; //Y轴方向拖动速度public float mSpeed = 10; //放大缩小速度public float yMinLimit = -50; //在Y轴最小移动范围public float yMaxLimit = 50; //在Y轴最大移动范围public float distance = 10; //相机视角距离public float minDinstance = 2; //相机视角最小距离public float maxDinstance = 30; //相机视角最大距离public float x = 0.0f;public float y = 0.0f;public float damping = 5.0f;public bool needDamping = true;// Start is called before the first frame updatevoid Start(){Vector3 angle = transform.eulerAngles;x = angle.y;y = angle.x;}// Update is called once per framevoid LateUpdate(){if (target){if (Input.GetMouseButton(1)){x += Input.GetAxis("Mouse X") * xSpeed * 0.02f;y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;y = ClamAngle(y, yMinLimit, yMaxLimit);}distance -= Input.GetAxis("Mouse ScrollWheel") * mSpeed;distance = Mathf.Clamp(distance, minDinstance, maxDinstance);Quaternion rotation = Quaternion.Euler(y, x, 0.0f);Vector3 disVector = new Vector3(0.0f, 0.0f, -distance);Vector3 position = rotation * disVector + target.position;if (needDamping){transform.rotation = Quaternion.Lerp(transform.rotation, rotation, Time.deltaTime * damping);transform.position = Vector3.Lerp(transform.position, position, Time.deltaTime * damping);}else{transform.rotation = rotation;transform.position = position;}}}/// <summary>/// 限制某一轴移动范围/// </summary>/// <param name="angle"></param>/// <param name="min"></param>/// <param name="max"></param>/// <returns></returns>static float ClamAngle(float angle, float min, float max){if (angle < -360){angle += 360;}if(angle > 360){angle -= 360;}return Mathf.Clamp(angle, min, max);}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。