Quantcast
Channel: Answers for "Array index confusion - what does [i-1] do exactly???"
Viewing all articles
Browse latest Browse all 8

Answer by ronronmx

$
0
0

Jessy, you're right there's something else going on in the code. Here's the full function below:

var topSpeed : float = 160;
var numberOfGears : int = 5;
private var gearSpeeds : float[];

function SetupGears()
{
    gearSpeeds = new float[numberOfGears];

    var tempTopSpeed : float = topSpeed;

    for(var i = 0; i < numberOfGears; i++)
    {
        if(i > 0){
            gearSpeeds[i] = tempTopSpeed / 4 + gearSpeeds[i-1];
            //Debug.Log("gearSpeeds if:  " + gearSpeeds[i]);
        }
        else{
            gearSpeeds[i] = tempTopSpeed / 4;
            //Debug.Log("gearSpeeds else:  " + gearSpeeds[i]);
        }

        tempTopSpeed -= tempTopSpeed / 4;
    }

}

As you can see, tempTopSpeed is being changed at the end of the loop:

tempTopSpeed -= tempTopSpeed / 4;

Can't believe I didn't catch that, sorry for the confusion.

I'm new to coding and especially arrays, so there are a few things that confuse me. For example, why divide topSpeed by (numberOfGears -1) instead of (numberOfGears)? Is it because arrays start at 0, so in order to divide topSpeed by the correct amount of gears in numberOfGears, you have to subtract 1? Sorry if this is a stupid question...it just doesn't register in my head yet :)


Viewing all articles
Browse latest Browse all 8

Latest Images

Trending Articles





Latest Images