I want to rotate my player’s sprite based on slopes yet I have no clue how to do it.
Here’s what it looks like:
Compared to what I want it to look:
Can anyone help with this?
I want to rotate my player’s sprite based on slopes yet I have no clue how to do it.
Here’s what it looks like:
Compared to what I want it to look:
Can anyone help with this?
I would build a new script, separate from the Player’s one, in order to keep things as clean as possible:
using UnityEngine;
public class RotatePlayerSprite : MonoBehaviour {
[Header("References")]
public Transform playerSprite; //Up to you to choose if you want to rotate the player or just the sprite
[ToolTip("If you assigned the hole player to playerSprite, do not assign this")]
public Transform playerTransform;
[Header("Raycast Settings")]
public bool userLayerMask;
[ToolTip("If you set userLayerMask to false, ignore this")]
public LayerMask terrainLayerMask;
public int raycastMaxDistance;
[Header("Animation Settings")]
public float characterRotationSpeed;
public bool resetRotationWhenRaycastDoesntHit;
//Internal variables
private Quaternion targetRotation;
private void Update()
{
playerSprite.rotation = Quaternion.RotateTowards(playerSprite.rotation, targetRotation, Time.deltaTime * characterRotationSpeed);
}
private void FixedUpdate()
{
Transform raycastOrigin = (playerTransform) ? playerTransform : playerSprite;
RaycastHit2D hit;
if (userLayerMask){
hit = Physics2D.Raycast(raycastOrigin.position, -raycastOrigin.up, raycastMaxDistance, terrainLayerMask);
}else{
hit = Physics2D.Raycast(raycastOrigin.position, -raycastOrigin.up, raycastMaxDistance);
}
if (hit.transform)
{
targetRotation = Quaternion.Euler(0, 0, Vector3.SignedAngle(raycastOrigin.position, hit.point)); //You have to test this, I am not good at 2D physics
}else if (resetRotationWhenRaycastDoesntHit)
{
targetRotation = Quaternion.Identity;
}
}
}