Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Check if my player is at the same position as another gameobject's position.

Discussion in 'Scripting' started by Langebeck, Sep 29, 2023.

  1. Langebeck

    Langebeck

    Joined:
    Jul 16, 2019
    Posts:
    4
    Hi Guys.

    In my script i am trying to tjek if the transform.position is equal to another game objects position, and i cant figure it out.. so far i got this, and its not working .. The Player moves, yes, and it moves to the position, all perfect.

    But it never make get to the position and do the Debug.Log, in my if statement.

    Hope some of you guys have a solution i can work with! <3

    Here is my code:

    if((transform.position - kommeind.transform.position).magnitude < 0.1f)
    {
    Debug.Log("Er Kommet ind");
    }
    else
    {
    Player.transform.position = Vector3.MoveTowards(transform.position, kommeind.transform.position, movespeed * Time.deltaTime);

    Debug.Log("Kommer ind");
    }
     
  2. samana1407

    samana1407

    Joined:
    Aug 23, 2015
    Posts:
    74
    Most likely this script is not located on the Player object. Here you check the distance with the transform of an unknown object

    if((transform.position - kommeind.transform.position).magnitude < 0.1f)

    but you move the Player

    Player.transform.position = Vector3.MoveTowards(transform.position, kommeind.transform.position, movespeed * Time.deltaTime);
     
  3. Langebeck

    Langebeck

    Joined:
    Jul 16, 2019
    Posts:
    4
    It is on attach to the player object, but even when i do this, it is still not working:

    if((Player.transform.position - kommeind.transform.position).magnitude < 0.1f)
    {
    Debug.Log("Er Kommet ind");
    }
    else
    {
    Player.transform.position = Vector3.MoveTowards(Player.transform.position, kommeind.transform.position, movespeed * Time.deltaTime);

    Debug.Log("Kommer ind");
    }
     
  4. Langebeck

    Langebeck

    Joined:
    Jul 16, 2019
    Posts:
    4
    So, just to be clear.. the player move, to the kommeind position, but the IF never gets active, the Debug.Log("Er kommet ind"); never shows.. -_- .. i struggled with the for days now :p
     
  5. Chubzdoomer

    Chubzdoomer

    Joined:
    Sep 27, 2014
    Posts:
    106
    Have you actually debugged the magnitude to verify the result of the calculation?