我对LibGdx很陌生,我还在学习。我正在开发一个小游戏项目来学习这个漂亮的框架。 相同的图片如下:
是代码:
public class Game
extends ApplicationAdapter {
Vector2 vec2Position = new Vector2();
Vector2 velocity = new Vector2();
Vector2 vec2Movement = new Vector2();
Vector2 vec2Touch = new Vector2();
Vector2 dir = new Vector2();
Vector3 vec3Temp = new Vector3();
float speed = 100;
OrthographicCamera camera;
SpriteBatch batch;
Texture texture;
Sprite sprite;
@Override
public void create() {
camera = new OrthographicCamera();
camera.setToOrtho(false);
batch = new SpriteBatch();
texture = new Texture(Gdx.files.internal("32x32.png"));
sprite = new Sprite(texture);
Gdx.input.setInputProcessor(new InputAdapter() {
@Override
public boolean touchDown(int screenX,
int screenY,
int pointer,
int button) {
camera.unproject(vec3Temp.set(screenX,
screenY,
0));
vec2Touch.set(vec3Temp.x,
vec3Temp.y);
return true;
}
});
}
@Override
public void render() {
Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT);
if (Gdx.input.justTouched()){
update(Gdx.graphics.getDeltaTime());
}
batch.begin();
sprite.draw(batch);
batch.end();
}
@Override
public void dispose() {
texture.dispose();
batch.dispose();
}
public void update(float deltaTime) {
System.out.println(">>>>> check delta:" + deltaTime);
vec2Position.set(sprite.getX(),
sprite.getY());
dir.set(vec2Touch)
.sub(vec2Position)
.nor();
velocity.set(dir)
.scl(speed);
vec2Movement.set(velocity)
.scl(deltaTime);
if (vec2Position.dst2(vec2Touch) > vec2Movement.len2()) {
vec2Position.add(vec2Movement);
} else {
vec2Position.set(vec2Touch);
}
//dung angle.
float x2 = sprite.getX(); //Enemy's new X
float y2 = sprite.getY(); //Enemy's new Y
float angle; // We use a triangle to calculate the new trajectory
angle = (float) Math
.atan2(vec2Touch.y - y2,
vec2Touch.x - x2);
angle = -90;
System.out.println(">>>>> angle:"+angle);
x2 += (float) Math.cos(angle) * 125
* Gdx.graphics.getDeltaTime();
y2 += (float) Math.sin(angle) * 125
* Gdx.graphics.getDeltaTime();
// sprite.setX(vec2Position.x);
// sprite.setY(vec2Position.y);
// sprite.setPosition(vec2Position.x,vec2Position.y);
sprite.setPosition(x2,
y2);
}
}