unity3d - 离开区域时平滑改变玩家的速度
问题描述
我试图让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;
}
解决方案
一个简单的解决方案是在退出触发器后逐渐降低更新速度,如下所示:
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
可以处理更改以设置移动行为。
推荐阅读
- python - 使用''temp''变量的原因是什么?
- apache - mysql 在 MAMP 上工作时 Apache 服务器未启动。说开发者无法验证
- flutter - 如何更新列表项的单个值而不是整个列表项
- mongodb - 获取嵌套数组的 $size(长度)并计算与父对象上存储值的差异 - 使用聚合
- c# - AutoMapper ValueFactory 在部署到服务器时尝试访问 Value 属性错误并且在执行了几天后正常
- python - 解码错误:标签中的电线类型错误。| 在 Atom+Hydrogen 中导入 tensorflow
- c# - 反应式将多个可观察对象合并为一个带有布尔值的可观察对象
- node.js - 错误:MERN 中的“User.findOne 不是函数”
- java - JavaFX:从另一个类中启动
- android - EditText TextWatcher 替换为 LiveData