2017-03-15 37 views
2

我正在用JavaScript編寫一個大富翁式的遊戲(使用p5.js庫)。我正在嘗試使用rect創建一張卡片的動畫,並在具有固定寬度和高度的2d對象的頂部滑動。這是我的3個功能,顯示我的思維過程:p5.js - 實現流暢的動畫與繪製函數

card_property.js:

function PropertyCard(posX, posY, width, height, property){ 
    this.width = width; 
    this.height = height; 
    this.posX = posX; 
    this.posY = posY; 
    this.property = property; 

    this.display = function(){ 
    rect(this.posX, this.posY, this.width, this.height); 
    }; 
    this.update = function(){ 
     // not sure if I need to use this 
    }; 
} 

這是除非使用條件邏輯,其被連續地調用我draw功能(p5.js功能的一個片段或p5.js noLoop函數被調用)我game.js內:

var propCards = [] 
... 
function draw(){ 
    ... 
    for (var j = propCards.length - 1; j >= 0; j--){ 
    frameRate(10) 
    console.log(propCards) 
    while (propCards[j].posX > 90){ 
     propCards[j].display(); 
     propCards[j].posX -= 5; 
    } 
    } 
} 

最後,這個函數c飯店酒店那我試圖動畫房產證的一個實例:

function addCard(property){ 
    propCard = new PropertyCard(680, 760, 20, 40, property); 
    propCards.push(propCard); 
} 

當我試圖創建動畫,我最終渲染,顯示卡跨降x值相互重疊的靜態圖像。我怎樣才能讓卡片滑過我創建的矩形並停在某個點上?下圖顯示了我所看到的:

Card animation attempt

+0

重繪平局每幀的背景是什麼? –

+0

請發表[MCVE],而不是隨機的片段,從整個項目。 –

回答

0

「繪製」顯示你計劃到它在函數結束。

所以你在做什麼是在同一幀中繪製多個矩形。

你必須做的是使一些計算放在哪裏矩形繪製的每個迭代。

如:

animationframe = 0 

// draw function 
// when you want the animation do: animationframe = distancetogo/5 
if (animationframe>0){ 
    for (var j = propCards.length - 1; j >= 0; j--){ 
    propCards[j].posX -= 5; 
    propCards[j].display(); 
    } 
}