How to prevent colliders from passing through each other?

后端 未结 8 1415
天命终不由人
天命终不由人 2020-12-04 20:23

I am having trouble keeping game objects inside of a contained space. When they reach the edge, there is some momentary push back but then they will go right through the wal

8条回答
  •  抹茶落季
    2020-12-04 20:54

    Collision with fast-moving objects is always a problem. A good way to ensure that you detect all collision is to use Raycasting instead of relying on the physics simulation. This works well for bullets or small objects, but will not produce good results for large objects. http://unity3d.com/support/documentation/ScriptReference/Physics.Raycast.html

    Pseudo-codeish (I don't have code-completion here and a poor memory):

    void FixedUpdate()
    {
        Vector3 direction = new Vector3(transform.position - lastPosition);
        Ray ray = new Ray(lastPosition, direction);
        RaycastHit hit;
        if (Physics.Raycast(ray, hit, direction.magnitude))
        {
            // Do something if hit
        }
    
        this.lastPosition = transform.position;
    }
    

提交回复
热议问题