在unity3d中,我有一个球员以一定的速度不断向前移动,我只控制它的左或右位置。我希望我的玩家在遇到一个对象并启用触发器时立即加快速度。
这是我试过的,但它似乎不能正确地工作。有什么想法吗?
void Update ()
{
GetComponent<Rigidbody>().velocity = new Vector3(Input.GetAxisRaw("Horizontal") * 4, 0, horizVel);
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "SpeedUp")
{
GetComponent<Rigidbody>().velocity = new Vector3(Input.GetAxisRaw("Horizontal") * 4, 0, horizVel * 10.0f);
}
}horizVel是速度设置为10的一个公共变量。
发布于 2018-05-31 10:06:56
似乎是因为您已经硬编码了速度变量OnTriggerEnter方法,而不是更新它。
更新被称为一次帧。如果您的horizVel设置为10,它将以每帧10次的速度移动。
当您点击OnTriggerEnter时,您的horizVel会更新为以前的10倍,即: 100。
但是,因为您还没有更新您的速度变量,所以当您回到Update方法时,您的horizVel将再次在10点返回。
我觉得你应该尝试的是:
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "SpeedUp")
{
horizVel *= 10f;
}
}这样,你的速度变量将保持在以前的10倍,而不仅仅是碰撞时期。
编辑“我试过了,但速度仍然提高,不仅在碰撞期间”
然后,您可以使用coroutine将速度变量重新设置为其原始值:
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "SpeedUp")
{
horizVel *= 10f;
StartCoroutine(ResetSpeedAfterTime(5f));
}
}
// Resets the speed variable back to the original value after a set amount of time
private IEnumerator ResetSpeedAfterTime(float time)
{
yield return new WaitForSeconds(time);
horizVel = 10f; // the original speed value;
}发布于 2018-05-31 09:51:08
虽然我是C#的初学者,我的答案可能不正确,但你是否尝试过给游戏对象分配一个id,以便加速字符的速度,然后在语句中调用它
if (other.gameObject.tag == "SpeedUp")
这可能是因为发动机无法计算碰撞发生的确切时刻。
发布于 2018-05-31 10:48:42
如果你只想在你的对象在触发范围内的时候提高速度,你可以在你的角色离开对撞机后逆转速度。
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "SpeedUp")
{
horizVel *= 10f;
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == "SpeedUp")
{
horizVel /= 10f;
}
}https://stackoverflow.com/questions/50621334
复制相似问题