I Want My Character To move On Specific Line With Script
I have Plane And Curvy Turn. currently I am Moving my Character Forward by 1 unity every second. now when character comes across "this Curvy Turn" I want it to be rotated 90' on the Y axis but slowly and gradually. and on the plane there are 3 lines on which character can walk (like in the android games "subway surfer" or "Sonic Dash" ).
i have collider to detect entry and exit
Can It Be done using WayPoints or something? just give me some hint.
thanks.
Answer by BigHandInSky · Feb 02, 2016 at 05:33 PM
You have a couple of options based on how accurate you want to be, but both will rely on using some form of loop to go through them:
Have a list/array of transform points,
Using a for loop, foreach point, until you reach the Count/Length of the block -
Move your player transform to the next point, and when (player.transform.position - array[loop].position).magnitude is less than a range you choose, increment the for loop
Continue until you have reached the end.
In code this translates to:
float nextPointRange = 5.0f;
Transform[] curveWaypointsArray;
Transform playerTransform;
// An IEnumerator makes this easier to start when needed,
// And also allows a greater degree of control over the movement
IEnumerator MoveThroughArray()
{
int loop = 0;
while(loop < curveWaypointsArray.Length)
{
//for simplicity just make the player face the next point each frame
playerTransform.LookAt(curveWaypointsArray[loop].position);
//while the player is not close to the next position, move forward
while((curveWaypointsArray[loop].position - playerTransform.position).magnitude > nextPointRange)
{
playerTransform.Translate(playerTransform.forward);
yield return new WaitForEndOfFrame();
}
//this makes each run of the while loop last a frame
yield return new WaitForEndOfFrame();
}
}
Now you can implement this in an update, but it will be a bit more scrappy than an IEnumerator like the one above, which will make doing this far easier to implement, so take an hour/two to read up on them. Hope this helps.
Yes, the "LookAt" function helped me. i am using it with virtual WayPoint, i don't really create wayPoints. i am calculating WayPoints, then using LookAt function to rotate my character accordingly.