Search code examples
unity-game-enginerotationtransformjoystick

Move and rotate 2d object using virtual joystick


Here is my code for moving a 2D top-down object using the built in virtual joystick:

void Update () 
    {
        Vector2 moveVec = new Vector2(CrossPlatformInputManager.GetAxis("Horizontal"), 
            CrossPlatformInputManager.GetAxis("Vertical"));


        Vector3 lookVec = new Vector3(CrossPlatformInputManager.GetAxis("Horizontal"), 
            CrossPlatformInputManager.GetAxis("Vertical"), 4000);

        transform.rotation = Quaternion.LookRotation(lookVec, Vector3.back);
        transform.Translate(moveVec * Time.deltaTime * speed);  
    }

Without the rotation code, the movement was perfect, after adding the rotation code the movement got all messed up, if the direction is down, it moves up. But the rotation is exactly how it should.


Solution

  • Simply change the transform.Translate(moveVec * Time.deltaTime * speed); line to transform.Translate(moveVec * Time.deltaTime * speed, Space.World); : by default, the translation is made relatively to the transform own space (Space.Self).