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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

How to find distance between a player an a wall

Discussion in 'Scripting' started by Watermelon_Dev, Dec 17, 2019.

  1. Watermelon_Dev

    Watermelon_Dev

    Joined:
    Dec 15, 2019
    Posts:
    5
    Hello everyone,
    I'm trying to make a kind of system that when the player pushes a button, It gives him the distance from the object directly in front of him. I've got no idea where to start. Does anyone know I way I could possibly do this?
     
  2. ZaffreSheep

    ZaffreSheep

    Joined:
    Aug 26, 2018
    Posts:
    32
    Hey Watermelon_Dev, You're probably looking for this: https://docs.unity3d.com/ScriptReference/RaycastHit-distance.html

    You can create a ray and raycasthit variable, and use it in
    Physics.Raycast
    , as shown in the example at the link I provided.

    It's good practice to make sure to do any Physics related functions in FixedUpdate(), so check for the player input in the Update() function(because FixedUpdate() isn't guaranteed to run every frame), and then perform the physics code in the FixedUpdate.
    Hope this helps ya!
     
    Emolk and Watermelon_Dev like this.
  3. Watermelon_Dev

    Watermelon_Dev

    Joined:
    Dec 15, 2019
    Posts:
    5
    Thanks! I'll try it out!
     
  4. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,516
    This applies mostly to moving objects or applying forces. If you're just using a raycast to check a distance then it's cool to do so in Update(), since it's not changing any physics data, just querying it.

    Plus, since this is to be displayed on the screen, you probably want it to be in sync with the most recently drawn frame, which FixedUpdate() may not be.
     
    ZaffreSheep and Watermelon_Dev like this.
  5. ZaffreSheep

    ZaffreSheep

    Joined:
    Aug 26, 2018
    Posts:
    32
    Interesting, I guess I never really considered them different; Makes sense though, thanks for the clarification.
     
    Watermelon_Dev and angrypenguin like this.
  6. Watermelon_Dev

    Watermelon_Dev

    Joined:
    Dec 15, 2019
    Posts:
    5
    I've just implemented it, and it works really well!
     
    ZaffreSheep and doarp like this.