0

i have a function that looks like this:

private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.name == "Despawner")
    {
        Destroy(this.gameObject);
    }
    if (collision.gameObject.name == "Char")
    {
        Destroy(this.gameObject);
        ScoreHandler.coinsCollected++;
    }
}

Basically what i want is if the coin is colliding with the player, i want the coin to be removed, but also remove the physical effects from the collision, so my if i jump to the coin from below, my character won't fall back to the ground, it just goes over it and removes it like if he would have collected it.

I also tried changing OnCollisionEnter2D to OnTriggerEnter2D but didn't get it working.

Edit: I changed to OnTriggerEnter2D from OnCollisionEnter2D. now the character goes through the coins but doesn't pick them up, like if there is no collision at all, also checked the IsTrigger in the Editor for the GameObject.

Kalip
  • 151
  • 1
  • 11
  • 2
    Sounds like you want to use a `Trigger` which is as simple as using the OnTrigger Functions instead of the OnCollision Functions, and clicking the Trigger check box on the collider. – AresCaelum Dec 06 '18 at 18:51
  • 1
    I talk a bit about the differences between triggers and colliders here: https://stackoverflow.com/questions/53208857/how-to-make-my-button-change-on-collision/53209235#53209235 – AresCaelum Dec 06 '18 at 18:52

2 Answers2

0

You should be able to detect the collision and ignore it. I do something similar with projectiles which will overlap and bounce off each other sometimes.

private void OnCollisionEnter2D(Collision2D collision) // or OnCollisionStay2D
{
    Physics2D.IgnoreCollision (this.gameObject.GetComponent<Collider2D> (), collision.gameObject.GetComponent<Collider2D> ());
    Destroy(this.gameObject);
    ScoreHandler.coinsCollected++;
}
A3mercury
  • 166
  • 1
  • 7
  • My character still can't jump through the coins from below: https://gyazo.com/964163e2b4c40ea27ba254b2386ee35f You can see it at the last second, but also the character moves on top of the coins till it gets destroyed – Kalip Dec 06 '18 at 18:57
0

I had to use a Trigger, instead of a Collision and its worked.

private void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.gameObject.name == "Despawner")
    {
        Destroy(this.gameObject);
    }
    if (collision.gameObject.name == "Char")
    {
        Destroy(this.gameObject);
        ScoreHandler.coinsCollected++;
    }
}
Kalip
  • 151
  • 1
  • 11