0
\$\begingroup\$

Still a Beginner at Unity 5 and this time I am trying to make a Spring.

The spring would act as you'd expect. Something comes in with a direction and force, so you bounce it the opposite direction of the way it came in. Something like this:

enter image description here

But for some reason my player object doesn't interact with my Spring. It goes right through it as if they are on separate layers.

enter image description here

As you see above it falls right through. Now here is my setup:

enter image description here

Finally the Spring Script:

using UnityEngine;
using System.Collections;

public class BounceOnContact : MonoBehaviour
{
    void OnCollisionEnter2D(Collision2D collisionInfo)
    {
        Rigidbody2D rBody = collisionInfo.collider.GetComponent<Rigidbody2D>();
        Vector2 vel = rBody.velocity;
        float mag = vel.magnitude;
        rBody.AddForce(Vector2.Reflect(vel, collisionInfo.contacts[0].normal) * mag, ForceMode2D.Impulse);
    }
}

I'm not really sure what I'm missing. The player object should hit my spring right?

\$\endgroup\$
1
\$\begingroup\$

Your Spring object's BoxCollider2D has the Is Trigger box checked, which means that you need to check for collisions with OnTriggerEnter2D, rather than OnCollisionEnter2D.

\$\endgroup\$
  • \$\begingroup\$ But then I lose the contacts[0].normal part that I'd get from Collision2D. Can I get that some other way by having a Collider2D? \$\endgroup\$ – OmniOwl Mar 21 '16 at 0:03
  • \$\begingroup\$ @Vipar No, not directly. Why not just uncheck Is Trigger and use OnCollisionEnter2D then? It should work. \$\endgroup\$ – Nox Mar 21 '16 at 0:08
  • 1
    \$\begingroup\$ I don't know entirely how these things work, which is why I ask :P I'm still at a beginner level :) But yeah that seemed to do it. Now to adjust. Thanks. \$\endgroup\$ – OmniOwl Mar 21 '16 at 0:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.