Share a third-person movement with a completely free perspective. The effect is as follows:
first step:
Create a character and a camera. The character will be equipped with a movement script, and the camera will be equipped with a perspective control script:
Step two:
Write a movement script to drag the camera into cameraTrans:
public class PlayerMove : MonoBehaviour
{
private CharacterController _player;
//移动
public float moveSpeed;
private float _horizontal, _vertical;
private Vector3 _direction;
public Transform cameraTrans;
public float turnSmoothTime = 0.1f;
private float _turnSmoothVelocity;
private void Awake()
{
_player = GetComponent<CharacterController>();
}
private void Update()
{
MoveByKey();
}
private void MoveByKey()
{
//获取按键
_horizontal = Input.GetAxis("Horizontal");
_vertical = Input.GetAxis("Vertical");
_direction = new Vector3(_horizontal, 0f, _vertical);
if (_direction.magnitude >= 0.1f)
{
float targetangle = Mathf.Atan2(_direction.x, _direction.z) * Mathf.Rad2Deg + cameraTrans.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetangle, ref _turnSmoothVelocity, turnSmoothTime);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
Vector3 moveDir = Quaternion.Euler(0f, targetangle, 0f) * Vector3.forward;
Vector3 moveDir1 = moveDir * moveSpeed * Time.deltaTime;
_player.Move(moveDir1);
}
}
}
third step:
Write a camera movement script and press the right mouse button to rotate the perspective:
public class CameraControl : MonoBehaviour
{
public Transform player; //相机追随目标
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;
void Start()
{
Vector3 angle = transform.eulerAngles;
x = angle.y;
y = angle.x;
}
void LateUpdate()
{
if (player)
{
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 + player.position;
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);
}
}
Finally, if this article helped you, please give it a like!