0
\$\begingroup\$

I have a capulse character Im moving around in my 3d Game, I usually rotate the character using this line of code:

void HandleRotation(){
        if(_move.magnitude > 0.1){
            _targetAngle = Mathf.Atan2(_move.x, _move.y) * Mathf.Rad2Deg + _camera.transform.eulerAngles.y;
            angle = Mathf.SmoothDampAngle(_playerTransform.eulerAngles.y, _targetAngle, ref _turnSmoothVelocity, 0.02f);
            Vector3 relativeForce = (Quaternion.Euler(0f, _targetAngle, 0f) * Vector3.forward).normalized;

                publisher.UpdateDirection(_move);
                _force.x = relativeForce.x * Speed * _move.magnitude;
                _force.z = relativeForce.z * Speed * _move.magnitude;
            
        }
        else {
            _force.x = 0;
            _force.z = 0;
            publisher.UpdateDirection(new Vector2());
        }
    }

 void ApplyRotation(){

      _rigidbody.MoveRotation(Quaternion.Euler(0, angle , 0));
 }

This works fine when on a flat plane, and on slopes, however id like to align my player to the slope they're on. I have code to check if a player is on a slope and to align them to the slope:

void SlopeCheck()
    {
        Quaternion newRot;
        RaycastHit downHit;
        if (Physics.Raycast(_groundCheck.position + Vector3.up, Vector3.down, out downHit, 5f, _groundLayer) && _isGrounded && !_jumpPressed)
        {
            _onSlope = true;
            slopeNormal = downHit.normal;
            _playerTransform.rotation = (Quaternion.FromToRotation(_playerTransform.rotation.eulerAngles.normalized, slopeNormal)) * _playerTransform.rotation;
        }
    }

However this ends up making my character jitter like crazy along the x axis:

Image of characer aligned awkwardly on slope

I have tried combining these two rotations in various ways but each one gives me awkward results, is there a way for me to make sure I can still rotate my character along the Y axis when aligned along a slope? I'm guessing because my character isnt pointing directly upwards, the rotation would need to be some combination of an x,y,z rotation but I'm unsure how to derive this in code. Any help would be greatly appreciated!

\$\endgroup\$
2
  • \$\begingroup\$ Have you tried using localRotation or localEulerAngles? \$\endgroup\$
    – Kevin
    Apr 24, 2023 at 18:51
  • \$\begingroup\$ Yeah thats still not working for me \$\endgroup\$
    – Jambo
    Apr 24, 2023 at 18:54

1 Answer 1

0
\$\begingroup\$

It seems like this order of rotation did the trick for me:

_playerTransform.rotation = (Quaternion.FromToRotation(Vector3.up, slopeNormal)) * (Quaternion.Euler(0, angle , 0));

It also works using MoveRotation!

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .