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

Raycasting 2D to get distance from player to an object

Discussion in '2D' started by Alexapo, Nov 12, 2021.

  1. Alexapo

    Alexapo

    Joined:
    Apr 6, 2021
    Posts:
    10
    Hello! I am trying to get a distance value from an object (an axe) to a player in realtime. I saw a tutorial using 3D where the code looks something like this:

    Code (CSharp):
    1. private void Update()
    2.     {
    3.         Vector3 direction = axePosition.transform.position - transform.position;
    4.         RaycastHit outInfo;
    5.  
    6.         bool hit = Physics.Raycast(transform.position, direction, out outInfo);
    7.         Debug.DrawRay(transform.position, direction);
    8.  
    9.         AkSoundEngine.SetRTPCValue("Axe_Distance", outInfo.distance);
    10.     }
    The last line "AkSoundEngine" is from a middleware that takes a value as an argument, which in this case is the distance between the player and the object.

    So what I need is an equivalent way of doing this in 2D. Any ideas?
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,529
    Yes, use the docs here or follow one of the thousands of tutorials on 2D Physics.
     
  3. Alexapo

    Alexapo

    Joined:
    Apr 6, 2021
    Posts:
    10
    I did use the documentation,and made several attempts to make it work. I ended up with this:
    ` void Update()
    {
    Vector2 direction = axePosition.transform.position - transform.position;
    int mask = LayerMask.GetMask("Axe");

    RaycastHit2D hit = Physics2D.Raycast(transform.position, direction, MaxDist, mask);
    Debug.DrawRay(transform.position, direction);

    if (hit)
    {
    AkSoundEngine.SetRTPCValue("Axe_Distance_Whoosh", hit.distance);
    }`
    I was still unable to get it to work, until I figured out at that the error was because of arguments set for the middleware. The raycasting worked just fine.
     
    MelvMay likes this.
  4. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,529
    Doing a "Debug.Log(hit.distance)" would immediately tell you if it was returning the expected distance or reasonable values.

    Anyway, glad you got your middleware sorted out.