首页 > 解决方案 > 离开区域时平滑改变玩家的速度

问题描述

我试图让special zone位于地面上accelerates the player,进入其中玩家的速度会增加。当他摆脱它时,speed smoothly returns to the original. 但是现在,当玩家离开该区域时,speed instantly becomes the original. 不知道如何实现。请帮忙:)

我的代码:

玩家运动

[SerializeField] private Rigidbody _rigidoby;
    public bool inZone = false;

    private void Update()
    {
        if (inZone == false)
        {
            _rigidoby.velocity = new Vector3(Input.GetAxis("Horizontal") * Time.deltaTime, 0, Input.GetAxis("Vertical") * Time.deltaTime) * 500;
        }
    }

专区

private Vector3 _cachedVelocity;
    private Rigidbody _collisionRigidbody;
    [SerializeField] private PlayerMovement _player;

    private void OnTriggerStay(Collider other)
    {
        _player.inZone = true;

        if (_collisionRigidbody == null)
        {
            _collisionRigidbody = other.GetComponent<Rigidbody>();
            _cachedVelocity = _collisionRigidbody.velocity;
        }

        _collisionRigidbody.velocity = new Vector3(Input.GetAxis("Horizontal") * Time.deltaTime, 0, Input.GetAxis("Vertical") * Time.deltaTime) * 1000;
    }

    private void OnTriggerExit(Collider other)
    {
        _collisionRigidbody.velocity = _cachedVelocity;
        _player.inZone = false;
    }

标签: unity3d

解决方案


一个简单的解决方案是在退出触发器后逐渐降低更新速度,如下所示:

private void OnTriggerExit(Collider other)
{
    //_collisionRigidbody.velocity = _cachedVelocity;
    _player.inZone = false;
}

private void Update()
{
    if (inZone == false)
    {
        _rigidoby.velocity = new Vector3(Input.GetAxis("Horizontal") * Time.deltaTime, 0, Input.GetAxis("Vertical") * Time.deltaTime) * 500;
    } else {
        If (_collisionRigidbody.velocity > _cachedVelocity;)
        _collisionRigidbody.velocity -= 0.01;
    }
}

另一个可能是在您退出触发器时启动协程。

或者,您可以使用Vector3.Lerp并在更新中设置速度变化的百分比,如下所示:

Vector3 _startingSpeedBeforeDeceleration = Vector3.zero;
private void OnTriggerExit(Collider other)
{
    //_collisionRigidbody.velocity = _cachedVelocity;
    _startingSpeedBeforeDeceleration = _collisionRigidbody.velocity;
    _player.inZone = false;
}

float percent = 0f; //from 0 to 1
private void Update()
{
    if (inZone == false)
    {
        _rigidoby.velocity = new Vector3(Input.GetAxis("Horizontal") * Time.deltaTime, 0, Input.GetAxis("Vertical") * Time.deltaTime) * 500;
    } else {
        If (_collisionRigidbody.velocity > _cachedVelocity;) {
            _collisionRigidbody.velocity = Vector3.Lerp(_startingSpeedBeforeDeceleration, _cachedVelocity, percent);
            percent += 0,01f;
        }
    }
}

未调试的代码。请注意,我将离开速度保留在变量_startingSpeedBeforeDeceleration中,这是可选的,并且取决于您想要的运动行为。例如,您可以尝试Vector3.Lerp将第一个参数更改_startingSpeedBeforeDeceleration为固定值,并在每次像这样变化时将刚体速度放在那里Vector3.Lerp(_collisionRigidbody.velocity, _cachedVelocity, percent);,这样您就有一个平滑的开始和平滑的结束,以及在路径中间的最高速度变化. 也percent可以处理更改以设置移动行为。


推荐阅读