动画两个固定点之间的平移(Libgdx)

时间:2015-12-29 08:47:16

标签: java android animation libgdx

我正在用libgdx进行2D游戏,我想知道屏幕上标准的移动方式(在两个已知点之间进行翻译)是什么。

按下按钮,我试图在两点之间为精灵的对角线移动设置动画。我知道起点和终点的x和y坐标。但是我无法弄清楚决定每次渲染渲染之间纹理应该在哪里的数学。目前我的算法有点像:

textureProperty = new TextureProperty();
firstPtX = textureProperty.currentLocationX
firstPtY = textureProperty.currentLocationY
nextPtX = textureProperty.getNextLocationX()
nextPtX = textureProperty.getNextLocationX()
diffX = nextPtX - firstPtX
diffY = nextPtY - firstPtY
deltaX = diffX/speedFactor // Arbitrary, controlls speed of the translation
deltaX = diffX/speedFactor
renderLocX = textureProperty.renderLocX()
renderLocY = textureProperty.renderLocY()
if(textureProperty.getFirstPoint() != textureProperty.getNextPoint()){
    animating = true
}
if (animating) {
    newLocationX = renderLocX + deltaX
    newLocationY = renderLocY + deltaY
    textureProperty.setRenderPoint(renderLocX, renderLocY)
}
if (textureProperty.getRenderPoint() == textureProperty.getNextPoint()){
   animating = false
   textureProperty.setFirstPoint(textureProperty.getNextPoint())
}
batch.draw(texture, textureProperty.renderLocX(), textureProperty.renderLocY())

但是,我可以预见到这段代码存在的一些问题。 1)由于像素是整数,如果我将该数字除以不均匀的数字,它将会变圆。 2)由于数字1,它将错过目标。

此外,当我测试动画时,物体从点1移动,远射未命中,这表明我的数学可能有问题。

这就是我的意思:

期望的结果: Desired Outcome

实际结果:

Actual Outcome

当然这是一个标准问题。我欢迎任何建议。

3 个答案:

答案 0 :(得分:0)

首先,你需要Vector2 direction,给出2点之间的方向 这个Vector应该被标准化,因此它的长度为1:

Vector2 dir = new Vector2(x2-x1,y2-y1).nor();

然后在render方法中你需要移动对象,这意味着你需要改变它的位置。您有speed(以距离/秒为单位),标准化Vector,给出方向以及自上次更新以来的时间。
所以新的位置可以像这样计算:

position.x += speed * delta * dir.x;
position.y += speed * delta * dir.y;

现在你只需要将位置限制在目标位置,这样你就不会走远:

boolean stop = false;
if (position.x >= target.x) {
    position.x = target.x;
    stop = true;
}
if (position.y >= target.y) {
    position.y = target.y;
    stop = true;
}

现在出现像素问题:
不要使用像素!使用像素将使您的游戏分辨率依赖 请改用Libgdx ViewportCamera。 这可以让你计算出你自己的世界单位中的所有东西(例如meter s),而Libgdx会为你转换它。

答案 1 :(得分:0)

假设您有起始坐标X1,Y1和结束坐标X2,Y2。让我们说你有一些变量p,它保存了传递路径的优点。因此,如果p == 0表示您处于X1,Y1,而p == 100表示您处于X2,Y2和0<p<100,则表示您介于两者之间。在这种情况下,您可以根据p来计算当前坐标:

X = X1 + ((X2 - X1)*p)/100;
Y = Y1 + ((Y2 - Y1)*p)/100;

所以,你不是基于前一个的当前坐标,但你总是根据起点和终点以及传递路径的百分比来计算。

答案 2 :(得分:0)

我没有看到任何大错误,虽然我看到有些像您正在使用 == 和 != 比较两个对象,但我建议您使用 a.equals(b) 和 !a.equals (b) 那样。其次,我发现您的 renderLock 坐标总是在 textureProperty.setRenderPoint(renderLocX, renderLocY) 中设置相同,您正在分配相同的返回值。也许您应该使用 newLocation 坐标。

顺便说一句,感谢您的代码,我正在搜索我从您那里得到的东西<3