2016-10-05 28 views
-2

在Unity中,我用這個腳本做了一個測試精靈,但是當我跳得快或者隨機時我的角色掉在了地上,但是他在移動時保持慢,但是在跳/快速着陸。我的角色一直在Unity3D中穿過障礙墜落

using UnityEngine; 
using System.Collections; 

public class code : MonoBehaviour { 
//void FixedUpdate() { 
     /*if (Input.GetKey (KeyCode.LeftArrow)) 
     { 
      int Left = 1; 
     } 
     if (Input.GetKey (KeyCode.RightArrow)) 
     { 
      int Right = 1; 
     } 


     if (Input.GetKey(KeyCode.UpArrow)) 
     { 

     } 
     */ 

public float speed1 = 6.0F; 
public float jumpSpeed = 8.0F; 
public float gravity = 20.0F; 
private Vector3 moveDirection = Vector3.zero; 

void FixedUpdate() { 
    CharacterController controller = GetComponent<CharacterController>(); 
    // is the controller on the ground? 
    if (controller.isGrounded) { 
     //Feed moveDirection with input. 
     moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0,  Input.GetAxis("Vertical")); 
     moveDirection = transform.TransformDirection(moveDirection); 
     //Multiply it by speed. 
     moveDirection *= speed1; 
     //Jumping 
     if (Input.GetButton("Jump")) 
      moveDirection.y = jumpSpeed; 

     if (Input.GetKey (KeyCode.UpArrow)) 
      moveDirection.y = jumpSpeed; 

    } 
    //Applying gravity to the controller 
    moveDirection.y -= gravity * Time.deltaTime; 
    //Making the character move 
    controller.Move(moveDirection * Time.deltaTime); 
} 
} 
+1

你是否附加了對撞機到你的地面和你的角色? –

+0

您沒有發佈'CharacterController'的代碼。這是一個問題,因爲它看起來像'isGrounded'沒有正確標記。 – KingDan

+0

@halfer我認爲他的意思是。 – Alox

回答

2

這是每個物理引擎的通病。

物理計算是一個代價高昂的操作,因此無法在每一幀中運行。爲了減少過熱(以降低準確性爲代價),Unity每0.02秒更新一次物理(這個數字是可配置的)。

你可以減少這個數字,但物理引擎過熱越小,它仍然不能保證100%的準確性。要達到100%的準確度,你不應該依賴物理引擎,而應該自己做。

下面是檢查直線飛行的子彈的碰撞的代碼(從我的一個寵物項目中獲取)。

IEnumerator Translate() 
{ 
    var projectile = Projectile.transform; // Cache the transform 
    while (IsMoving) 
    { 
     // Calculate the next position the transform should be in the next frame. 
     var delta = projectile.forward * ProjectileSpeed * Time.deltaTime; 
     var nextPosition = projectile.position + delta; 
     // Do a raycast from current position to the calculated position to determine if a hit occurs 
     RaycastHit hitInfo; 
     if (Physics.Linecast(projectile.position, nextPosition, out hitInfo, CollisionLayerMask)) 
     { 
      projectile.position = hitInfo.point; 
      OnCollision(hitInfo); // Ok, we hit 
     } 
     else projectile.position = nextPosition; // Nope, haven't hit yet 
     yield return null; 
    } 
} 

在你的情況,你只需要做的光線投射時,你的角色開始跳,以確定他是否擊中地面,如果他這樣做,你做的東西,以防止他墜落通過。

+0

如果你不介意可以告訴我的代碼,以阻止他墜落通過謝謝(我是一個結節:/)謝謝! – epic

+0

您是否將「rigidbody」附加到您的角色(與「CharacterController」一起)?如果是這樣的話,你可以刪除它,因爲'CharacterController'可以在沒有'rigidbody'的情況下從Unity 4獨立工作。如果由於某種原因,您無法刪除它,打開'isKinematic'或至少關閉'useGravity'。 https://docs.unity3d.com/Manual/class-Rigidbody.html –