1. 程式人生 > >Unity 手指滑動控制視訊播放進度。

Unity 手指滑動控制視訊播放進度。

1:我這邊在一開始做的時候用的是unity自帶videoPlayer來做視訊的控制器的,後來測試發現滑動的並不是那麼平滑,後來改為了AVPro這個外掛,就比較平滑。

2:下面是程式碼


using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Video;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using RenderHeads.Media.AVProVideo;
using System;

public class Swape_Help : MonoBehaviour
{
    private Vector3 startFingerPos;
    private Vector3 nowFingerPos;
    private float xMoveDistance;
    private float yMoveDistance;
    private int backValue = 0;
    public MediaPlayer video;
    Text Text;

    void Update()
    {
        JudgeFinger();
    }


    float timer;//計時器
    Vector3 beforePos;//前0.1秒的手指位置;

    public void JudgeFinger()
    {

        if (Input.touchCount > 0)
        {
            if (Input.GetTouch(0).phase == TouchPhase.Stationary) return;

            if (Input.GetTouch(0).phase == TouchPhase.Began)
            {
                startFingerPos = Input.GetTouch(0).position;

            }
            timer += Time.deltaTime;
            if (timer > 0.1f)
            {
                beforePos = Input.GetTouch(0).position;
                timer = 0;

            }

            nowFingerPos = Input.GetTouch(0).position;


            xMoveDistance = Mathf.Abs(nowFingerPos.x - startFingerPos.x);

            yMoveDistance = Mathf.Abs(nowFingerPos.y - startFingerPos.y);

            if (xMoveDistance > 0)
            {
                //向螢幕右滑動
                if (nowFingerPos.x - beforePos.x > 0)//當前位置減去前0.1位置來判斷方向
                {
                    backValue = -1;

                }
                else
                {

                    //向螢幕左滑動
                    backValue = 1;

                }

            }
            if (Input.GetTouch(0).phase == TouchPhase.Moved)
            {
                if (video.Control.IsPlaying())
                {
                    video.Pause();
                }
                SetVideo_ChangeValue(backValue);
            }
            if (Input.GetTouch(0).phase == TouchPhase.Ended)
            {
                video.Play();
            }
        }


    }

    void SetVideo_ChangeValue(int isRightOrLeft)
    {

        /* TODO測試*/   //向左滑動
        if (isRightOrLeft == 1)
        {
            float m = video.Control.GetCurrentTimeMs() - (xMoveDistance * 0.5f / Screen.width) * video.Info.GetDurationMs();
            m = Mathf.Clamp(m, 0, video.Info.GetDurationMs());

            video.Control.Seek(m);

            //Text.text = video.frame.ToString() + "滑動後幀數"+x.ToString()+"ppp";
        }
        if (isRightOrLeft == -1)
        {
            float m = video.Control.GetCurrentTimeMs() + (xMoveDistance * 0.5f / Screen.width) * video.Info.GetDurationMs();
            m = Mathf.Clamp(m, 0, video.Info.GetDurationMs());

            video.Control.Seek(m);
        }

    }

    public void LoadScnes(string Name)
    {
        SceneManager.LoadScene(Name);
       // Debug.Log("....");

    }

}