简体   繁体   中英

How to create a movement queue using an array with C# and Unity 3D

I've created seven different GameObjects and added them to a Vector3 array to create a line queue. What I'm trying to achieve is a rotative movement where the first object assumes the 7th position, the second object assumes the first position and so on.

I would like your help to make the function move this objects. This is what I have so far:

using UnityEngine;
using System.Collections;

public class StairsController : MonoBehaviour {

    public GameObject[] degrau;
    Vector3[] positionArray = new Vector3[7];

    private int i = 6;
    private int a = 6;

    // Use this for initialization
    void Start () {
        positionArray [i-6] = degrau[a-6].transform.position; 
        Debug.Log (positionArray [i-6]);

        positionArray [i-5] = degrau[a-5].transform.position;
        Debug.Log (positionArray [i-5]);

        positionArray [i-4] = degrau[a-4].transform.position;
        Debug.Log (positionArray [i-4]);

        positionArray [i-3] = degrau[a-3].transform.position;
        Debug.Log (positionArray [i-3]);

        positionArray [i-2] = degrau[a-2].transform.position;
        Debug.Log (positionArray [i-2]);

        positionArray [i-1] = degrau[a-1].transform.position;
        Debug.Log (positionArray [i-1]);

        positionArray [i] = degrau[a].transform.position;
        Debug.Log (positionArray [i]);
    }

    public void SimpleMov (){
        // i need help here
        degrau [a].transform.position = positionArray [i - 1];
    }
}

But this is not working as it should because it's not making a rotative movement. How can I fix it in order to achieve this movement.

Thank you!

This modified modulo function will give you the index selected (typically i+1), but if you exceed the bounds of the length it will loop back to the front.

So if you want the 8th index of a 7-long array you will return 0 (back to the start).

int mod(int i, int m) { return ((i % m) + m) % m; }

// Set this to 0 inside of Start()
int startIndex;

public void SimpleMov (){
    int positionIndex = startIndex;
    for (int i = 0 ; i < degrau.Length ; i++) 
    {
        positionIndex++;
        degrau[i].transform.position = positionArray [mod(positionIndex, positionArray.Length)]
    }
    startIndex++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM