c# – Unity 3D, player not moving in the direction the camera is facing or jumping correctly

I’ll start by saying that I’m pretty new to this and wanted to try and build a basic third-person controller to learn how they’re set up.

I can get the player to move around just fine, and I’ve got the camera floating around the player by moving the mouse, the player doesn’t move relative to the direction the camera is facing, and when I press “jump” I either barely hop off the ground or I’m launched into space.

If someone could take a look at my code and maybe guide me in the right direction as to what I’m doing wrong, it would be very appreciated!

Here’s my code,

private void FixedUpdate()
    Cursor.lockState = CursorLockMode.Locked;

    Rigidbody rb = GetComponent<Rigidbody>();

    //getting input for custom button mapping 
    float horizontal = Input.GetAxisRaw("Horizontal");
    float vertical = Input.GetAxisRaw("Vertical");

    Vector3 forward = Camera.main.transform.forward;
    Vector3 right = Camera.main.transform.right;

    forward.y = 0f;
    right.y = 0f;


    Vector3 moveDirection = new Vector3(horizontal, 0f, vertical).normalized;
    rb.velocity = new Vector3(moveDirection.x * _speed, rb.velocity.y, moveDirection.z * _speed);

    if (moveDirection != new Vector3(0, 0, 0))
        _playerMesh.rotation = Quaternion.LookRotation(moveDirection);

    Vector3 jump = new Vector3(0.0f, 2.0f, 0.0f);

    if (Physics.Raycast(transform.position, Vector3.down, _distToGround + 0.1f)) // casts a beam down and checks for collision
            isGrounded = true; //Grounds Player
            isGrounded = false;
        Debug.Log("no ground");

    if (isGrounded && Input.GetKeyDown(KeyCode.Space)) //Jump
        rb.AddForce(jump * _jumpForce, ForceMode.Impulse);

    if (moveDirection.magnitude > -0.1f)
            float targetangle = Mathf.Atan2(moveDirection.x, moveDirection.z) * Mathf.Rad2Deg + _cam.eulerAngles.y;
            float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetangle, ref _turnSmoothVel, _turnSmoothTime);
            transform.rotation = Quaternion.Euler(0f, angle, 0f);

            Vector3 _movedir = Quaternion.Euler(0f, targetangle, 0f) * Vector3.forward;
        _controller.Move(_movedir.normalized * _speed * Time.fixedDeltaTime); //smoothly turns the player character 


Also, I have a RigidBody component and a PlayerController component attached to my player character if that helps any.

Read more here: Source link