Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Lose score when pass through a collider object

Discussion in '2D' started by varun001, Jun 19, 2017.

  1. varun001

    varun001

    Joined:
    Jun 19, 2017
    Posts:
    2
    Hi
    I am building three types of colliders in my game.
    1. one through which the character would pass but loose x point
    2. one through which he can not pass and has to jump over it
    3. one through which he can not pass but moves when collide with it

    I am able to code 2 and 3 but stuck with 1.
    Please help!
    Screen Shot 2017-06-19 at 3.png
    EDIT : All three colliders have rigibody2d as well to maintain physics or gravity.
     
    Last edited: Jun 20, 2017
  2. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,807
    Make it an object with a Collider set to Trigger. Then use OnTriggerEnter2D(Collider2D other) to detect when the character entered it, and deduct points.
    Code (CSharp):
    1. public class Example : MonoBehaviour {
    2.     public float value;
    3.  
    4.     private void OnTriggerEnter2D(Collider2D other) {
    5.         Player player = other.GetComponent<Player>();
    6.         if(player != null) {
    7.             player.points -= value;
    8.         }
    9.     }
    10. }
    https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnTriggerEnter2D.html
     
    varun001 likes this.
  3. varun001

    varun001

    Joined:
    Jun 19, 2017
    Posts:
    2
    @jeffreyschoch thanks for the reply. But my query is still not solved. I also want my collider to have rigibody2d as well for physics and gravity.
     
  4. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,807
    So you need the player to move through and be detected, but it should also interact with the environment with physics?

    One way would be to give the item one collider and one trigger, then in code use Physics2D.IgnoreCollision(itemCollider, playerCollider) when the item starts. You can give the item script a variable to get a reference to the collider. That way the trigger will still detect the player, but the collider will ignore the player.

    You could also accomplish the same thing with physics layers and making the trigger a child object.
     
    varun001 likes this.