How to move an object with keyboard in Unity 3D

Hello programmers, In this article, I will show “How to move an object with the keyboard in Unity 3d”

While creating any game the essential element of a 3D game is to move its game object. Moving an Object in a game is very simple. Let’s get started with the building process.

Create Objects

  • First, open your unity project.
  • In Hierarchy > 3D Object > Plane
  • Hierarchy > 3D Object > Sphere

  • Both Plane and Sphere will be added to the Scene.

C# Script

  • Go to Assets
  • Assets > Create > C# Script

Input.GetAxis:

It returns the value of all the virtual axis identified by its axisName.

Input.GetAxis("Horizontal")

or

Input.GetAxis("Vertical")

For making an object move, we should use predefined elements such as the Horizontal and Vertical axis.

It will take input from the keyboard and the input will be between the range -1 and 1.

The below-given program is to move an object with a keyboard in Unity 3D.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ballcontrol : MonoBehaviour
{

    public Rigidbody rb ;
    public float horizontalInput;
    public float verticalInput;
    public float speed = 10.0f;
    
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        horizontalInput = Input.GetAxis("Horizontal");
        verticalInput = Input.GetAxis("Vertical");
    }

    private void FixedUpdate()
    {
        rb.AddForce(new Vector3(horizontalInput, 0.0f, verticalInput) * speed); 
    }

}

Now drag and drop the C# script to the required game object.

Now run the project.

Output:

Leave a Reply

Your email address will not be published. Required fields are marked *