Search Unity

How can I make a trigger in 2d

Discussion in 'Scripting' started by Badpig_Studios, Jul 12, 2021.

  1. Badpig_Studios

    Badpig_Studios

    Joined:
    Jul 11, 2021
    Posts:
    4
    I have tried to make one by measuring the x axis of the trigger and the player, and when they are the same it activates what I want it to do but it does not work.

    And I do not know what to do.
     
  2. Badpig_Studios

    Badpig_Studios

    Joined:
    Jul 11, 2021
    Posts:
    4
    here is the script
    {
    private float Trigger_Point;
    private float Player_point;
    public float moveY = 0;
    public float moveX = 0;
    public GameObject Move_Objective;
    public GameObject Trigger_Object;
    public GameObject Player;

    void FixedUpdate()
    {
    Player_point = Player.transform.position.x;
    Trigger_Point = Trigger_Object.transform.position.x;

    if(Player_point == Trigger_Point)
    {
    //in this line start the action
    Move_Objective.transform.position += new Vector3(moveX, 0, 0) * Time.deltaTime;
    Move_Objective.transform.position += new Vector3(0, moveY, 0) * Time.deltaTime;

    }
    }
    }
     
  3. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,639
    It's unlikely that two floats will ever be equal in any case. Instead, you need to check whether they are "close enough". Something like
    if (Mathf.abs(Player_point-Trigger_Point) < 0.01f)


    you might need to change 0.01 to a different number depending on how fast your player is moving.

    Another way to implement triggers that is probably easier is to use a 2D collider (set to "trigger") and implement OnTriggerEnter2D.

    https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnTriggerEnter2D.html
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    Floating (float) point imprecision:

    Never test for equality with floating point (float) variables. Here's why:

    https://forum.unity.com/threads/why-doesnt-this-code-work.1120498/#post-7208431

    How to report your problem productively in the Unity3D forums:

    http://plbm.com/?p=220

    How to understand compiler and other errors and even fix them yourself:

    https://forum.unity.com/threads/ass...3-syntax-error-expected.1039702/#post-6730855

    If you post a code snippet, ALWAYS USE CODE TAGS:

    How to use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/
     
  5. Badpig_Studios

    Badpig_Studios

    Joined:
    Jul 11, 2021
    Posts:
    4
  6. Badpig_Studios

    Badpig_Studios

    Joined:
    Jul 11, 2021
    Posts:
    4


    the player has a constant velocity
     
  7. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    This is irrelevant to floating point precision.