- Home /
Make the character follow the images one by one smoothly
I'm working on a 2D simple game, and what I want to ask is I want to make my character follow the path I already made in images object. So, I made a lot of images one by one, and then I put them in the array. I want to make my character to follow them one by one smoothly, but I just can make my character follow one of them. Here is the example :
And this is the code for making the character move, I use loop, but it seems like the character just goes to the end of the loop.
public image[] route;
public GameObject character;
private Vector2 startpos;
private float timelerp = 2f;
private float currentlerptime = 0;
void Start()
{
startpos = character.transform.position;
}
void Update()
{
currentlerptime += Time.deltaTime;
if (currentlerptime >= timelerp)
{
currentlerptime = timelerp;
}
float perc = currentlerptime / timelerp;
for (int i=0; i<5; i++)
{
character.transform.position = Vector2.Lerp(startpos, jalur[i].transform.position, perc);
}
}
Answer by LCStark · Oct 06, 2018 at 01:18 PM
The code in your Update
function is executed during a single frame, so your loop moves your character through all the images in the array so fast you can't see it.
Add a new int
field which will serve as a marker, holding the index of the image you are moving to at this time. Set its value to 0 in your Start
method. Remove your loop in the Update
function and leave the character.transform.position
change the way it is. Use your new int field instead of the i
iterator of the loop to select a proper image.
After you've changed your position, check if your perc
value has reached 1.0f
(or if your currentlerptime
is equal to timelerp
) to check whether you have reached the next image yet.
If you have reached the target position, you can increment your image counter. Just be sure to check whether you are still within the range of your array when you run your Update
method:
void Update() {
if (counter > 4) return;
...
}
Your answer
Follow this Question
Related Questions
How to find total distance from start to end of an array which stores positions in vector3? 2 Answers
Child GameObject is aligned to world axis and not the parents axis (UPDATE) 1 Answer
why one works, the other does not 2 Answers
Moving an object object x pos + speed?? 0 Answers
How do i make my background keep the same position as my character? 0 Answers