Rotating Character While Terrain Hugging

By using this post, I have made a driving character, which automatically moves forward and hugs the ground and slopes (matches its rotation). This works, but I also want my character to rotate left and right while riding the ground and slopes (see: Kirby Air Ride). Is that a possibility and how would I accomplish it?

      public Transform backLeft;
      public Transform backRight;
      public Transform frontLeft;
      public Transform frontRight;
      public RaycastHit lr;
      public RaycastHit rr;
      public RaycastHit lf;
      public RaycastHit rf;
      public Vector3 upDir;
      void Update () {
          Physics.Raycast(backLeft.position + Vector3.up, Vector3.down, out lr);
          Physics.Raycast(backRight.position + Vector3.up, Vector3.down, out rr);
          Physics.Raycast(frontLeft.position + Vector3.up, Vector3.down, out lf);
          Physics.Raycast(frontRight.position + Vector3.up, Vector3.down, out rf);
          upDir = (Vector3.Cross(rr.point - Vector3.up, lr.point - Vector3.up) +
                   Vector3.Cross(lr.point - Vector3.up, lf.point - Vector3.up) +
                   Vector3.Cross(lf.point - Vector3.up, rf.point - Vector3.up) +
                   Vector3.Cross(rf.point - Vector3.up, rr.point - Vector3.up)
                  ).normalized;
          Debug.DrawRay(rr.point, Vector3.up);
          Debug.DrawRay(lr.point, Vector3.up);
          Debug.DrawRay(lf.point, Vector3.up);
          Debug.DrawRay(rf.point, Vector3.up);
          transform.up = upDir;
      
      }

Thank you for reading, and please do reply with any help you can give.

1 Answer

1

Ok, so: if I have understood what you want to do it should be pretty easy…
Right now your character`s rotation always matches floor , and you want this rotation to be altered when the player is turning right or left. I would just do this:

  1. calculate the terrain’s perpendicular normal vector; it is your upDir vector which you already have.

  2. create a second vector for turning, for example, if this vector is based on an analogic stick you will have a X input value between -1 (totally left) and 1 (totally right). The calculation could be something like:

    float x = “analogicInput”;
    float scale = 10f;
    Vector3 inputRotation = new Vector3 (x*scale, 0,0);

  3. Add both vector getting a new upVector that depends on the input and terrain. Assign transform.up to this.

Just adding this to your code should be enough (using whatever you want instead of “analogicInput” and whatever scale you want)

I tried adding the code, and it is saying that it could not convert string to float. And I do not understand what you mean by adding vectors and assigning them to transform.up, wouldn't that only affect on the vertical rotation?

–

@Noge-v im trying to do terrain hugging with this exact same script but i need my character to do Yaw rotation (y axis) , how can i do that ?

–