Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

First, running lantern raffle

Effect: Design idea:

  • Click the button, according to the demand (probability) calculation of this lucky draw to win items
  • Simulate rotation (first accelerating and then decelerating) and stop after a period of time

Scene construction: One button, one group prize (placed on a parent object), one halo (the currently selected prize)

Implementation code:

using System.Collections;
using UnityEngine;
using UnityEngine.UI;

public class RotaryTablePanel : MonoBehaviour
{
    // Lucky draw button,
    public Button drawBtn;
    // Draw pictures parent object
    public Transform rewardImgTran;
    / / the aura
    public Transform HaloImgTransform;
    // Draw pictures
    private Transform[] rewardTransArr;

    // Default display state
    private bool isInitState;
    // End of lottery -- end of state, halo does not turn
    private bool drawEnd;
    / / the winning
    private bool drawWinning;
    
    // Display status time --> control the rotation speed of the halo
    private float rewardTime = 0.8 f;
    private float rewardTiming = 0;

    // Index of the current aura reward
    private int haloIndex = 0;
    // This time the winning ID
    private int rewardIndex = 0;
    
    // Click the lucky draw button
    private bool isOnClickPlaying;
    
    void Start()
    {
        drawBtn.onClick.AddListener(OnClickDrawFun);
        rewardTransArr = new Transform[rewardImgTran.childCount];
        for (int i = 0; i < rewardImgTran.childCount; i++)
        {
            rewardTransArr[i] = rewardImgTran.GetChild(i);
        }
        
        // Default display time
        rewardTime = 0.6 f;
        rewardTiming = 0;
        
        drawEnd = false;
        drawWinning = false;
        isOnClickPlaying = false;
    }

    
    void Update()
    {
        if (drawEnd) return;
        
        // Lucky draw display
        rewardTiming += Time.deltaTime;
        if (rewardTiming >= rewardTime)
        {
            rewardTiming = 0;
            haloIndex++;
            if (haloIndex >= rewardTransArr.Length)
            {
                haloIndex = 0; } SetHaloPos(haloIndex); }}// Set the halo display position
    void SetHaloPos(int index)
    {
        HaloImgTransform.position = rewardTransArr[index].position;

        // win && this ID == win ID
        if (drawWinning && index == rewardIndex)
        {
            isOnClickPlaying = false;
            drawEnd = true;
            //todo... Display winning items and maintain data --> Note: index is an index
            Debug.Log("Congratulations on your winning. The index of the winning item is:" + index + "No."); }}// Click the lucky draw button
    void OnClickDrawFun()
    {
        if(! isOnClickPlaying) {// Select an ID at random
            rewardIndex =  Random.Range(0, rewardTransArr.Length);
            Debug.Log("Lucky draw begins. The random ID of this lucky draw is:" + rewardIndex);
            isOnClickPlaying = true;
            drawEnd = false;
            drawWinning = false; StartCoroutine(StartDrawAni()); }}/// <summary>
    ///Start the raffle animation
    ///Fast then slow - adjust the time according to demand
    /// </summary>
    /// <returns></returns>
    IEnumerator StartDrawAni()
    {
        rewardTime = 0.8 f;
        / / to accelerate
        for (int i = 0; i < 7; i++)
        {
            yield return new WaitForSeconds(0.1 f);
            rewardTime -= 0.1 f;
        }

        yield return new WaitForSeconds(2f);
        / / to slow down
        for (int i = 0; i < 5; i++)
        {
            yield return new WaitForSeconds(0.1 f);
            rewardTime += 0.1 f;
        }
        
        yield return new WaitForSeconds(1f);
        drawWinning = true; }}Copy the code

Two, the turntable lottery

Effect: Design idea:(Similar to above)

  • Click the button, according to the demand (probability) calculation of this lucky draw to get the item index
  • Calculate the required rotation Angle based on the random index
  • Simulate rotation and stop at the calculated Angle after a period of time

Scene construction: A button, a dial, a pointer;

Implementation code:

using UnityEngine;
using UnityEngine.UI;

public class RotaryDrawDemo : MonoBehaviour
{
    / / wheel
    public Transform RotateTableTrans;
    // Lucky draw button
    public Button DrawBtn;

    // The number of regions in the turntable --
    private int rotateTableNumber = 10;
    
    // Rotate the animation time
    private float rotateTime = 3f;
    private float rotateTiming = 0f;

    /// <summary>
    ///Target position to be rotated to
    /// </summary>
    private Quaternion targetAngels = Quaternion.identity;

    // Speed of rotation
    private float rotateSpeed = 20;
    // Simulate the selection time of the lottery
    private float RotateTime = 3f;

    /// <summary>
    ///Whether to start raffle rotation
    /// </summary>
    private bool isStartRotate = false;
    // This time the winning ID
    private int rewardIndex = 0;

    void Start()
    {
        DrawBtn.onClick.AddListener(OnClickDrawFun);
    }

    void Update()
    {
        if(! isStartRotate)return;
        
        rotateTiming += Time.deltaTime;
        // The animation time has passed
        if (rotateTiming >= RotateTime)
        {
            RotateTableTrans.Rotate(Vector3.back * 2);
            // Calculate the Angle between the current rotation Angle and the target Angle
            if (Quaternion.Angle(RotateTableTrans.rotation, targetAngels) <= 2)
            {
                // Set the target Angle
                RotateTableTrans.rotation = targetAngels;
                // The rotation stops
                isStartRotate = false;

                // todo... Prize presentation, data maintenance
                Debug.Log("***** congratulations or prize, prize index:" + rewardIndex + ", the turntable Angle is:" 
                          + RotateTableTrans.localEulerAngles.z + "* * * * *"); }}else
        {
            // Turn the dial (back = clockwise, forward = counterclockwise)
            RotateTableTrans.Rotate(Vector3.back * 10); }}// Click the lucky draw button
    void OnClickDrawFun()
    {
        if(! isStartRotate) {// Start the rotation
            isStartRotate = true;
            rotateTiming = 0;

            // Random to the number of areas on the dial
            rewardIndex = Random.Range(0, rotateTableNumber);
            RotateTableNumber;
            float targetRot = rewardIndex * 36; 
            // Set the target location
            targetAngels = Quaternion.Euler(0.0, targetRot);
            
            Debug.Log("----- start the lottery to random areas, the index is :" + rewardIndex + ", the Angle is: + targetRot + "-- -- -- -- --"); }}}Copy the code

Three, slot machine raffle

Effect: Specific reference:Unity to achieve slot machine rolling lottery effect


If there is no understanding of the place, you can comment consultation, or click the link to view the example source code: one, two example source code link without integral students can V letter search “development students stay”, reply to the “Unity lottery” project source code.