嗨,我正在做无尽的sidescroller游戏,其中地形看起来像一条无限的隧道。我设法使用以下代码随机生成隧道:
private void createPaths() {
if(startingPath) {
pathBottom.setLastPoint(0, canvasHeight);
pathTop.setLastPoint(0, 0);
slopeWidth = 0;
slopeHeight = generateRandomNumber(canvasHeight / 4, canvasHeight / 2);
lastX = 0;
lastY = canvasHeight - slopeHeight;
newX = lastX;
newY = lastY;
startingPath = false;
} else {
lastX = canvasWidth;
lastY = newY;
newX = lastX;
newY = canvasHeight - slopeHeight;
}
pathBottom.lineTo(lastX, lastY);
pathTop.lineTo(lastX, lastY - OFFSET);
do {
lastX = newX;
lastY = newY;
slopeWidth = generateRandomNumber(canvasWidth / 8, canvasWidth / 2);
newX += slopeWidth;
if(i % 2 == 0) {
slopeHeight = generateRandomNumber(canvasHeight / 12, canvasHeight / 6);
newY = canvasHeight - slopeHeight;
} else {
slopeHeight = generateRandomNumber(canvasHeight / 4, canvasHeight / 2);
newY = canvasHeight - slopeHeight;
}
pathBottom.cubicTo(
interpolateLinear(lastX, newX, 0.333f),
lastY,
interpolateLinear(lastX, newX, 0.666f),
newY,
newX,
newY);
pathTop.cubicTo(
interpolateLinear(lastX, newX, 0.333f),
lastY - OFFSET,
interpolateLinear(lastX, newX, 0.666f),
newY - OFFSET,
newX,
newY - OFFSET);
i++;
} while (newX < canvasWidth * 2);
pathBottom.lineTo(newX, canvasHeight);
pathTop.lineTo(newX, 0);
}
并使用以下方式滚动
public void updateTerrain() {
moveX -= speed;
int pos = newX - canvasWidth + moveX;
if(pos > 0) {
Matrix matrix = new Matrix();
matrix.setTranslate(-speed, 0);
pathBottom.transform(matrix);
pathTop.transform(matrix);
} else {
createPaths();
moveX = 0;
}
}
问题是:路径越长,游戏变得越来越不稳定&#34;。我想我应该在一段时间后减少在路径中绘制的点数,但说实话我不知道该怎么做,仍然让地形滚动并生成。如果你能帮助我,我将不胜感激。感谢。
答案 0 :(得分:1)
这看起来像一块较大的逻辑。性能问题可能在于此处未显示的其他一些代码。
一般建议(根据像Romain Guy和Chet Haase这样的人)是在onDraw期间避免对象分配(也就是新的)。任何&#34;新&#34;有可能触发GC。
我会重复使用相同的Matrix实例并更新它。
另外,正如fadden提到的那样#34;固定尺寸的滑动窗结构&#34; (类似于循环缓冲区或环形缓冲区)上面的注释,您应该确保您的Path对象是固定大小。