How to Make the GameObject Moving By Arrow key Unity 2D



Introduction 

Understanding how mouse input works is one of the most fundamental tools in every Unity developer’s skill set. Not only is the mouse used for interacting with 2D UI elements, such as buttons, sliders, and checkboxes, but it’s also very common to use it to interact with 3D game objects inside the game scene, or, for example, to display an informative UI tooltip next to the mouse cursor.

Shown Below The code for moving the gameObject the left by mouse touch to  by the mouse touch


public class Neon : MonoBehaviour
{
    private Rigidbody2D rb;
    [SerializeField] private float movSpeed;

    void Start()
    {
        // Assign the Rigidbody component to the variable.
    }

    void Update()
    {
        // Move left when the left arrow key is pressed
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            rb.velocity = new Vector2(-movSpeed, rb.velocity.y);
            gameObject.transform.localScale = new Vector3(-0.25f, 0.25f, 0);
        }
        // Move right when the right arrow key is pressed
        else if (Input.GetKey(KeyCode.RightArrow))
        {
            rb.velocity = new Vector2(movSpeed, rb.velocity.y);
            gameObject.transform.localScale = new Vector3(0.25f, 0.25f, 0);
        }
        // Stop moving when no arrow keys are pressed
        else
        {
            rb.velocity = new Vector2(0, rb.velocity.y);
        }
    }
}

Explanation:


  • Rigidbody2D rb;: Declares a private variable to hold a reference to the Rigidbody2D component attached to the GameObject.

  • [SerializeField] private float movSpeed;: Declares a private variable to control the movement speed of the GameObject.

  • Start() : Unity method that is called once when the script is initialized. It assigns the Rigidbody component to the rb variable.

  • Update() : Unity method that is called every frame. It checks for arrow key input and moves the GameObject.

  • The code checks for arrow key input using Input.GetKey(KeyCode.LeftArrow) and Input.GetKey(KeyCode.RightArrow).

  • If the left arrow key is pressed, it moves to the left and adjusts its scale to face left.

  • If the right arrow key is pressed, it moves to the right side and adjusts its scale to face right.

  • If no arrow keys are pressed, the GameObject is stop.




Happy coding









Previous Post Next Post

Contact Form