My object compenetrates with ground when I use 2D raycast for collision

Viewed 107

Basicaly my problem is that my object compenetrates with ground when I use 2D raycast for to check collision with ground, because fall's velocity is too big. I tried to fix the problem, but I couldn't, following my code:

public class PlayerMove : MonoBehaviour
{
    Transform _tr;
    [SerializeField]
    float speed = 4;
    [SerializeField]
    float gravity = 9.81f;
    [SerializeField]
    LayerMask mask;
    float xAxe;
    void Awake()
    {
        _tr = GetComponent<Transform>();
    }
    void Update()
    {
       xAxe = Input.GetAxis("Horizontal");
       _tr.position += Vector3.right * xAxe * speed * Time.deltaTime;
    }
    void FixedUpdate()
    {
        RaycastHit2D hit = Physics2D.Raycast(_tr.position + (Vector3.down / 2), Vector3.down, 0,mask);
        if (hit.collider == null)
        {
            //Continue to fall
            _tr.position += -Vector3.up * gravity * Time.fixedDeltaTime; //Gravity force
        }
        else
        {
            //STOP!
        }
    } 
}

Following an image of problem:

Compenetration with the floor

Thanks everyone !

1 Answers

Your problem is as the speed increases, your object goes from the raycast missing in one physics step, to your object intersecting in the next.

You could fix this by trying to implement your own continuous collision detection...

But why re-invent the wheel? Unity already provides collision detection using colliders, I would recommend adding one of these to your object, setting it's collision mode to continuous, and perhaps using a rigidbody to control the physics movement for you also.

Related