Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to correctly move backgrounds using texture offset

Discussion in '2D' started by RisingNebula, Jul 20, 2014.

  1. RisingNebula

    RisingNebula

    Joined:
    Aug 11, 2013
    Posts:
    5
    I am trying to create a moving 2d background for a platformer by offsetting the texture of a Quad (mainTextureOffset). The offset moves to match the camera movement, it sort of works, but instead of the texture tiling, i get some wacky effect. Anyone know what I am doing wrong?

    The code i am using is in a BackgroundScroller class attached to the background component.

    Code (CSharp):
    1. public class BackgroundScroller : MonoBehaviour {
    2.  
    3.     public static BackgroundScroller current;
    4.  
    5.     private float lastCameraPos;
    6.  
    7.     void Start () {
    8.        
    9.         lastCameraPos = Camera.main.transform.position.x;
    10.        
    11.     }
    12.  
    13.     void Update () {
    14.        
    15.         float shift = Camera.main.transform.position.x - lastCameraPos;
    16.         lastCameraPos = Camera.main.transform.position.x;
    17.         Vector2 offset = renderer.material.mainTextureOffset;
    18.        
    19.         offset.x += +shift * 0.01f;
    20.    
    21.         renderer.material.mainTextureOffset = new Vector2 (offset.x, 0);
    22.     }
    23. }
    Do i need to check the offset.x on update and move the texture manually once its off screen?
    Thanks

     
  2. ClintSiu

    ClintSiu

    Joined:
    Jun 15, 2014
    Posts:
    19
    Is the Wrap Mode in your texture set to Repeat?
     
  3. RisingNebula

    RisingNebula

    Joined:
    Aug 11, 2013
    Posts:
    5
    No I didn't! (still noob'n it out).
    Thats great, thanks a lot.

    also, logging the offset.x i notice that the x pos keeps increasing and does not reset. Is there any issue with this? Is it beneficial to reset the offset manually? example:
    Code (CSharp):
    1. if (offset.x >= 0.1f) {
    2. offset.x -= 0.1f;
    3. }