每段動畫都是從0~1播放的一個百分比,通過控制播放的時間,來控制開始播放的百分比,按下p鍵之後,從設定開始的百分比到結束的百分比,
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
/// <summary>
/// dcc
/// 擷取使用該腳本物體的動畫元件,并通過修改時間來控制動畫開始和結束的百分比位置
///
///
/// </summary>
public class ControlAnimation : MonoBehaviour {
//擷取動畫元件
private Animation m_ani;
//卡通片段的名字
public string animationCilpName = "Rotate_ani";
//開始的時間百分比
public float startTime = 0.3f;
//停止的時間百分比
public float stopTime = 0.8f;
// Use this for initialization
void Awake()
{
m_ani = GetComponent<Animation>();
}
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.P))
{
//播放
m_ani.Play();
//通過改變動畫的狀态(AnimationState)控制動畫的運動
// public AnimationState this[string name] { get; }
//動畫的整個過程的時間(normalizedTime)是0-》1
m_ani[animationCilpName].normalizedTime = startTime;
}
if (m_ani[animationCilpName].normalizedTime > stopTime)
{
//動畫停止
//或者可以用
//m_ani.Stop();
m_ani[animationCilpName].normalizedSpeed = 0;
}
}
void PlayAnimation(bool isNormal)
{
if (isNormal)
{
//正常播放
//GetComponent<Animation>().Play("對應片段的名字");
GetComponent<Animation>().Play();
}
else
{
///倒播速度為-1,時間為正常的時間,,然後播放
GetComponent<Animation>()[GetComponent<Animation>().clip.name].speed = -1;
GetComponent<Animation>()[GetComponent<Animation>().clip.name].time = 1;
GetComponent<Animation>().Play();
}
}
}
unity3d版本:2017.2.0f3
案例百度雲連結:https://pan.baidu.com/s/1PDFl_8ZX-mwXOhmjFW1wMw
提取碼:klal