2017-03-15 66 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(); 
    } 
}