3-D Game Development: Moving Objects in Unity 3D

3-D Game Development: Moving Objects in Unity 3D

Hola, this week we will continue the previous article. I recommend you to follow my previous article to work on this current article. In this article, we will be moving the 3D objects in the game we are developing using C# language. Let’s dig into it.

First, we will create a 3D wall object, which will be moving infinite time over the screen. Go to the Assets -> Fantasy Demo Caves -> FBX. Drag the stone_bridge object to the scene view.

Then, right-click in the hierarchy window, select the create empty. It will create an empty GameObject. Drag the stone_bridge assets in the wall object. As you can see in the image. Now, we will duplicate the stone_bridge assets. One can do this by pressing Ctrl + D or CMD + D. Drag new duplicated assets below the original. Create a wall-like structure as shown in the image.

Navigate to the Project window, Create a scripts folder in the assets folder. In scripts, create a C# file by right-clicking in the empty space. Give the filename as Objects. Now, we have to assign the code to assets. This can be done, by dragging the Objects C# file to Wall GameObject in the Hierarchy Window. By doing this, whatever code written in the file is executed on that particular GameObject. Here in our case, it will execute on the Wall GameObject.

Here comes, Coding Part

This is the code to move the wall continuously infinite time. Remember, you have to change the value of resetPosition and value in Vector3 objects’ argument. Because every device has different coordinates. To know the current coordinates of the GameObject, select the particular object. It will show every coordinate in the Inspector window.

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

public class Objects : MonoBehaviour
{
    [SerializeField] private float objectSpeed = 5; 
    private float resetPosition = -168.5f;
    // Start is called before the first frame update
    void Start(){
    
    }

    // Update is called once per frame
    void Update(){
        transform.Translate(Vector3.left * (objectSpeed * Time.deltaTime));    
        if(transform.localPosition.x <= resetPosition){
            Vector3 newPos = new Vector3(-77.9f, transform.position.y, transform.position.z);
            transform.position = newPos; 
        }
    }
}

Let’s Run

Press the play button, you can see that wall is moving continuously. Well done, you can now move the steady object in Unity 3D. Great progress. You can also access the project from the public machine of the sandbox.

Credit: https://concordia.udemy.com/course/devslopes-unity3d/