【问题标题】:Unity C# check if player (Rigidbody2D) stopped moving for x secondsUnity C#检查玩家(Rigidbody2D)是否停止移动x秒
【发布时间】:2015-08-26 22:19:52
【问题描述】:

我正在编写一个脚本,因此我可以检测到玩家何时没有移动 x 秒并相应地加载另一个场景。

如果玩家在 x 秒后再次开始移动,则不应调用加载另一个场景。

我尝试过使用 isSleeping 函数并通过包含协程和 WaitForSeconds 来延迟它,但它仍在每帧检查 Rigidbody2D。有没有其他方法可以检查 Rigidbody2D 是否在 x 秒内没有移动,然后才加载游戏过关,否则继续像以前一样移动?

 using UnityEngine;
 using System.Collections;

 public class PlayerStop : MonoBehaviour {


     void Update() {

         if (GetComponent<Rigidbody2D>().IsSleeping()) {
             Application.LoadLevel(2);
         }
     }
 }

此外,我还有一个脚本,可以让我画线(用鼠标)并停止玩家的移动,但是线会在 x 秒后消失。因此,例如,如果我将线条设置为在 1 秒后消失,我想检查 Rigidbody2D 是否停止移动 2 秒,然后才加载游戏结束场景。否则什么都不做,因为 Rigidbody2D 将在线条消失后继续移动。

【问题讨论】:

  • 可能在每一帧上,都可以查看上一帧的坐标。继续此操作 x 秒,如果之前的坐标与所有帧中的当前坐标相同,则进入下一级

标签: c# unity3d


【解决方案1】:

试试这个

using UnityEngine;
using System.Collections;

public class PlayerStop : MonoBehaviour {

    float delay = 3f;
    float threshold = .01f;

    void Update() {

        if (GetComponent<Rigidbody2D>().velocity.magnitude < threshold * threshold)
            StartCoRoutine("LoadTheLevel");
    }

    IEnumerator LoadTheLevel()
    {
        float elapsed = 0f;

        while (GetComponent<Rigidbody2D>().velocity.magnitude < threshold * threshold)
        {
            elapsed += Time.deltaTime;
            if(elapsed >= delay)
            {
                Application.LoadLevel(2);
                yield break;
            }
            yield return null;
        }
        yield break;
    }
}

【讨论】:

  • 非常感谢,它似乎工作正常,只需要更新“StartCoroutine”
  • @Dixevil 嗨,如果它解决了您的问题,请不要忘记接受答案 - 这样,网站上的其他用户就会知道该问题已成功回答。
【解决方案2】:

你可以试试这个...我现在无法测试这个,所以可能需要稍微调整一下...

首先是一些私有变量:

private float _loadSceneTime;
private Vector3 _lastPlayerPosition;
private float _playerIdleDelay;

然后在Update 方法中检查玩家是否移动了:

private void Update()
{
    //  Is it time to load the next scene?
    if(Time.time >= _loadSceneTime)
    {
        //  Load Scene
    }
    else
    {
        //  NOTE: GET PLAYERS POSITION...THIS ASSUMES THIS 
        //  SCRIPT IS ON THE GAME OBJECT REPRESENTING THE PLAYER
        Vector3 playerPosition = this.transform.position;

        //  Has the player moved?
        if(playerPosition != _lastPlayerPosition)
        {
            //  If the player has moved we will attempt to load 
            //  the scene in x-seconds
            _loadSceneTime = Time.time + _playerIdleDelay;
        }

        _lastPlayerPosition = playerPosition;
    }
}

【讨论】:

  • 您好,感谢您的解决方案。它正在工作,但到了弹出游戏结束场景的地步。我那里有重新启动级别按钮,它具有重新启动上一个场景的功能。一旦我点击按钮,它会立即再次加载游戏结束场景。
猜你喜欢
  • 1970-01-01
  • 2022-10-24
  • 1970-01-01
  • 2020-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多