How do I move a prefab the same speed as my scrolling background?
So, I followed the first example in this tutorial, to get a forever scrolling background: https://unity3d.com/learn/tutorials/topics/2d-game-creation/2d-scrolling-backgrounds
So, I'm using the two quads, that moves with mathf.repeat, with the following move code:
float newPosition = Mathf.Repeat(Time.time * ScrollSpeed, tileSizeZ);
transform.position = startPosition + Vector3.left * newPosition;
Now, I would like to have some obstacles (prefabs) spawn, and move at the same speed as the background, for the player to avoid. I can't seem to get this to work though.
I have tried two different approaches.
Change the position of the instantiated prefab.
Add translation to the instantiated prefab.
1 works great, using this code:
transform.position = startPosition + Vector3.left * (script.ScrollSpeed * Time.time);
(where script.Scrollspeed
is the scrollspeed from the background), except that because I'm using Time.time, it starts setting their spawn position too far in. So only the first spawned obstacle is actually correct.
I've tried to compensate somehow, for the passed time, but can't find a way that works.
2 I've tried with something like this:
transform.Translate(Vector3.left * script.ScrollSpeed * Time.deltaTime);
But it seems to always go just a little bit slower than the background.
So, any ideas on how to get this in sync? I kind of like option 1, and feel like it shouldn't be that difficult to compensate, I just haven't been able to figure out how.
Your answer
Follow this Question
Related Questions
Stop movement on collision 1 Answer
1st Person shooter, move player forward where cam is facing 1 Answer
2D moving Script 1 Answer
My 2d movement script isn't working 0 Answers