简体   繁体   中英

Due to collision checking, my Unity character is occasionally falling through the floor. What can I do to fix this?

I have a basic 2D-oriented Character Controller - custom, that I'm writing for a 2.5D game with 3D models (Therefore I can't use the Unity2D physics and collision volumes).

My controller mostly works, however I'm hitting a strange little issue where every so often - apparently at a certain speed - it skips the collision check and falls through the floor or platform. Can someone spot what I'm doing wrong?

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;
        }
    }
}

}

First, you can attach Box Collider 2D and Rigidbody 2D to 3D models. Try it.

Are you sure you need a custom character controller? CharacterController.Move (or SimpleMove ) does collision detection for you.

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

Alternatively, since you are using Rigidbodies, you should consider using ApplyForce or adding velocity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM