Home > Net >  How do I make it so that the Rotation of the player object does not affect the Input.GetAxisRaw(&quo
How do I make it so that the Rotation of the player object does not affect the Input.GetAxisRaw(&quo

Time:07-19

In my code, when I change the rotation of the player object, the Input.GetAxisRaw("Horizontal") also follows that rotation and messes the whole player controller up. How do I make it so that the Input.GetAxis is permanent and stays in place? The whole rotation is being done in the if statement of if Input.GetKey("a").

    using UnityEngine;

public class JUSTMOVE : MonoBehaviour
{
    public float speed = 7f;
    Vector3 moveDirection;
    public Rigidbody rb;
    float horizontalMovement;
    float verticalMovement;
    public float movementMultiplier = 10f;
    bool grounded;
    public float groundDrag = 6;
    public LayerMask whatIsGround;
    public float airMultiplier = 3f;
    public float playerHeight = 2f;
    public float jumpForce = 5f;
    void FixedUpdate()
    {
        grounded = Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f   0.2f, whatIsGround);

        horizontalMovement = Input.GetAxisRaw("Horizontal");

        if (grounded)
            rb.drag = groundDrag;
        else
            rb.drag = 0;


        moveDirection = transform.forward * verticalMovement   transform.right * horizontalMovement;

        if(grounded)
        {
            rb.AddForce(moveDirection.normalized * speed * movementMultiplier, ForceMode.Force);
        } else if(!grounded)
        {
            rb.AddForce(moveDirection.normalized * speed * movementMultiplier * airMultiplier, ForceMode.Force);
        }

        if(Input.GetKey("a"))
        {
            transform.localRotation = Quaternion.Euler(0,270,0);
        }

        Vector3 flatVel = new Vector3(rb.velocity.x, 0f,rb.velocity.z);

        if(flatVel.magnitude > speed)
        {
            Vector3 limitedVel = flatVel.normalized * speed;
            rb.velocity = new Vector3(limitedVel.x, rb.velocity.y, limitedVel.z);
        }

         if(Input.GetKey("w") && grounded)
         {
            rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
            rb.AddForce(transform.up * jumpForce, ForceMode.Impulse);
         }
    }
}

CodePudding user response:

If I get it right, you want a top/down controller instead of a first/third person controller ?

If so, you need to move align the camera rotation instead of you character rotation.

Replace this :

moveDirection = transform.forward * verticalMovement   transform.right * horizontalMovement;

By this :

moveDirection = Camera.main.transform.forward * verticalMovement   Camera.main.transform.right * horizontalMovement;
  • Related