2016-05-03 34 views
1

我試圖讓一個「播放器不能移動,而這個動畫播放」檢查我的移動方法。如何在Unity中使用動畫事件作爲條件?

我有一個3x8的面板網格,我正在使用這個應用程序,隨着播放器從面板移動到面板。我有兩個動畫:當玩家離開面板時播放的MovingOut和當玩家進入面板時播放的「MovingIn」。所以我想要的流程如下:

播放器按下一個移動鍵→移動被禁用→「MovingOut」播放→播放器的transform.position移動到目標位置→「MovingIn」播放→移動被重新啓用。

每個動畫只有4幀。我目前在「MovingOut」的開始處有一個動畫事件,它將int CanMove設置爲0,另一個動畫事件在「MovingIn」的末尾,將CanMove設置爲1.

以下是我的代碼目前爲止的樣子:

public void Move(int CanMove) 
{ 
    //this lets me use panelManager to access methods in the PanelManager script. 
    panelManager = GameObject.FindObjectOfType(typeof(PanelManager)) as PanelManager; 
    animator = GetComponent<Animator>(); 

    if (Input.GetAxisRaw("Horizontal") == 1 && CanMove == 1) //go right 
    { 
     movingToPanel += 1; 

     if (IsValidPanel(movingToPanel)) 
     { 
      //play animation MovingOut 
      animator.Play("MovingOut"); 
      transform.position = panelManager.GetPanelPos(onPanel + 1); 
      onPanel += 1; 
     } 
     else 
     { 
      movingToPanel -= 1; 
     } 
    } 
    //else if(...the rest of the inputs for up/down/left are below. 
} 

我MovingIn在動畫設置,使其發揮在MovingOut動畫結束,這就是爲什麼我不把它在腳本:

我不能爲我的生活f詳細說明如何將CanMove傳遞到方法中,而不必在調用方法時對其進行定義。目前我有Move(1);在我的Update()方法中調用只是爲了檢查移動是否正在運行(除了這個問題我有),它的作用在於我可以將面板移動到面板,但由於CanMove在更新中被定義爲1功能,動畫的事件不會阻止移動。

任何有識之士將不勝感激!

回答

3

你應該稍微改變你的設計。刪除canMove作爲參數傳遞給Move並使其成爲玩家類的字段。然後有一個功能來設置canMove。然後有一個單獨的功能,如果canMove爲真,則允許您移動。事情是這樣的:

private bool canMove = true; 

public void SetMove(int setCanMove) // called with animation events 
{ 
    canMove = setCanMove == 1 ? true : false; 
} 

public void Move() 
{ 
    if (Input.GetAxisRaw("Horizontal") == 1 && canMove == true) //go right 
    { 
     //movement code and animation call... 
    } 
    // Other directions... 
} 

然後你就可以調用setMove功能可按使用動畫事件和停止播放器移動爲他們的持續時間。即在MovingOut動畫開始時呼叫setMove(false),在MovingIn動畫結束時呼叫setMove(true)。這將停止在您的Update循環中設置canMove

+0

Unity動畫事件不允許您調用採用bool參數的函數,當您嘗試添加函數時,它們不會顯示在列表中。根據文檔,它只接受一個「浮動,字符串,int,對象引用或一個AnimationEvent對象」,所以很不幸,這似乎不起作用......這是我把它當作一個int來嘗試設置的原始原因它是一個0和1的整數,而不是一個布爾值。 – SolAureus

+0

啊,我的錯,你仍然可以使用這種方法。只需將'canMove'變量改爲int並使用setter方法將其設置爲1和0. –

+0

@SolAureus我已更新我的答案以顯示如何執行此操作。如果傳遞'1',它會將'canMove'設置爲true,並將其設置爲false以表示任何其他值。 –

0

您可以從動畫師的GetInteger函數中獲取整數值,該函數將返回integer值設置爲當前動畫。

if(this.GetComponent<Animator>().GetInteger(canmove)==0) 
    //move 
else 
    //can't move 
相關問題