How to detect slope angle in 2D

Hi everyone,

there are some examples on google and forums but non of them useful.
Please, in my 2D platformer game I want to detect slope angle the player is standing on using ray. I have read that there is a solution to shoot a ray from the player down to the ground and compute at what angle the player is standing on.

I am trying to atchieve different animations of sliding down slopes at different angles. If I am able to measure the angle, then I can slide different slopes with different speed and play different animations.

Please help.

For general scripting help, you should post in the HelpRoom, I’ve moved it for you this time.
No payment necessary, just remember to accept the answer if it helps you solve your issue.

EDIT:
This uses a slightly different method, RaycastNonAlloc which saves a specified number of hit points, in this case, I get the first 2 hits and save them in ‘hits’ that way the first is our characters collider, but the second… oh the second is our beautiful floor collider (hopefully).

void Update(){
	RaycastHit2D[] hits = new RaycastHit2D[2];
	int h = Physics2D.RaycastNonAlloc(transform.position, -Vector2.up, hits); //cast downwards
	if (h > 1) { //if we hit something do stuff
		Debug.Log(hits[1].normal);

		angle = Mathf.Abs(Mathf.Atan2(hits[1].normal.x, hits[1].normal.y)*Mathf.Rad2Deg); //get angle
		Debug.Log(angle);

		if(angle > 30){
			//DoSomething(); //change your animation
		}

	}
}

ORIGINAL: (see comments for why it doesn’t work!)

Transform yourCharacter;
float angle;

void Update(){
	RaycastHit2D hit = Physics2D.Raycast(yourCharacter.position, -Vector2.up); //cast downwards
	if (hit.collider != null) { //if we hit something do stuff
		Debug.Log(hit.normal);

		angle = Mathf.Abs(Mathf.Atan2(hit.normal.x, hit.normal.y)*Mathf.Rad2Deg); //get angle

		if(angle > 30){
			DoSomething(); //change your animation
		}

		//you can use hit.normal.x to know which direction to slide in, negative = left, positive = right for standard 2D view
	}
}