Unity抽奖老虎机水果机项目源码 for NGUI

做了一个老虎机的demo。效果如下。

1

示例(不是图片。点击可看效果):

Unity Web Player. Install now!
Unity Web Player. Install now! Restart your browser after install.

图片

2

 

如上图。主要就四个脚本:

入口脚本:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Holoville.HOTween;
using Holoville.HOTween.Plugins;

/// <summary>
/// 老虎机管理
/// </summary>
public class SlotMachine : MonoBehaviour
{
    #region 数据定义

    /// <summary> 物体的预设模型 </summary>
    public GameObject cellItemPrefab;
    public GameObject cellItemPrefab2;

    /// <summary> 所有列对象 </summary>
    Transform[] lines;

    /// <summary> 所有列脚本 </summary>
    public Tile[] items;

    /// <summary> 是否可以旋转 </summary>
    public bool isAuto = false;

    /// <summary> 物体大小 </summary>
    public Vector3 cellSize = new Vector3(1.6f, 1.4f, 1f);


    /// <summary> 声音文件 </summary>
    public AudioSource spinSound, stopSound, cashSound;

    Line[] lineList;

    /// <summary> 总列数 </summary>
    int totalLine = 3;

    /// <summary> 是否可以点击旋转 </summary>
    bool isInput = true;

    /// <summary> 物品种类 </summary>
    int totalSymbols;

    #endregion

    #region 数据初始化
    void Start()
    {
        totalSymbols = PayData.totalSymbols;

        InitArena();
        isInput = true;
    }

    #endregion

    #region 游戏内容初始化

    /// <summary>  初始化游戏界面 对象网格  </summary>
    void InitArena()
    {
        lines = new Transform[totalLine];
        lineList = new Line[totalLine];

        // 创建列数循环
        for (int i = 0; i < totalLine; i++)
        {
            //每列父物体
            GameObject pgo = new GameObject();
            pgo.name = "Base" + (i + 1).ToString("000");
            pgo.transform.parent = transform;
            pgo.transform.localScale = Vector3.one;
            pgo.transform.localPosition = Vector3.zero;
            //总个数父物体。方便滚动
            GameObject go = new GameObject();
            go.transform.parent = pgo.transform;
            Line script = go.AddComponent<Line>();
            script.idx = i;

            Transform tf = go.transform;
            lines[i] = tf;
            tf.parent = pgo.transform;

            tf.localPosition = new Vector3(-135 + i * 135, 0, 0);//(i - 4.5f) * Vector3.right * cellSize.x + Vector3.forward * cellSize.y;
            tf.localScale = Vector3.one;
            go.name = "Line" + (i + 1).ToString("000");

            script.items = new Tile[PayData.totalCell];
            // 每列物品个数循环
            for (int j = 0; j < PayData.totalCell; j++)
            {
                GameObject g = Instantiate(cellItemPrefab) as GameObject;
                g.name = "Tile" + (j + 1).ToString("000");
                Transform t = g.transform;
                Tile c = g.GetComponent<Tile>();
                c.slotMachine = this;
                c.SetTileType(Random.Range(0, totalSymbols) % totalSymbols);
                c.lineScript = script;
                script.items[j] = c;
                c.idx = j;
                t.parent = tf;
                t.localPosition = new Vector3(0,270 - j *90,0);//Vector3.forward * j * cellSize.y;
                t.localScale = Vector3.one;
                t.localRotation = Quaternion.identity;
            }
            script.idx = i;
            lineList[i] = script;
        }
        GameObject obj = Instantiate(cellItemPrefab2) as GameObject;
        obj.transform.parent = transform.parent.parent;
        obj.transform.localEulerAngles = Vector3.zero;
        obj.transform.localScale = Vector3.one;
        obj.transform.localPosition = new Vector3(0,-285,0);
        items = GetComponentsInChildren<Tile>();
    }

    #endregion

    #region 点击开始游戏
    /// <summary>
    /// 开始旋转 (点击按钮调用)
    /// </summary>
    public void DoSpin()
    {
        if (isAuto) return;
        Spin();
    }
    /// <summary> 执行旋转 </summary>
    void Spin()
    {
        if (!isInput) return;
        //ClearChoice();
        DoRoll();
        spinSound.Play();
    }


    /// <summary> 发消息开始转动并等待转动结束 </summary>
    void DoRoll()
    {
        for (int i = 0; i < totalLine; i++)
        {
            Transform line = lines[i];
            //开启协同
            StartCoroutine(RepeatAction(0.1f, 8 + i * 3, () =>
            {
                line.SendMessage("RollCells", true, SendMessageOptions.DontRequireReceiver);
            }, () =>
            {
                stopSound.Play();
            }, () =>
            {
                line.SendMessage("RollCells", false, SendMessageOptions.DontRequireReceiver);
            }));
        }
        //设置当前不能点击
        isInput = false;
        
        //开启协同
        StartCoroutine(DelayAction(2.2f, () =>
        {
            isInput = true;
            FindMatch();
        }));
    }

