Advertisement
daviddevel

parallax

Oct 23rd, 2014
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. using UnityEngine;
  2. using System .Linq;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5.  
  6.  
  7. public class Parallax : MonoBehaviour {
  8.  
  9. public Vector2 speed = new Vector2(1,1);
  10. public Vector2 direction = new Vector2(-1,0);
  11.  
  12. public bool isLooping = false;
  13. private List <Transform> backgroundPart;
  14.  
  15.  
  16. // Use this for initialization
  17. void Start () {
  18.  
  19. if(isLooping)
  20. {
  21. backgroundPart = new List<Transform>();
  22.  
  23. for (int i = 0; i < transform.childCount; i++){
  24.  
  25. Transform child = transform.GetChild(i);
  26.  
  27. if (child.renderer != null)
  28. {
  29. backgroundPart.Add (child);
  30. }
  31. }
  32. backgroundPart = backgroundPart
  33. .OrderBy(t =>t.position.x).ToList();
  34.  
  35.  
  36. }
  37. }
  38.  
  39. // Update is called once per frame
  40. void Update () {
  41.  
  42. Vector2 movement = new Vector2 (
  43. speed.x * direction.x,
  44. speed.y * direction.y);
  45. movement*= Time.deltaTime;
  46.  
  47. transform.Translate (movement);
  48.  
  49. if (isLooping)
  50. {
  51. Transform firstChild = backgroundPart.FirstOrDefault();
  52.  
  53. if (firstChild !=null)
  54. {
  55. if(firstChild.position.x < Camera.main.transform.position.x)
  56. {
  57. if(!firstChild.renderer.IsVisibleFrom(Camera.main))
  58. {
  59. Transform lastChild = backgroundPart.LastOrDefault();
  60.  
  61. Vector3 lastPosition = lastChild.position;
  62.  
  63. Vector3 lastSize = (lastChild.renderer.bounds.max - lastChild
  64. .renderer.bounds.min);
  65.  
  66.  
  67. firstChild.position = new Vector3(
  68. lastPosition.x + lastSize.x,
  69. firstChild.position.y,
  70. firstChild.position.z);
  71. backgroundPart.Remove(firstChild);
  72. backgroundPart.Add(firstChild);
  73. }
  74. }
  75. }
  76. }
  77. }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement