Search code examples
c#unity-game-engine2d

how to move player by single button press Based on direction rotation of joystick


Number 1 is the Joystick (work fine)

number 2 is the button needed to press for the Object to move

what is the code to move the object only when the button is pressed and based on the Joystick directions if it sat still or moved?

annotated screenshot of the controls


Solution

  • It would probably be something along the lines of:

    using UnityEngine;
    
    public class Spaceship: MonoBehaviour
    {
      // ...
    
      ///<summary>rigidbody for the ship for physics</summary>
      public Rigidbody2D rb;
      ///<summary>the force for the thrusters or something</summary>
      public float thrustForce;
    
      ///<summary>The current joystick input vector</summary>
      private Vector2 _direction = Vector2.zero;
      ///<summary>is the thrusting button held?</summary>
      private bool _thrusting = false;
    
      ///<summary>in which we obtain the current state of the inputs</summary>
      void Update()
      {
        // ...
      
        // get current direction (normalizing it if the magnitude is greater than 1)
        Vector2 rawDir = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
    
        // (n^2) > 1 only if n > 1
        // (so we can check the more efficient .sqrMagnitude instead of .magnitude)
        if (rawDir.sqrMagnitude > 1) 
        {
          _direction = rawDir.normalized;
        }
        else
        {
          _direction = rawDir;
        }
    
        // if you don't care about analog 'not fully tilting
        // the stick in a certain direction' inputs, you can
        // just omit that if statement and make the direction
        // .normalized in all situations
    
        // and is the thrust button held?
        // Replace "Thrust" with "Jump" to test this using the spacebar.
        // This will need to be refactored in order to use a GUI button.
        _thrusting = Input.GetButton("Thrust");
      
        // ...
      }
    
      ///<summary>and now we use those inputs for some PHYSICS!!! (wow)</summary>
      void FixedUpdate()
      {
        // ...
    
    
        if (_thrusting) // if button is held
        {
          // we add the appropriate thrust force in the specified direction
          rb.AddForce(_direction * thrustForce);
        }
    
        // ...
    
      }
    
    }
    
    

    the above code uses the legacy input system, but it should be simple enough to refactor the core logic to work with the new input system in case your project uses that.