我正在 libgdx 中制作 2d 游戏,我想知道屏幕上移动(在两个已知点之间转换)的标准方式是什么。
按下按钮时,我尝试为 Sprite 在两点之间的对角线移动设置动画。我知道起点和终点的 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 移动的对象会因远距离镜头而错过,这表明我的数学可能有问题。
这是我用图形表示的意思:
实际结果:
这当然是一个标准问题。我欢迎任何建议。
最佳答案
假设您有起始坐标 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;
因此,当前坐标不是基于前一个坐标,而是始终根据起点和终点以及通过路径的百分比进行计算。
关于java - 动画两个固定点之间的平移 (Libgdx),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34507560/