由于碰撞检查,我的Unity角色偶尔会掉进地板。我该怎么做才能解决这个问题?

时间:2015-04-30 23:29:05

标签: c# unity3d

我有一个基本的面向2D的角色控制器 - 自定义,我正在为具有3D模型的2.5D游戏编写(因此我不能使用Unity2D物理和碰撞卷)。

我的控制器大部分都在工作,但是我经常遇到一个奇怪的小问题 - 显然是以一定的速度 - 它会跳过碰撞检查并掉到地板或平台上。有人能发现我做错了吗?

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour
{
public float PlayerSpeed;
public float JumpPower;
public float _Gravity = 9.89f;

public Vector3 Flip = Vector3.zero;
private Vector3 MoveDirection = Vector3.zero;

private bool FacingLeft = false;
private bool FacingRear = false;
public bool GroundContact = false;

private Rigidbody RigidBody;

private void Awake()
{
    RigidBody = GetComponent<Rigidbody>();
}

private void Update()
{
    DetectionRays();
    MoveDirection.x = PlayerSpeed * Input.GetAxis("Horizontal");
    if (GroundContact) {

        MoveDirection.y = 0;
        if (Input.GetButtonDown("Jump")) {

            MoveDirection.y = JumpPower;
        }
    } else {

        MoveDirection.y -= _Gravity * Time.deltaTime;
    }

    Vector3 movementVector = new Vector3(MoveDirection.x * Time.deltaTime, MoveDirection.y * Time.deltaTime, 0);
    transform.Translate(movementVector);
}

private void DetectionRays()
{
    DetectDown();
}


private void OnCollisionEnter(Collision Collide)
{
    if (Collide.transform.tag == "Ground")
    {
        GroundContact = true;
    }
}

private void DetectDown()
{
    RaycastHit Obsticle;
    Vector3 RayDownPosit = transform.position;
    RayDownPosit.y += 0.8f;
    Ray RayDown = new Ray(transform.position, Vector3.down);
    Debug.DrawRay(RayDownPosit, Vector3.down, Color.red, 0.05f, false);
    GroundContact = false;
    if (Physics.Raycast(RayDown, out Obsticle, 0.05f))
    {
        if (Obsticle.transform.tag == "Ground")
        {
            GroundContact = true;
        }
    }
}

}

1 个答案:

答案 0 :(得分:0)

首先,您可以将Box Collider 2D和Rigidbody 2D附加到3D模型。试试吧。

您确定需要自定义角色控制器吗? CharacterController.Move(或SimpleMove)会为您进行碰撞检测。

http://docs.unity3d.com/ScriptReference/CharacterController.Move.html

或者,由于您使用的是刚体,因此应考虑使用ApplyForce或添加速度。