2016-10-05 26 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 –