好吧,所以我想爲我的2D角色創建一個小衝刺協程。當協同程序調用時,重力關閉,他在一段時間內在兩個速度之間徘徊。這個問題在我的Dash協同程序中,while循環檢查time.time(當前時間)>開始時間+短線持續時間。統一:無限雖然循環在協程
在用Mono調試時,我發現我的變量currentTime在設置後沒有改變,即使我可以清楚地看到while循環運行多次。這使我陷入無限循環。
有什麼建議嗎?
void Update() {
MoveAndJump();
CheckDash();
}
void MoveAndJump(){
if(dashing){
return;
}
Vector2 moveDir = new Vector2 (Input.GetAxisRaw ("Horizontal") * moveSpeed, rb.velocity.y);
rb.velocity = moveDir;
// Consider Switching to an overlap circle based on the actual character graphic. This currently uses a rectangle
// This can also use 4 points to create a more complex box shape. This only works well when using at least about 1 unit size. any smaller and it is innacurate
isGrounded = Physics2D.OverlapArea (groundPoint_right.position, groundPoint_left.position, groundMask);
Debug.Log (isGrounded);
if (Input.GetAxisRaw ("Horizontal") == 1) {
transform.localScale = new Vector3 (1 , 1 * transform.localScale.y, 1* transform.localScale.z);
} else if (Input.GetAxisRaw ("Horizontal") == -1) {
transform.localScale = new Vector3 (-1, 1* transform.localScale.y, 1* transform.localScale.z);
}
if(Input.GetKeyDown(KeyCode.Space) && isGrounded){
rb.AddForce (new Vector2 (0, jumpHeight));
}
}
void CheckDash(){
if(Input.GetKeyDown(KeyCode.W) && !dashing && Time.time > nextdashtime){
dashing = true;
StartCoroutine ("Dash");
}
}
IEnumerator Dash(){
//Before dash loop
rb.gravityScale = 0f;
float startDashTime = Time.time;
float endDashTime = startDashTime + dashDuration;
float currentDashTime;
//Dash Loop
while(Time.time < (startDashTime + dashDuration)){
currentDashTime = Time.time;
// The value to lerp by should be the % that time.time is between start time and end time
rb.velocity = new Vector2 (Mathf.Lerp (startDashSpeed, endDashSpeed, ((currentDashTime - startDashTime)/(endDashTime - startDashTime))),0f);
}
//When dash loop is complete
nextdashtime = Time.time + dashcooldown;
dashing = false;
rb.gravityScale = 1;
yield return null;
}
// FOR CHECKING GROUND CHECK LIMITS
/*void OnDrawGizmos(){
Gizmos.color = Color.red;
Gizmos.DrawLine (groundPoint_left.position, groundPoint_right.position);
}*/
}
在這種情況下,我需要比衝動更多的控制。我需要能夠隨着時間的推移控制速度。 – Prodigle
然後使用剛體的不同過載和受力模式。您也可以嘗試不斷的強制:https://docs.unity3d.com/Manual/class-ConstantForce.html – Aybe