    /// <summary>
    /// 延迟协同方法
    /// </summary>
    /// <param name="dTime"></param>
    /// <param name="callback"></param>
    /// <returns></returns>
    IEnumerator DelayAction(float dTime, System.Action callback)
    {
        yield return new WaitForSeconds(dTime);
        callback();
    }

    /// <summary>
    /// 延迟协同方法
    /// </summary>
    /// <param name="dTime"></param>
    /// <param name="count"></param>
    /// <param name="callback1"></param>
    /// <param name="callback2"></param>
    /// <param name="callback3"></param>
    /// <returns></returns>
    IEnumerator RepeatAction(float dTime, int count, System.Action callback1, System.Action callback2, System.Action callback3)
    {
        if (count > 1) callback1();
        else callback3();
        if (--count > 0)
        {
            if (count == 1) callback2();
            yield return new WaitForSeconds(dTime);
            StartCoroutine(RepeatAction(dTime, count, callback1, callback2, callback3));
        }

    }

    /// <summary> 查找匹配的物品 </summary>
    void FindMatch()
    {
        List<int> obtain = new List<int>();
        for (int i = 0; i < lines.Length; i++)
        {
            Line lin = lines[i].GetComponent<Line>();
            for (int j = 0; j < lin.items.Length; j++)
            {
                float y = lin.items[j].transform.localPosition.y;
                if (y <= 10 && y >= -30)
                {
                    obtain.Add(lin.items[j].GetTileType());
                    //break;
                }
            }
        }
        //获得物品
        Debug.LogError("获得物品类型:" + obtain[0] + "__" + obtain[1] + "___" + obtain[2]);
    }
    #endregion
}

列管理脚本:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Holoville.HOTween;
using Holoville.HOTween.Plugins;

/// <summary>
/// 列数管理脚本
/// </summary>
public class Line : MonoBehaviour 
{
    // line order
    public int idx = 0;

   /// <summary>
   /// 该列的所有子物体
   /// </summary>
    public Tile[] items;

    /// <summary>
    /// 按时间顺序排序 开始滚动
    /// </summary>
    /// <param name="isLinear">是否往下运动。否 往上</param>
    public void RollCells(bool isLinear)
    {
        List<Tile> tlist = new List<Tile>();
        int y = 0, t = 7;
        int totalSymbols = PayData.totalSymbols;

        int index1 = PayData.totalCell - 1;

        if (PayData.down)
        {

            for (int i = index1; i < PayData.totalCell; i++)
            {
                tlist.Add(items[i]);
                items[i].idx = y++;
                items[i].MoveTo(0);
                int total = totalSymbols;
                if (idx == 0 || idx == 4) total--;
                //随机显示物品
                items[i].SetTileType(Random.Range(0, total) % total);
            }
            for (int i = 0; i < index1; i++)
            {
                tlist.Add(items[i]);
                items[i].idx = y++;
            }
        }
        else
        {
            for (int i = 1; i < PayData.totalCell; i++)
            {
                tlist.Add(items[i]);
                items[i].idx = y++;
            }
            for (int i = 0; i < 1; i++)
            {
                tlist.Add(items[i]);
                items[i].idx = y++;
                items[i].MoveTo(t++);
                int total = totalSymbols;
                if (idx == 0 || idx == 4) total--;
                //随机显示物品
                items[i].SetTileType(Random.Range(0, total) % total);
            }
        }

        items = tlist.ToArray();
        for (int i = 0; i < 7; i++)
        {
            items[i].TweenMoveTo(i, isLinear);
        }
    }
}

单个物品管理:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Holoville.HOTween;
using Holoville.HOTween.Plugins;

/// <summary>
/// 单个物品管理
/// </summary>
public class Tile : MonoBehaviour
{
    public SlotMachine slotMachine;

    /// <summary>  物品排序 </summary>

    public int idx = 0;


    public UISprite sprites;
    SpriteRenderer shapeRenderer;
    SpriteRenderer choideRenderer;

    /// <summary> 所属的行 </summary>
    public Line lineScript;


    /// <summary>
    /// 设置显示图片
    /// </summary>
    /// <param name="type"></param>
    public void SetTileType(int type)
    {
        _type = type;
        sprites.spriteName = PayData.itemName[type];
    }

    private int _type;
    /// <summary> 获取类型 </summary>
    public int GetTileType()
    {
        return _type;
    }

