Move forward with constant speed in Unity using C#
You may have played video games where the player moves forward with a constant speed and overcomes some obstacles by moving sidewise. Well, you can do this same kind of thing in Unity with the help of C# programming.
In this tutorial, I will show you how to move a GameObject in the forward direction at a constant speed in Unity using C# coding.
To achieve this task for our player, we have to attach our C# script to the player GameObject. After that, we have the C# code given below to move our player in the forward direction:
using UnityEngine; public class CharacterControllerSC : MonoBehaviour { public float movingSpeed = 3f; void Update() { transform.Translate(Vector3.forward * movingSpeed * Time.deltaTime); } }
In the above code, we have first defined a public variable movingSpeed
that accepts float value. I have assigned 3 to this variable. As you can see, I have set it as public, so you can change its value from the inspector also.
Next in the Update()
method, we are moving the object in the forward direction with a constant speed of 3 using the transform.Translate()
method. In the below gif image, you can see how it will work:
Note that, I have multiplied Vector3.forward
the speed of the object movingSpeed
multiplied by Time.deltaTime
. Multiplying by Time.deltaTime is very important because it ensures that the movement of the GameObject is frame-rate independent. Otherwise, it changes the movement speed depending on the change in the frame rate.
Leave a Reply