How do you get an angle of a point on a collider by using raycast?

I’m new to C# and Unity, I’m just trying to get the angle of a collider in 2d. It’s giving me both 90 and 180 on similar flat surfaces. I’m just getting confused more and more as I delve into this.

My thought process:
I make a line and if it hits something that is a layer called ground then I get the angle of the point it got hit on.

Any help would be much appreciated! Bonus if you can help me figure out how to keep the ray fixed as in not rotating relative to the object its attached to, that would be a great help. I tried transform.position-new Vector3(0,1,0) but that only works on lines.

Thanks in advance!

public bool onGround=false;
    public Vector2 groundNormal;
    public float myAngle;



    private void FixedUpdate()
    {
        Debug.DrawRay(transform.position, -transform.up, Color.cyan);
        if (Physics2D.Raycast(transform.position, -transform.up, 1.5f, 1 << LayerMask.NameToLayer("Ground")) == true)
        {
     
            onGround = true;
            groundNormal = Physics2D.Raycast(transform.position, -transform.up, 1.5f, 1 << LayerMask.NameToLayer("Ground")).normal;
            myAngle = Vector2.Angle(groundNormal, transform.position);


        }
        else {

            onGround = false;
        }
    }

}

Please use Code Tags:

public bool onGround=false;
public Vector2 groundNormal;
public float myAngle;

private void FixedUpdate()
{
    Debug.DrawRay(transform.position, -transform.up, Color.cyan);
    if (Physics2D.Raycast(transform.position, -transform.up, 1.5f, 1 << LayerMask.NameToLayer("Ground")) == true)
    {
        onGround = true;
        groundNormal = Physics2D.Raycast(transform.position, -transform.up, 1.5f, 1 << LayerMask.NameToLayer("Ground")).normal;
        myAngle = Vector2.Angle(groundNormal, transform.position);
    }
    else
    {
        onGround = false;
    }
}

Here is the presentation of Calculating Angles between two points:

The A is the source point and the B is the target point, now you can get the angle between A and B in Unity by using Vector3.Angle or Vector2.Angle or Vector2.SignedAngle.

Thanks.

Pass in a RayCastHit2D to your raycast.
The normal that is returned is the vector the poly is facing.

Exmaple of getting RayHit2D is there you just need to get myHit.normal

Hi, I’m sure this isn’t so relevant anymore, but here is how i did it:

  1. I used an EdgeCollider to trace the walls.
  2. The Bouncing object contains a RayCaster, a RgidBody2D and a CircleCollider2D.
  3. Make a Physics2D Material. Here you can set the Bouncyness.
  4. Add the Bouncy Physics2D Material to the CircleCollider2D

That’s it!

Hope this helps anyone who gets here.