TransWikia.com

Attach movement to each list object

Game Development Asked by mavish on January 9, 2021

How would i move every sphere that gets spawned every 2 seconds ? Basically i want every sphere to follow the previous spawned sphere or even all N-1 spheres should follow the first spawned sphere along a predefined path and they should keep rolling as a train of spheres. I am lost when i try to imprint movement to each sphere.

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

public class Spawner : MonoBehaviour
{
    public GameObject[] prefabs;
    public List<GameObject> listBalls = new List<GameObject>();
    private GameObject x;
    public int timer = 0;
    private float movementSpeed = 5f;

    void Start()
    {
        createBall();
    }

    void Update()
    {
        if (Time.time - timer > 0.8f)
        {
            createBall();
            timer += 2;
        }
        listBalls[listBalls.Count-1].transform.position += new Vector3(0, 0, movementSpeed * Time.deltaTime);
    }

    void createBall()
    {
        x = prefabs[Random.Range(0, prefabs.Length)];
        Instantiate(x, x.transform.position, Quaternion.identity);
        listBalls.Add(x);
    }

    void moveBall(GameObject x, GameObject y)
    {
        x.transform.position += y.transform.position - new Vector3(0,0,-1);
    }
}

Loop added but movement staggered

        void Update()
    {
        if (Time.time - timer > 0.8f)
        {
            createBall();
            timer += 2;
        }
        foreach (GameObject item in listBalls)
        {
            item.transform.position += new Vector3(0, 0, movementSpeed * Time.deltaTime);
        }
    }

```

One Answer

There are several ways to do this, depending on how exactly you want the balls to move. Most solutions are going to use some kind of loop. If you aren't familiar with loops, you should read some tutorials on loops in C#.

Example 1: All balls move same direction/distance each frame

Vector3 movement = new Vector3(0, 0, movementSpeed * Time.deltaTime);

foreach (var ball in listBalls) {
    ball.transform.position += movement;
}

Example 2: Each ball moves towards the next ball

float distance = movementSpeed * Time.deltaTime;
//move the last ball
listBalls[listBalls.Count - 1].transform.position += new Vector3(0, 0, distance);

//move each ball (except the last) towards the next ball
for (int i = 0; i < listBalls.Count - 1; i++) { //note we don't want to move the last ball again
    Transform ball = listBalls[i].transform;
    Transform nextBall = listBalls[i + 1].transform;
    ball.position = Vector3.MoveTowards(ball.position, nextBall.position, distance);
}

Correct answer by Kevin on January 9, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP