Third Person User Control
Introduction
在游戏开发中,角色控制模块是必不可少的。经典的第三人称视角就是被广泛应用的一项设计。这个Demo主要是针对Unity3D下第三人称视角模型(相机跟随)的一个简单实现,记录一下实现的过程与核心代码。
Idea
- 在Unity3D中导入一个人物模型,并创建一个可供人物活动的Terrain
- 调整摄像机至正确的视角(初始处于人物背后)
- 设置InputManager按键传值等基本属性,如W、A、S、D、Jump、Crouch等基本动作
- 导入或创建人物动作动画,并设定相应的Animator
- 编写脚本响应按键,实现的主要思路就是当人物移动时获取人物当前的朝向向量,归一化后乘速度得到人物前进的Vector3,之后再根据设定的转向速度将摄像机向量绕人物进行旋转(Z不变),并将人物朝向向量进行旋转得到转向向量,将转向向量与前进向量相加,即得到这一帧人物的移动向量,根据移动向量进行人物与摄像机的Transform即可。
- 在移动时绑定人物动画
Code
// Controll.cs
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
namespace UnityStandardAssets.Characters.ThirdPerson
{
[RequireComponent(typeof (ThirdPersonCharacter))]
public class ThirdPersonUserControl : MonoBehaviour
{
private ThirdPersonCharacter m_Character; // A reference to the ThirdPersonCharacter on the object
private Transform m_Cam; // A reference to the main camera in the scenes transform
private Vector3 m_CamForward; // The current forward direction of the camera
private Vector3 m_Move;
private bool m_Jump; // the world-relative desired move direction, calculated from the camForward and user input.
private void Start()
{
if (Camera.main != null)
{
m_Cam = Camera.main.transform;
}
else
{
Debug.LogWarning(
"Warning: no main camera found. Third person character needs a Camera tagged \"MainCamera\", for camera-relative controls.", gameObject);
}
// get the third person character ( this should never be null due to require component )
m_Character = GetComponent<ThirdPersonCharacter>();
}
private void Update()
{
if (!m_Jump)
{
m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
}