[英]Unity C# check if player (Rigidbody2D) stopped moving for x seconds
I'm working on a script, so I could detect when player is not moving for x seconds and load another scene accordingly. 我正在编写脚本,因此可以检测到玩家何时不移动x秒钟,并相应地加载另一个场景。
If player started moving again after x seconds, then loading another scene should't be called. 如果玩家在x秒后再次开始移动,则不应调用加载另一个场景。
I've tried using isSleeping function and delay it by including Coroutine with WaitForSeconds but it is still checking Rigidbody2D every frame. 我试过使用isSleeping函数,并通过在WaitForSeconds中包含Coroutine来延迟它,但它仍在每帧检查Rigidbody2D。 Is there any other way to check if Rigidbody2D hasn't moved for x seconds and only then load game over level, otherwise continue moving as before?
还有其他方法可以检查Rigidbody2D是否没有移动x秒,然后才将游戏加载到关卡之上,否则继续像以前一样移动吗?
using UnityEngine;
using System.Collections;
public class PlayerStop : MonoBehaviour {
void Update() {
if (GetComponent<Rigidbody2D>().IsSleeping()) {
Application.LoadLevel(2);
}
}
}
In addition I have a script, which enables me to draw lines (with mouse) and stop player's movement, however lines disappear after x seconds. 此外,我还有一个脚本,可以使用鼠标绘制线条并停止玩家的移动,但是线条会在x秒后消失。 So for example if I'd set lines to disappear after 1 second, I would like to check if Rigidbody2D stopped moving for 2 seconds and only then load game over scene.
因此,例如,如果我将线条设置为在1秒后消失,那么我想检查Rigidbody2D是否停止移动2秒钟,然后才将游戏加载到场景中。 Otherwise do nothing as Rigidbody2D will continue moving again after line disappears.
否则请不要执行任何操作,因为Rigidbody2D将在行消失后继续继续移动。
Try this 尝试这个
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;
}
}
You could try this...I'm not able to test this right now, so may need a little tweaking... 您可以尝试一下...我现在无法测试,因此可能需要一些调整...
First some private variables: 首先是一些私有变量:
private float _loadSceneTime;
private Vector3 _lastPlayerPosition;
private float _playerIdleDelay;
And in the Update
method check if the player has moved: 然后在
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.