如何使用 LibGDX 实现水平滚动?
How do you implement Horizontal-Scrolling with LibGDX?
我想编写一个类似于旧 "Warfare 1917" 浏览器游戏的游戏。我卡在滚动部分了。
我会尝试用 gif 解释我想要的内容:
我搜索并尝试了一整天的所有方法,但我无法找到任何真正的解决方案。我希望你能明白我在做什么。
我认为这应该可以解决问题
public class MovingCamera extends InputAdapter {
OrthographicCamera camera; // The camera to be moved
float pivotX; // The pivot for the movement
public MovingCamera() {
camera = new OrthographicCamera(); // Initialize camera
}
// Create a pivot
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
Vector3 unprojected = camera.unproject(new Vector3(screenX, screenY, 0)); // Convert from pixel to world coordinates
pivotX = unprojected.x; // Save first finger touch on screen (Will serve as a pivot)
return true; // Input has been processed
}
// Move the camera
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
Vector3 unprojected = camera.unproject(new Vector3(screenX, screenY, 0)); // Convert from pixel to world coordinates
camera.position.x += unprojected.x - pivotX; // Change camera position
camera.update(); // Apply changes
return true; // Input has been processed
}
}
并且在您的渲染方法中:
public void render(SpriteBatch spriteBatch) {
spriteBatch.setProjectionMatrix(camera.combined); // Let the Sprite Batch use the camera
spriteBatch.begin();
// [Draw your Textures, TextureRegions, Sprites, etc...]
spriteBatch.end();
}
因为移动相机是一种不好的做法,最好移动一个图层(你的精灵的容器)或者你可以尝试 ScrollPane,WidgetGroup 的实现
p.s。在 v.1.9.11
上测试
我想编写一个类似于旧 "Warfare 1917" 浏览器游戏的游戏。我卡在滚动部分了。
我会尝试用 gif 解释我想要的内容:
我搜索并尝试了一整天的所有方法,但我无法找到任何真正的解决方案。我希望你能明白我在做什么。
我认为这应该可以解决问题
public class MovingCamera extends InputAdapter {
OrthographicCamera camera; // The camera to be moved
float pivotX; // The pivot for the movement
public MovingCamera() {
camera = new OrthographicCamera(); // Initialize camera
}
// Create a pivot
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
Vector3 unprojected = camera.unproject(new Vector3(screenX, screenY, 0)); // Convert from pixel to world coordinates
pivotX = unprojected.x; // Save first finger touch on screen (Will serve as a pivot)
return true; // Input has been processed
}
// Move the camera
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
Vector3 unprojected = camera.unproject(new Vector3(screenX, screenY, 0)); // Convert from pixel to world coordinates
camera.position.x += unprojected.x - pivotX; // Change camera position
camera.update(); // Apply changes
return true; // Input has been processed
}
}
并且在您的渲染方法中:
public void render(SpriteBatch spriteBatch) {
spriteBatch.setProjectionMatrix(camera.combined); // Let the Sprite Batch use the camera
spriteBatch.begin();
// [Draw your Textures, TextureRegions, Sprites, etc...]
spriteBatch.end();
}
因为移动相机是一种不好的做法,最好移动一个图层(你的精灵的容器)或者你可以尝试 ScrollPane,WidgetGroup 的实现
p.s。在 v.1.9.11
上测试