Smoothing Vector3.normalized?

本文关键字:normalized Vector3 Smoothing | 更新日期: 2023-09-27 18:13:49

我在Unity 3D中创建了一个带有角色控制器的玩家,我让他全部配置为行走,环顾四周等。所以当使用法向量时,玩家开始时很平稳,直到达到最大速度。当我没有将它标准化时,你可以通过同时按W和D/A走得更快,你的速度比正常情况快50%。但当我将其归一化时,玩家便会立即处于最大速度。这看起来很奇怪。

我该如何做才能让玩家在达到最大速度之前开始平滑?

这是我的完整脚本,以防你需要它:

using UnityEngine;
using System.Collections;
public class FirstPersonController : MonoBehaviour {
    CharacterController cc;
    public float    baseSpeed = 3.0f;
    public float    mouseSensitivity = 1.0f;
    public bool     inverted = false;
    public bool     gravityOn = true;
    public bool     lockMouse = true;
    float           mouseRotX = 0,
                    mouseRotY = 0;
    float           curSpeed = 3.0f;
    float           invertion = 1.0f;
    float           gravitySpeed = 0;
    string          h = "Horizontal";
    string          v = "Vertical";

    void Start () {
        cc = gameObject.GetComponent<CharacterController>();
        if (lockMouse && Debug.isDebugBuild)
            Screen.lockCursor = true;
        if (!Debug.isDebugBuild)
            Screen.lockCursor = true;
    }
    void FixedUpdate () {
        curSpeed = baseSpeed;
        if (inverted)
            invertion = -1.0f;
        else
            invertion = 1.0f;
        mouseRotX = Input.GetAxis("Mouse X") * mouseSensitivity;
        mouseRotY -= invertion * Input.GetAxis("Mouse Y") * mouseSensitivity;;
        mouseRotY = Mathf.Clamp(mouseRotY, -90.0f, 90.0f);
        float forwardMovement = Input.GetAxis(v);
        float strafeMovement = Input.GetAxis(h);
        Vector3 speed = new Vector3(strafeMovement, 0, forwardMovement);
        speed = transform.rotation * speed;
        Debug.Log(speed.normalized);
        //Applying Gravity
        if (cc.isGrounded)
        {
            gravitySpeed = 0.0f;
        }
        else if (gravityOn)
        {
            if (gravitySpeed >= 20.0f)
            {
                gravitySpeed = 20.0f;
            }
            if (cc.isGrounded == false)
            {
                gravitySpeed += Physics.gravity.y * Time.deltaTime;
            }
            cc.Move(new Vector3(0, gravitySpeed, 0) * Time.deltaTime);
        }
        //Applying movement and rotation.
        cc.Move(speed.normalized * curSpeed * Time.deltaTime);
        transform.Rotate(0, mouseRotX, 0);
        Camera.main.transform.localRotation = Quaternion.Euler(mouseRotY, 0 ,0); 
    }
}

Smoothing Vector3.normalized?

您想获得的功能是均匀加速运动

你需要这样写:

Vector3 _speed = Vector3.zero;
const float KDrag = 0.25f;
void FixedUpdate () 
{
float forwardMovement = Input.GetAxis(v);
float strafeMovement = Input.GetAxis(h);
Vector3 acceleration = cc.transform.right * strafeMovement + cc.transform.forward * forwardMovement;
_speed += acceleration * Time.fixedDeltaTime;
_speed -= _speed * KDrag * Time.fixedDeltaTime;
cc.Move( _speed  * Time.fixedDeltaTime );
}