- Home /
Vector3[]?
A friend of mine was showing me a few things that you could do. This was one of them:
Vector3[] curPos = new Vector3[place];
timeI += Time.deltaTime;
float z = omegaZ * timeI;
float y = Mathf.Abs (amplitudeY * Mathf.Sin (omegaY * timeI));
eSpawn.eSnake [place].transform.position = new Vector3 (0.0f, y + curPos[place].y , z + curPos[place].z);
place++;
if (place == 5)
{
place = 0;
}
Problem is, it doesn't seem to work as I thought it did. And everytime the code reaches the line
eSpawn.eSnake [place].transform.position = new Vector3 (0.0f, y + curPos[place].y , z + curPos[place].z);
It stops running.
What am I doing wrong?
I'm basically trying to get the current position of each object in a list, and then change that position. Otherwise it snaps to 0,0,0 which doesn't work well for what I want.
@mattyman174 Coding really doesn't care about whitespace. If it was to care it would cause a compiler error ins$$anonymous$$d and the code would not run at all.
The Vector3 array (curPos) has a fixed size of 'place'. That means the largest index you can read out of this array is [place - 1] since the first element in the array is zero (0).
So if you want to get last item rewrite the line 5 as follow:
eSpawn.eSnake [place].transform.position = new Vector3 (0.0f, y + curPos[place - 1].y , z + curPos[place - 1].z);
And the other thing to check is: Does the eSnake array/list have the right size.
You could do the incrementation in modulus space:
place = ++place % curPos.Length;
This way you ensure that the index does not overflow the size of the array.
How does it stops running ? Do you get an error message in the console ? An exception ? NullRef or ArgumentOutOfRange maybe ? Or does it leaves the function and just keep going, ignoring your code ? By the way, is that piece of code inside a Unity loop (Update, for instance), or a ponctual function (Start) ?
Answer by RaulG · Jan 13, 2015 at 09:47 AM
public int place;
public List<Vector3> posList = new List<Vector3>();
public void Snaker()
{
posList.Add (new Vector3 (eSpawn.eSnake [place].transform.position.x,
eSpawn.eSnake [place].transform.position.y,
eSpawn.eSnake [place].transform.position.z));
Vector3 v = posList [0];
timeI += Time.deltaTime;
float z = omegaZ * timeI;
float y = Mathf.Abs (amplitudeY * Mathf.Sin (omegaY * timeI));
eSpawn.eSnake [place].transform.position = new Vector3 (0.0f, y + v.y , z + v.z);
place++;
if (place == 5)
{
place = 0;
}
}
I switched over to a list, changed posList to 0, and parented the objects to a main object. Works semi right. Now I just need to add a delay between movements and I think it'll be okay.
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Plotting particle movement Time/keyframe issue 0 Answers
Stopping Vector3.Lerp 3 Answers
Choppy y-axis crane movement when grabbing food, not dropping food on target 0 Answers
GameObject wont stop rotating ? 1 Answer