我正在使用此代码,但有些并不完美。它正在工作,但不顺利。首先它进入touchX,然后进入touchY。但我同时想要这个。我尝试了不同的代码,但是没有用。我该如何解决?有什么问题?
package com.anil.game1;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector3;
public class Game1 extends ApplicationAdapter {
private SpriteBatch batch;
private OrthographicCamera camera;
private Texture player1Texture;
private Rectangle player1Rectangle;
private Vector3 touchPos;
@Override
public void create () {
batch = new SpriteBatch();
camera = new OrthographicCamera(480, 800);
player1Texture = new Texture("Player1.png");
player1Rectangle = new Rectangle();
player1Rectangle.set(240, 0, 64, 64);
touchPos = new Vector3();
}
@Override
public void render () {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined);
batch.begin();
if (Gdx.input.isTouched()) {
touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(touchPos);
//player1Rectangle.setPosition(new Vector2(touchPos.x, touchPos.y));
}
if (touchPos.x > player1Rectangle.x)
player1Rectangle.x += 5;
else
player1Rectangle.x -= 5;
if (touchPos.y > player1Rectangle.y)
player1Rectangle.y += 5;
else
player1Rectangle.y -= 5;
batch.draw(player1Texture, player1Rectangle.x - 32, player1Rectangle.y - 32);
batch.end();
}
@Override
public void dispose () {
batch.dispose();
player1Texture.dispose();
}
}
最佳答案
在这个部分:
if (touchPos.x > player1Rectangle.x)
player1Rectangle.x += 5;
else
player1Rectangle.x -= 5;
if (touchPos.y > player1Rectangle.y)
player1Rectangle.y += 5;
else
player1Rectangle.y -= 5;
您将强制矩形始终沿X和Y方向移动一定的量。永远都不要坐着或放慢脚步。另外,您可能不想分开处理X和Y,因为这样一来,其速度在基本方向上会变慢,在对角线方向上会变快,这看起来很奇怪。最后,您需要在速度和时间上保持稳定的运动速度。
因此,首先,为对象定义速度。另外,您将需要使用Vector2进行计算。
private static final float SPEED = 300f; //world units per second
private final Vector2 tmp = new Vector2();
现在,在计算了触摸位置之后,您想要确定向哪个方向移动以及沿该方向移动多远。因此,在您的
isTouched
块之后://how far the player can move this frame (distance = speed * time):
float maxDistance = SPEED * Gdx.graphics.getDeltaTime();
//a vector from the player to the touch point:
tmp.set(touchPos.x, touchPos.y).sub(player1Rectangle.x, player1Rectangle.y);
if (tmp.len() <= maxDistance) {// close enough to just set the player at the target
player1Rectangle.x = touchPos.x;
player1Rectangle.y = touchPos.y;
} else { // need to move along the vector toward the target
tmp.nor().scl(maxDistance); //reduce vector length to the distance traveled this frame
player1Rectangle.x += tmp.x; //move rectangle by the vector length
player1Rectangle.y += tmp.y;
}