How to smooth a scrolling object in Unity 3D

2.1k Views Asked by At

all.

I am making a mobile game in Unity, and it's a side-scroller. I want a platform to move across the screen until it gets off-screen. Then, I will set its position back to the starting point, so that the scrolling appears infinite. Here's my code:

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

public class ScrollingObject : MonoBehaviour
{
    public float speed;
    Vector3 startPos;

    void Start()
    {
        startPos = transform.position;
    }

    void Update()
    {

        transform.Translate ((new Vector3 (-1, 0, 0)) * speed * Time.deltaTime);

        if (transform.position.x < -22.71982) 
        {
            transform.position = startPos; 
        }

    }

}

This works, but it appears sort of choppy, and not smooth. Does anyone have any advice to make this platform move a bit smoother? Thanks in advance.

2

There are 2 best solutions below

0
David On

A better idea is to create two such game objects, one is current, another will be created at run-time, when the current object is about to leave off the screen. You might create a prefab, and then instantiate that at the right time:

Instantiate(YourPrefab, new Vector3(0, 0, 0), Quaternion.identity); 

After the new prefab instance comes into the view, keep it as the new current one, and remove the old one.

--------------------- Time ----------------------->
| Current (A) | Next Current (B) |
-------------------------------------------------->
              | 
              v
         screen edge here


 --------------------- Time ----------------------->
| Old Current (A) | Current (B) |
--------------------------------------------------->
        |                       | 
        v                       v
   To be destroyed         screen edge here
0
Ajjo On

Create two or more copies (as per your requirement) of the prefab and maintain an object pool. The purpose of the pool is to avoid destroying objects and creating them again. Simply disable the object and activate them when it is time for it to come on screen. Keep swapping or changing the index as you scroll. This avoids memory fragmentation and any computation you may have in the initialisation step (in start() or awake()) of a game object.