How to disable collision between the player and the picked up object?

Viewed 46

I disabled collision between the player and the pickable objects to prevent jitteriness whenever the picked-up object is colliding with the player while moving.

 public void BreakConnection()

    {
        pickupRB.constraints = RigidbodyConstraints.None;

        currentlyPickedUpObject = null;

        lookObject = null;

        physicsObject.pickedUp = false;

        currentDist = 0;

        Physics.IgnoreLayerCollision(layer1, layer2, false);
    }

    public void PickUpObject()
    {
        Physics.IgnoreLayerCollision(layer1, layer2, true); 

        physicsObject = lookObject.GetComponentInChildren<PhysicsObjects>();

        currentlyPickedUpObject = lookObject;

        // currPicked = true;  

        pickupRB = currentlyPickedUpObject.GetComponent<Rigidbody>();

        pickupRB.constraints = RigidbodyConstraints.FreezeRotation;

        physicsObject.playerInteractions = this;

       
    }

I tried this Physics.IgnoreLayerCollision(layer1, layer2, true); when the object is picked up and Physics.IgnoreLayerCollision(layer1, layer2, false); when it is realised.

However, it is causing unwanted behaviour with other pickable objects. Is there a way to ONLY disable collision between the currentlyPickedUpObject and the player? not all the pickable objects? I need currentlyPickedUpObject to collide with all other objects except the player. please help.

2 Answers

Instead of changing whether layers can affect each other, change the layer of the object, you want to pick up, to another one, which never affects player's layer (as you have done by code or in collision layer matrix).

If your objects are on some important layer (let's say pickable), you could always duplicate your layer (pickableIgnorePlayer). If you have a lot of checks for layers in your code that can be a little tedious, but at the moment I can't see another way (maybe besides implementing own collisions for items).

To change layer of an object simply access gameObject's layer gameObject.layer = layerIndex. You can also use layer's name. You don't need to destroy layers (I'm not sure if you even can). What you probably mean is to change layer back to the original, which you do the same way, which is accessing gameObject.layer.

By duplicating layer I mean adding the new layer in the layers tab with the altered name and then making changes to your code if necessary. For eg. if your code was checking if layer was pickable, now check if layer is pickable or pickableIgnorePlayer if needed.

With the collision matrix you can define by layer with layers collide with which. Check: https://docs.unity3d.com/Manual/LayerBasedCollision.html You can change the layer at runtime so that you set your object to another interaction state, where the layer of the object and the player will not interact anymore, like so: gameObject.layer = 8;

Related