Can not move and rotate at the same time

Hello, I have a code to move and rotate my object but when I move it, I can’t rotate it. It just rotates when Vertical Input value equals to 0.
It should has a very simple solution but i couldn’t figure it out. Also, I need to use moveRotation and movePosition, transform.Translate or etc doesn’t fit with my game.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public float movementSpeed = 15;
    public float rotationSpeed = 4;
    private Rigidbody rb;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    private void FixedUpdate()
    {

        rb.MovePosition(rb.position + transform.forward * movementSpeed * Input.GetAxis("Vertical") * Time.deltaTime);

        float turn = Input.GetAxis("Horizontal") * rotationSpeed * Time.deltaTime;
        Quaternion turnRotation = Quaternion.Euler(0f, turn, 0f);
        rb.MoveRotation(rb.rotation * turnRotation);


    }
}

[/ICODE]

Hi and welcome!
First and foremost, you should use FixedUpdate() only for physics (Rigidbody) related code, so the Inputs should be caught and saved in Update(). That’s not causing the problem here tho. I got it to work with the following code:

    public float movementSpeed = 15;
    public Vector3 rotationSpeed = new Vector3(0,40,0);
    private Rigidbody rb;
    private Vector2 inputDirection;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    private void Update()
    {
        Vector2 inputs = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
        inputDirection = inputs.normalized;
    }

    private void FixedUpdate()
    {
        Quaternion deltaRotation = Quaternion.Euler(inputDirection.x * rotationSpeed * Time.deltaTime);
        rb.MoveRotation(rb.rotation * deltaRotation);
        rb.MovePosition(rb.position + transform.forward * movementSpeed * inputDirection.y * Time.deltaTime);
    }

Hope that helps. Also, your rotation speed was insanely low, so i bumped it up a bit.

5 Likes

Thanks! It helped me a lot.

Just a quick reminder that for using delta time in FixedUpdate you should use:

Time.fixedDeltaTime

Actually, that does not matter, as Time.deltaTime will automatically return the correct value depending on whether it’s used from within Update or FixedUpdate.
https://docs.unity3d.com/ScriptReference/Time-fixedDeltaTime.html

4 Likes

Super. Thanks for letting me. Didn’t know that. :slight_smile:

This has helped me a lot with smooth rigidbody movement. My only issue is that the object in question will continue moving briefly after releasing the input. Am I doing something wrong?

edit: The issue was with the smoothing of the input returned by Input.getAxis. Resolved by changing Input.getAxis to Input.getAxisRaw.