2
votes

I got pre-made projectiles from the Unity's asset store and couldn't figure out a way to make them work my intended way.

The projectiles have colliders (not triggers), rigidbody and a script that moves them by .velocity. It detects a collision using OnCollisionEnter, making them push objects that have rigidbodies (behavior not wanted).

I could indeed use OnTriggerEnter, but the projectile spawns particles using the ContactPoint from the OnCollisionEnter method that OnTriggerEnter doesn't have access to. I tried to simulate this ContactPoint using raycasts, but no luck. Could rewrite the code from scratch, but only if there's no other way...

There's this video where the guy has the same setup as my projectile, rigidbody and collider, yet, the projectile doesn't push the other object, but he doesn't go deeper on its behavior.

Any ideas?

2

2 Answers

0
votes

You'll need to keep the velocity, angular velocity, and position every frame, then add some code to OnCollisionEnter in which you tell the two colliders to ignore each other from now on, and also restore the projectile's original velocity, angular velocity and position.

    private Collider col;
    private Rigidbody rigidBody;
    private Vector3 vel;
    private Vector3 angularVel;
    private Vector3 position;

    private void Start() {
        col = gameObject.GetComponent<Collider>();
        rigidBody = gameObject.GetComponent<Rigidbody>();
    }

    private void FixedUpdate() {
        vel = rigidBody.velocity;
        angularVel = rigidBody.angularVelocity;
        position = transform.position;
    }

    private void OnCollisionEnter(Collision collision) {
        Physics.IgnoreCollision(col, collision.collider);
        rigidBody.velocity = vel;
        rigidBody.angularVelocity = angularVel;
        transform.position = position;
    }
0
votes

In Edit -> Project Settings -> Physics, you will find the Layer Collision Matrix at the bottom. Here you can choose which layers collide with which layers. The default layer for gameobjects is "Default". Assign a new layer to your projectiles and the gameobjects you don't want collisions with. Then you can uncheck the box that represents these two layers in the Layer Collision Matrix. Now these gameobjects will not affect each other when colliding and methods like OnCollisionEnter will not be called for them. Hope this answers your question fully.