Android 绘制和滚动路径性能问题
嗨,我正在做一个无休止的侧滚游戏,那里的地形看起来像一条无限长的隧道。我设法使用以下代码随机生成隧道:Android 绘制和滚动路径性能问题,android,android-canvas,side-scroller,Android,Android Canvas,Side Scroller,嗨,我正在做一个无休止的侧滚游戏,那里的地形看起来像一条无限长的隧道。我设法使用以下代码随机生成隧道: private void createPaths() { if(startingPath) { pathBottom.setLastPoint(0, canvasHeight); pathTop.setLastPoint(0, 0); slopeWidth = 0; slopeHeight = generateR
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);
}
问题是:路径越长,游戏变得越“波涛汹涌”。我认为我应该在一段时间后减少路径中绘制的点,但老实说,我不知道如何做,仍然让地形滚动并生成。如果你能帮助我,我将不胜感激。谢谢。这看起来像是更大逻辑的一小部分。性能问题可能存在于此处未显示的其他一些代码中 一般建议(根据Romain Guy和Chet Haase等人的说法)是在onDraw期间避免对象分配(又名新)。任何“新”都有可能触发GC 我将重复使用相同的Matrix实例,并对其进行更新 此外,正如法登在上面的评论中提到的“固定大小的滑动窗口结构”(类似于循环缓冲区或环形缓冲区),您应该确保您的路径对象是固定大小的
那么您要生成一个无边界增长的数据结构,然后每帧渲染整个内容?如果是这样,你可能想换成固定尺寸的推拉窗结构。你能给我一些建议吗?
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;
}
}