2016-09-30 29 views
0

我有一個精靈渲染器,它告訴我的遊戲引擎如何渲染精靈。此類中的更新方法每秒調用大約120次。以這樣的速度穿越精靈表格太快了。在畫布上播放精靈表比幀率慢

在我的精靈類中,我有一個名爲duration的屬性,它告訴渲染器精靈應該玩多少秒。一旦它達到最後一幀,它應該重新開始。

我不完全確定如何計算這個與update每秒運行120次,精靈表應該持續x秒直到重新開始。

class SpriteRenderer extends Component { 

    // The current frame 
    public frame: number = 0; 
    // The sprite reference 
    public sprite: Sprite = null; 

    update() { 

     // Number of frames in the sprite sheet 
     let frames = this.sprite.frames; 
     if (frames > 0) { 
      // The time in seconds the sprite sheet should play 
      let duration = this.sprite.duration; 

      if (/* What should go here? */) { 
       this.frame++; 
       if (this.frame > frames - 1) { 
        this.frame = 0; 
       } 
      } 
     } 

    } 

} 

回答

1

您可以實現一個控制幀時間的時間變量。 這個變量是一個浮點數,一旦它變得足夠大,你可以做下一幀並重置變量。

我從來沒有做過任何類型的腳本,但這可能工作。它至少會讓你知道我在說什麼。

如果更新每秒運行120次,這意味着它每60/120秒運行0.5次。

現在我們可以將currentTime增加0.5,並檢查currentTime>sprite.duration * 60我認爲。 :)

Exampe:

class SpriteRenderer extends Component { 

    // The current frame 
    public frame: number = 0; 
    // The sprite reference 
    public sprite: Sprite = null; 
    public currentTime: number = 0.0; //This is the current time. 
    public updateTime: number = this.sprite.duration*60; //This is how long the update time is. 
    update() { 
     this.currentTime += 0.5; //Add to the current time. 
     // Number of frames in the sprite sheet 
     let frames = this.sprite.frames; 
     if (frames > 0) { 
      // The time in seconds the sprite sheet should play 
      let duration = this.sprite.duration; 

      if (this.currentTime > this.sprite.duration*60) { //Check if the current time is more than the wait time. 
       this.currentTime = 0.0; //Reset the wait time. 
       this.frame++; 
       if (this.frame > frames - 1) { 
        this.frame = 0; 
       } 
      } 
     } 

    } 

} 
+0

八九不離十,'this.currentTime + = 0.01;'在我的情況應該是'this.currentTime + = Time.deltaTime;''this.udateTime'將是' duration'。將我的持續時間設置爲「1」,它每秒播放1幀,這比它更接近。 –

+0

是的,我正在更新我的答案,以計算每秒應該添加的時間以及需要多長時間。 –

+0

更緊密!我的if現在看起來像這樣:if(this.currentTime> duration * Time.deltaTime)'my'deltaTime'約爲'0.008'。它仍然有點快。如果我將持續時間設置爲5,則大約需要1秒... –