Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Turning player to face joystick direction and keep moving that way

Discussion in '2D' started by Zeepblok, May 23, 2017.

  1. Zeepblok

    Zeepblok

    Joined:
    Sep 26, 2015
    Posts:
    15
    Hi all,

    I have a slightly different problem with the joystick and movement than the similar topic I found. Namely. If I use my old script (without turning to face the joystick) my player moves perfectly through my scene (its a top-down game) but when I add the turning code my player turns perfectly but he moves all over the place and doesn't follow the direction he looks at.

    here is the code

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class PlayerMovementHandler : MonoBehaviour
    4. {
    5.  
    6.     private float speed;
    7.     private Rigidbody2D controller;
    8.     public JoyStick moveJoyStick;
    9.  
    10.     public PlayerMovementHandler()
    11.     {
    12.         speed = 3f;
    13.     }
    14.  
    15.     // Use this for initialization
    16.     private void Start()
    17.     {
    18.         controller = GetComponent<Rigidbody2D>();
    19.     }
    20.  
    21.     // Update is called once per frame
    22.     void Update()
    23.     {
    24.         Vector3 dir = Vector3.zero;
    25.         Vector3 movement = new Vector3(dir.x, 0, dir.y);
    26.         dir.x = Input.GetAxis("Horizontal");
    27.         dir.y = Input.GetAxis("Vertical");
    28.  
    29.         if(moveJoyStick.InputDirection != Vector3.zero)
    30.         {
    31.             dir = moveJoyStick.InputDirection;
    32.         }
    33.  
    34.         transform.Translate(dir * speed * Time.deltaTime);
    35.  
    36.             //the turn part of my code
    37.         float heading = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
    38.         transform.rotation = Quaternion.Euler(0f, 0f, heading - 90);
    39.  
    40.     }
    41. }
    42.  
     
  2. Zeepblok

    Zeepblok

    Joined:
    Sep 26, 2015
    Posts:
    15
    Fixed it, I changed this:

    Code (CSharp):
    1. transform.Translate(dir * speed * Time.deltaTime);
    to this:

    Code (CSharp):
    1. transform.Translate(dir * speed * Time.deltaTime, Space.World);
     
  3. GorGargoullieth10th8

    GorGargoullieth10th8

    Joined:
    Mar 15, 2019
    Posts:
    1
    I am trying a project exactly like this, and the code is not working. Is there something that is different for Macs?
     
  4. YuvMan

    YuvMan

    Joined:
    Mar 30, 2019
    Posts:
    2
    in the last line, I changed from heading -90 TO heading + 90, and it worked like magic!