[英]Unity C# check if player (Rigidbody2D) stopped moving for x seconds
我正在編寫腳本,因此可以檢測到玩家何時不移動x秒鍾,並相應地加載另一個場景。
如果玩家在x秒后再次開始移動,則不應調用加載另一個場景。
我試過使用isSleeping函數,並通過在WaitForSeconds中包含Coroutine來延遲它,但它仍在每幀檢查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將在行消失后繼續繼續移動。
嘗試這個
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;
}
}
您可以嘗試一下...我現在無法測試,因此可能需要一些調整...
首先是一些私有變量:
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.