0
\$\begingroup\$

I have a character that moves around using a virtual joystick on screen (mobile game joystick) however the player doesn't face forward to the position the joystick is pointing. Whenever I modify the rotation values on script it goes off the rails and moves erratically. What can I do to achieve this movement without altering it's translation?

Here is my script:

     void Update()
{


    horizontal = inputJoystick.horizontal();
    vertical = inputJoystick.vertical();

    moveDirection = new Vector3(horizontal, 0, vertical);
    moveDirection = transform.TransformDirection(moveDirection);
    moveDirection *= speed;

    //rotationDirection = new Vector3(horizontal, 0, vertical);
    //transform.rotation = Quaternion.LookRotation(rotationDirection, Vector3.up);
    controller.Move(moveDirection * Time.deltaTime);

}
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Right now when you rotate the mesh you interfere with the movement because transform.TransformDirection(moveDirection) transforms from local to world space, so your move direction ends up depending on more than just the joystick's direction and as you rotate the mesh it will change. You need to keep this transform stable.

You can use a game object hierarchy like:

Controller
-- Mesh

And attach to the Controller all your movement-related components, including something like CharacterMovementScript, and to the Mesh attach the rotating component CharacterRotateScript.

public class CharacterMovementScript : MonoBehaviour {

    void Update () {
        var horizontal = Input.GetAxis("Horizontal");
        var vertical = Input.GetAxis("Vertical");

        var moveDirection = new Vector3(horizontal, 0, vertical);
        moveDirection = transform.TransformDirection(moveDirection);
        moveDirection *= 1.0f;

        var controller = GetComponent<CharacterController>();
        controller.Move(moveDirection * Time.deltaTime);
    }
}

public class CharacterRotateScript : MonoBehaviour {

    void Update () {
        var horizontal = Input.GetAxis("Horizontal");
        var vertical = Input.GetAxis("Vertical");

        if (horizontal != 0.0f || vertical != 0.0f) {
            var rotationDirection = new Vector3(horizontal, 0, vertical);
            transform.rotation = Quaternion.LookRotation(rotationDirection, Vector3.up);
        }
    }
}

Doing this should get you closer to what you're looking for, I think.

\$\endgroup\$

You must log in to answer this question.

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