gpt4 book ai didi

java - Android/Libgdx 如何解决这个问题?

转载 作者:行者123 更新时间:2023-12-02 03:26:40 24 4
gpt4 key购买 nike

目前我正在编写一款游戏,您可以在其中移动一艘宇宙飞船并尝试避开小行星。当用户触摸宇宙飞船时,它应该移动,并跟随用户手指的移动。宇宙飞船是一个四处移动的 Sprite :

if (Gdx.input.isTouched()) {  

x = Gdx.input.getX() - width / 2;
y = -Gdx.input.getY() + height / 2;

}

我现在遇到的问题是用户可以通过触摸屏幕来传送宇宙飞船。我怎样才能解决这个问题?可以设置触摸区域吗?

最佳答案

计算从船舶到触摸点的单位 vector 方向并将其乘以速度。您需要通过相机取消投影将触摸坐标转换为世界坐标。

private static final float SHIP_MAX_SPEED = 50f; //units per second
private final Vector2 tmpVec2 = new Vector2();
private final Vector3 tmpVec3 = new Vector3();

//...

if (Gdx.input.isTouched()) {
camera.unproject(tmpVec3.set(Gdx.input.getX(), Gdx.input.getY(), 0)); //touch point to world coordinate system.
tmpVec2.set(tmpVec3.x, tmpVec3.y).sub(x, y); //vector from ship to touch point
float maxDistance = SHIP_MAX_SPEED * Gdx.graphics.getDeltaTime(); //max distance ship can move this frame
if (tmpVec2.len() <= maxDistance) {
x = tmpVec3.x;
y = tmpVec3.y;
} else {
tmpVec2.nor().scl(maxDistance); //reduce vector to max distance length
x += tmpVec2.x;
y += tmpVec2.y;
}
}

关于java - Android/Libgdx 如何解决这个问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38768543/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com