2015-12-29 56 views
1

我正在libgdx中制作一个2D游戏,我想知道在屏幕上移动(在两个已知点之间转换)的标准方式是什么。两个固定点之间的动画翻译(Libgdx)

在一个按钮上按下,我试图为两个点之间的精灵对角线运动设置动画。我知道开始点和结束点的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,它会错过目标。

另外,当我测试动画时,从point1移动的对象,错过了一个长镜头,这暗示着我的数学可能是错误的。

这里是我的意思图形:

期望的结果: Desired Outcome

实际结果:

Actual Outcome

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

回答

0

首先你需要一个Vector2 direction,给出两点之间的方向。
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会为你转换它。

0

比方说,你有起始坐标X1,Y1和结束坐标X2,Y2。假设你有一些变量p,它保存了传递路径的优点。所以如果p == 0这意味着你在X1,Y1,如果p == 100这意味着你在X2,Y2,并且如果0<p<100你在两者之间。在这种情况下,你可以计算出当前坐标视象电话号码:

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

那么,你是不是立足于前一个电流COORDS,但你总是取决于起点和终点,并通过路径的百分比计算。