How to make an object move in the direction it’s facing in Unity

Sometime we have to move the object forward in a game. We can do that in a few simple steps.

In this tutorial, we will see how to make an object move forward in the direction it’s facing.

In our post on Unity Vector3, we had discussed vector3.forward function, the same is available for transform. We will use that to find the direction the object is facing and then take our input and multiply to that.

First, we need a speed input to define how fast we need to move in the forward direction.

We will clamp the variable to not go below zero using mathf.clamp as we don’t want the object to move in the backward direction.

We will use transform.Translate to move the object in the forward direction.

Here is the final working code. Just add this script to the object you want to move.

using UnityEngine;

public class move: MonoBehaviour
{
    float speed=1;

    // Update is called once per frame
    void Update()
    {
        
       speed+=Input.GetAxis("Vertical")*Time.deltaTime; 
       speed=Mathf.Clamp(speed,0,100);
       Debug.Log(speed);        
       transform.Translate(transform.forward*Time.deltaTime*speed,Space.World);

        
    }
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from VionixStudio

Subscribe now to keep reading and get access to the full archive.

Continue reading