Unity3D第三人称视角DEMO(相机跟随)

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");
            }
  
  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值