- Home /
How to scroll the background in a 2D game
I'm creating a simple 2D scroll game (like flappy bird, character goes all the way to the right and the background & obstacles are automatically and repeatedly generated)
I created three backgrounds, left, middle and right, and place them next to each other. A script called scrolling is added to each background. The script goes:
public GameObject next
public int distance
void OnTriggerEnter2D(Collider2D c){
next.transform.Translate(new Vector3(distance,0,0));
Debug.Log("enter");
}
"left" acts as next for right, right for middle, and middle for left, so they pave the road ahead in turn on and on. A Physics2D trigger is placed on the background (which is a rectanglular sprite), as well as a circle collider on the main character. However, when the character enters...nothing at all happened. Even the log did not show. Does anyone know why this happened?
Or, after I rethought about it, would the reason be that I simply "translate" the main character to make it move in one direction? Since I want him to move uniformly in x direction. But would this make him a kinematic object, so that the collision with the trigger doesn't count?
Answer by Endless_Aftermath · Aug 13, 2014 at 09:57 PM
If the script posted above is on the background, then the Collider2D should be on the character, right? And it should have an option in the inspector for "Trigger", I think. I usually work with 3D and this is the way it works there. OR you could try putting the script above on the character, just change the code a bit to look like this...
void OnTriggerEnter2D(Collider2D c)
{
c.transform.Translate(new Vector3(distance,0,0));
Debug.Log("enter");
}//end of OnTriggerEnter2D()
no...actually the trigger is on the background, and the character has the collider. (since if both are colliders than character would bounce off the space) And what I would like would be to move the background so that the space infinitely extends, ins$$anonymous$$d of translating the main character himself.