1. 程式人生 > >unity3d實現廣告滑動效果

unity3d實現廣告滑動效果

ans cto 代碼 tag itween ngui logs lap image

新建了一個帶mask的prefab,加上代碼只需要將圖片prefab、按鈕prefab和所想添加的圖片

拖進去會自動生成按鈕,滑動速度可以隨意調time,滑動效果用itween實現的,所以需要加上itween插件

效果如下:(圖片是我最愛的馬路小天使(ˉ﹃ˉ))

技術分享技術分享

附上代碼

技術分享
 1 using UnityEngine;
 2 using System.Collections.Generic;
 3 using UnityEngine.UI;
 4 
 5 public class Mask : MonoBehaviour {
 6 
 7     public List<Sprite> sprite = new
List<Sprite>(); 8 List<GameObject> image=new List<GameObject >(); 9 public GameObject pic; 10 public Button but; 11 public float time; 12 float width, height; 13 int num; 14 void Start () 15 { 16 num = sprite.Count; 17 width = this
.gameObject.GetComponent<RectTransform>().rect.width; 18 height = this.gameObject.GetComponent<RectTransform>().rect.height; 19 pic.transform.GetComponent<RectTransform>().sizeDelta=new Vector2(width,height); 20 for (int i = 0; i < num; i++) 21 {
22 23 GameObject p = Instantiate(pic,new Vector3(transform.position.x+i*width,transform.position.y,0),transform.rotation)as GameObject; 24 p.transform.parent = this.gameObject.transform; 25 image.Add (p) ; 26 p.GetComponent<Image>().sprite = sprite[i]; 27 Button b = Instantiate(but, new Vector3(transform.position.x- ( 25 * num - 15) / 2+25*i, transform.position.y - height/2 + 15, 0), transform.rotation) as Button; 28 b.transform.parent = GameObject.FindWithTag("Button").transform; 29 System.Object obj = (System.Object)i; 30 b.onClick.AddListener(delegate(){this.MoveToPic((int)obj);}); 31 } 32 33 34 } 35 void OnGUI() 36 { 37 if (GUI.Button(new Rect(transform.position.x + 20 + width / 2, Screen.height - transform.position.y - 15, 30, 30), ">")) 38 { 39 if (image[0].transform.position.x < transform.position.x-3) 40 { 41 Move(1); 42 } 43 } 44 if (GUI.Button(new Rect(transform.position.x -width/2-50,Screen.height- transform.position.y-15 , 30, 30), "<")) 45 { 46 if (image[num - 1].transform.position.x > transform.position.x+3) 47 { 48 Move(-1); 49 } 50 } 51 } 52 public void Move(int dir) 53 { 54 for (int i = 0; i <num; i++) 55 { 56 iTween.MoveAdd(image[i], iTween.Hash("x", width * dir, "time", time)); 57 } 58 } 59 public void MoveToPic(int i) 60 { 61 62 float offset = transform.position.x - image[i].transform.position.x; 63 for (int j = 0; j < num; j++) 64 { 65 iTween.MoveAdd(image[j], iTween.Hash("x", offset, "time", time)); 66 } 67 } 68 69 70 }
View Code

unity3d實現廣告滑動效果