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

Question Car control question (direction/movement/acceleration)

Discussion in 'Scripting' started by nasargsyan, Jul 29, 2023.

  1. nasargsyan

    nasargsyan

    Joined:
    May 1, 2023
    Posts:
    15
    Greetings !

    Currently I am working on a Unity top-down 2D simulator game with a car to drive in the city.
    In order to move the car I use this code :

    Code (CSharp):
    1.  
    2.  
    3. public class car_move1 : MonoBehaviour
    4.  
    5. {
    6.  
    7. [SerializeField]
    8.  
    9. private float speed;
    10.  
    11. [SerializeField]
    12.  
    13. private float rotationSpeed;
    14.  
    15. void Update()
    16.  
    17. {
    18.  
    19. float horizontalInput = Input.GetAxis("Horizontal");
    20.  
    21. float verticalInput = Input.GetAxis("Vertical");
    22.  
    23. Vector2 movementDirection = new Vector2(horizontalInput, verticalInput);
    24.  
    25. float inputMagnitude = Mathf.Clamp01(movementDirection.magnitude);
    26.  
    27. movementDirection.Normalize();
    28.  
    29. transform.Translate(movementDirection * speed * inputMagnitude * Time.deltaTime, Space.World);
    30.  
    31. if (movementDirection != Vector2.zero)
    32.  
    33. {
    34.  
    35. Quaternion toRotation = Quaternion.LookRotation(Vector3.forward, movementDirection);
    36.  
    37. transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation, rotationSpeed * Time.deltaTime);
    38.  
    39. }
    40.  
    41. }
    42.  
    43. }
    44.  


    The question is, how to separate car rotation with its movement and add an acceleration, and all that by using separate keys. For example , arrow keys , ASDW and joystick on gamepad shall rotate, and 2 other keys will accelerate/move and break/stop the car (to be accurate let's take left and right triggers on gamepad).

    By this post/message I'm not requesting/asking for a direct code, but if you please direct me, my thoughts to find out the solution.

    Thank you
     
  2. AngryProgrammer

    AngryProgrammer

    Joined:
    Jun 4, 2019
    Posts:
    431
    nasargsyan likes this.
  3. nasargsyan

    nasargsyan

    Joined:
    May 1, 2023
    Posts:
    15