Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
554 views
in Technique[技术] by (71.8m points)

unity3d - How can I prevent non-trigger colliders from pushing each other in Unity?

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?

question from:https://stackoverflow.com/questions/65914130/how-can-i-prevent-non-trigger-colliders-from-pushing-each-other-in-unity

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...