    /// <summary>
    ///  将最下一个移动到最顶部
    /// </summary>
    /// <param name="seq"></param>
    public void MoveTo(int seq)
    {
        //Debug.LogWarning(seq);
        transform.localPosition = new Vector3(0, 270 - seq * 90, 0);
    }

    /// <summary>
    /// 开始移动和渐变动画
    /// </summary>
    /// <param name="seq"></param>
    /// <param name="isLinear"></param>
    public void TweenMoveTo(int seq, bool isLinear)
    {
        if (isLinear)
            TweenMove(transform, transform.localPosition, new Vector3(0, 270 - seq * 90, 0));
        else
            TweenMove2Back(transform, transform.localPosition, new Vector3(0, 270 - seq * 90, 0), new Vector3(0, 250 - seq * 90, 0));//250稍微修改一点。实现反弹效果
    }

    /// <summary>
    /// 移动和渐变动画
    /// </summary>
    /// <param name="tr">需要移动的物体</param>
    /// <param name="pos1">开始位置</param>
    /// <param name="pos2">结束位置</param>
    void TweenMove(Transform tr, Vector3 pos1, Vector3 pos2)
    {
        tr.localPosition = pos1;
        TweenParms parms = new TweenParms().Prop("localPosition", pos2).Ease(EaseType.Linear);
        HOTween.To(tr, 0.1f, parms);
    }

    /// <summary>
    /// 网上反弹移动效果动画
    /// </summary>
    /// <param name="tr">移动物体</param>
    /// <param name="pos1">开始位置</param>
    /// <param name="pos2">反弹位置</param>
    /// <param name="pos3">结束位置</param>
    void TweenMove2Back(Transform tr, Vector3 pos1, Vector3 pos2, Vector3 pos3)
    {
        tr.localPosition = pos1;
        SequenceParms sparams = new SequenceParms(); //.OnComplete(tr, "OnCompleteTween", 1);
        Sequence mySequence = new Sequence(sparams);
        TweenParms parms;
        parms = new TweenParms().Prop("localPosition", pos2).Ease(EaseType.Linear);
        mySequence.Append(HOTween.To(tr, 0.1f, parms));
        parms = new TweenParms().Prop("localPosition", pos3).Ease(EaseType.Linear); //.OnComplete(OnCompleteMove);
        mySequence.Append(HOTween.To(tr, 0.1f, parms));
        mySequence.Play();
    }

    IEnumerator DelayAction(float dTime, System.Action callback)
    {
        yield return new WaitForSeconds(dTime);
        callback();
    }
}

配置脚本:

using UnityEngine;
using System.Collections;

/// <summary>
/// 配置
/// </summary>
public class PayData 
{
    /// <summary> 物品种类 </summary>
    public static int totalSymbols = 7;
    /// <summary> 图标配置 </summary>
    public static string[] itemName = new string[7] { "icon_fangyu", "icon_g_shayu", "icon_gaiputi", "icon_haigui", "icon_jinqiangyu_gold", "icon_sale_coin_1", "icon_sale_crystal_1" };
    /// <summary> 滚动方向 </summary>
    public static bool down = true;
    /// <summary> 每列个数 </summary>
    public static int totalCell = 7;
}

最后。结构:

1

绑定每个物品的模型即可.同时绑定上3个音效.模型上绑上每个物品管理脚本如下:

2

 

工程下载地址(请自行导入 NGUI 3.x 版本):

 链接:http://pan.baidu.com/s/1eQti0JC 密码:1he5

如上.只要绑定一个显示UISprite既可。

本文链接:

https://bobsong.cn/569.html
1 + 2 =
10 评论
    2015年01月22日 回复

    可否传一份工程,很想参考一下工程!

      2015年01月22日 回复

      @闫亚珍 可以,等下晚上下班回家上传下

        2015年01月22日 回复

        @小宝 谢谢 我想看参考一下NGUI滚轴控制那一块的

          2015年01月22日 回复

          @闫亚珍 那个是用 HOTween 做的滚动。其他的用的NGUI。

            2015年01月22日

            @小宝 噢,我已经加你微信了,想和大牛聊一下,行吗?

            2015年01月22日

            @闫亚珍 已上传。我不是大牛。我是菜鸟

    最佳演员
    2015年05月27日 回复

    大神,这代码太刁了,Java渣渣看的很吃力

      最佳演员
      2015年05月27日 回复

      @最佳演员 请问大神的微信或者群是多少哟

        2015年05月27日 回复

        @最佳演员 博客里都有呢。右上角。

    2016年01月10日 回复

    不错,下载下来学习学习[嘻嘻]