Unity 学习笔记-3D 游戏制作

208 阅读2分钟

角色操控

CharacterController

Move:移动

public float moveSpeed = 1f;
public CharacterController charCtrl;
private Vector3 direction = new Vector3();

void Update()
{
    Move();
}
void Move()
{
    float h = Input.GetAxis("Horizontal");
    float v = Input.GetAxis("Vertical");
    direction.Set(h, 0, v);
    
    charCtrl.Move(direction * moveSpeed * Time.deltaTime);
}

视角跟随

Cinemachine

FreeLook

  • Follow和LookAt设置为要跟随的角色
  • Orbits-BindingMode 改为World Space
  • 调整Orbits下TopRig、MiddleRig和BottomRig至合适数值
  • Axis Control下调整各轴的Invert和speed

角色转向及移动

  • 先得到输入朝向
void Move()
{
    float h = Input.GetAxis("Horizontal");
    float v = Input.GetAxis("Vertical");
    input.Set(h, v);

    if (input.magnitude <= 0.1)
        return;
        
    direction.Set(h, 0, v);
}

固定视角

image_Yv-daDYRzF.png

void Move()
{
    // ...
    // 移动
    transform.position += moveSpeed * direction.normalized * Time.deltaTime;
    // 插值改变朝向
    transform.forward = Vector3.Slerp(transform.forward, direction, rotateSpeed * Time.deltaTime);
}

鼠标控制视角

image_ZaBB0of1GC.png

  • 摄像机朝向需参与计算
void Move()
{
    // ...
    // 1、让角色旋转至正确角度
    // 输入的角度
    float inputDeg = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg;
    // 目标角度:输入角度+摄像机角度
    float targetDeg = inputDeg + cam.transform.eulerAngles.y;
    // 计算平滑角度(让转向更加平滑)
    float deg = Mathf.SmoothDampAngle(
        transform.eulerAngles.y,
        targetDeg,
        ref smoothTurnDeg,
        turnTime
        );
    transform.rotation = Quaternion.Euler(0, deg, 0);

    // 2、以正确角度移动
    // 计算移动方向并移动
    Vector3 moveDir = Quaternion.Euler(0, targetDeg, 0) * Vector3.forward;
    charCtrl.Move(moveDir * moveSpeed * Time.deltaTime);
}

光标处理

  • 将光标锁定在屏幕中间并隐藏
private void SetCursorLockState(bool IsLock = false)
{
    Cursor.lockState =
        IsLock ? CursorLockMode.Locked : CursorLockMode.Confined;
    Cursor.visible = !IsLock;
}

动画控制

创建角色Avatar

  • 在模型的导入设置中(对应fbx资源的Inspector面板),确保 “Rig” 选项卡下的 “Animation Type” 设置为 “Humanoid”(如果是人类角色)
  • 下面“Avatar Definition”选择“Create From This Model”

动画切换

animator.CrossFade(动画状态名, 过渡时间);

根运动

  • 是否应用动画的根运动:Animator - Apply Root Motion
  • 启用的话,注意Animator得添加在对象的根节点上

动画事件

  • 事件相关的数据(回调、参数)是跟资源绑定的
  • 要显示事件参数的话,得先在Project面板中选中动画资源,然后在Animation面板中选中帧事件

image_pQR7QfuFEG.png

  • 只能接收0个或1个参数,如果想处理多个参数的话,得用AnimationEvent
void CharacterCanMove(AnimationEvent evt)
{
    // evt.intParameter, evt.floatParameter
    // evt.stringParameter, evt.objectReferenceParameter
}

寻路

AI Navigation

  • 通过Package Manager安装
  • 在Window - AI 下打开面板
  • 旧版:点击Bake进行烘焙

角色对象设置:

  • 添加Nav Mesh Agent组件
  • 常用接口
// 是否停止寻路
agent.isStopped = true/false;
// 设置目标位置
agent.SetDestination(targetPos);