0
\$\begingroup\$

I have been working on a personal project that is suppose to mimic Anthem. I am using a state machine for the character controller that I intend to integrate with the Unity's Animation state machine.

I am calculating a new velocity that makes the player follow the mouse when flying, and I am making transform.up = Velocity so that the player appears to be going head first towards its velocity.

The issue is that when you start to rotate in a circular way on the xz plane, the player will start to roll and its transform.forward moves from facing towards the ground (which is what I want) to facing the sky.

Animation of roll

The core code is in public override Update():

public class s_MechFlyt : MechStates{

  float flySpeedPercentage;

  public s_MechFlyt(in MechController Master) : base(Master){
    flySpeedPercentage = 2.5f;
  }

  public override void Update(){
    if (_Master.SprintButtonHeld){

      Quaternion Rot = Quaternion.Euler(-_Master.DMouse.y , _Master.DMouse.x , 0);

      _Master.Velocity = Rot * Vector3.forward * _Master.Stats.Speed * flySpeedPercentage;
      Vector3 Rotation = _Master.Velocity;**
      //Rotation.y = Mathf.Clamp(Rotation.z, 0, 50);
      _Master.transform.up = Vector3.Normalize(Rotation);
      //_Master.transform.rotation = Rot;

      //_Master.transform.rotation = Quaternion.RotateTowards(_Master.transform.up, _Master.Velocity, 5);

      _Master._Controller.Move(_Master.Velocity * Time.deltaTime);

      if (_Master.JumpButtonHeld){
        _Master.ChangeStates("hover");
        _Master.transform.up = Vector3.up;
      }

    }
    else{
      _Master.ChangeStates("fall");
      _Master.transform.up = Vector3.up;
    }
  }

  public override void EnterState(){
    _Master.CamController.ChangeStates("flying");
  }
}
\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

You already have a rotation that points Vector3.forward in the direction of flight, while keeping Vector3.up as vertical as it can.

Pitching that rotation forward 90 degrees means it points Vector3.up in the direction of flight, and points Vector3.forward down.

Quaternion mouseRotation = Quaternion.Euler(-_Master.DMouse.y , _Master.DMouse.x , 0);

_Master.Velocity = mouseRotation * Vector3.forward * _Master.Stats.Speed * flySpeedPercentage;

_Master.transform.rotation = mouseRotation * Quaternion.Euler(90f, 0, 0);
\$\endgroup\$
1
  • \$\begingroup\$ That worked exactly as I wanted! thanks! \$\endgroup\$ Mar 6, 2021 at 16:57

You must log in to answer this question.

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