Forum rules - please read before posting.

How to tilt character in direction of slope walking up and down (point and click)

Hey everyone, I'm working on a 2D sidescroller project with perspective akin to classic Mario (only left and right). I'm using a polygon collider for the walkable area (point-and-click to move), and it's working well. However, I'm wondering how to make the character tilt or rotate to match the angle of a slope when walking uphill, to create the illusion that they're facing the direction of the slope. Any suggestions? Thanks!

Unity Version 2023.3.0a17
Silicon Apple M1 max pro
AC v1.79.3

Comments

  • In the same way that a car would tilt on slopes?

    This wouldn't involve AC, but a custom script can be used to detect the angle of the ground, and tilt the character's "Sprite child" along its normal.

    For smooth turning along hard corners, you can raycast from two points: one a little to the left and above the character's feet, the other a little to the right and above. Record the positions they hit the ground downwards (on the NavMesh layer), and use the angle between their relative position and Vector2.right to affect the sprite-child's rotation:

    using UnityEngine;
    using AC;
    
    public class TiltCharacter : MonoBehaviour
    {
    
        public Transform leftPosition;
        public Transform rightPosition;
        public Transform spriteChild;
        public LayerMask layerMask;
        public float distance;
    
        void Update ()
        {
            RaycastHit2D leftHit = Physics2D.Raycast (leftPosition.position, Vector2.down, distance, layerMask);
            if (leftHit.collider != null)
            {
                Vector2 leftHitPoint = leftHit.point;
    
                RaycastHit2D rightHit = Physics2D.Raycast (rightPosition.position, Vector2.down, distance, layerMask);
                if (rightHit.collider != null)
                {
                    Vector2 rightHitPoint = rightHit.point;
    
                    Vector2 relativeDirection = (rightHitPoint - leftHitPoint).normalized;
                    spriteChild.eulerAngles = Vector3.forward * Vector2.SignedAngle (Vector2.right, relativeDirection);
                }
            }
        }
    
    }
    
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Welcome to the official forum for Adventure Creator.