目前我使用的方法是检测触摸位置(Gdx.input.getX()& Y())是否在对象纹理所在的区域内。如果是这样,我将对象纹理的setPosition设置为鼠标位置为中心。虽然这项工作但它并不健全。因为如果我的手指移动得比更新更快,只要触摸位置在纹理边界外。它不再更新。
必须有一种更可靠的方式,请指教。基本上,我想触摸纹理并将纹理拖动到我的触摸移动的任何地方。
非常感谢。
我目前的做法是这样的:
public class PlayScreen implements Screen {
int scWidth, scHeight;
int playerWidth, playerHeight;
private SpriteBatch batch; // This is in the render.
Player player;
// Create a constructor
Game game;
public PlayScreen(Game game){
this.game = game;
}
@Override
public void show() {
batch = new SpriteBatch();
scWidth = Gdx.graphics.getWidth();
scHeight = Gdx.graphics.getHeight();
playerWidth = 180;
playerHeight = 240;
player = new Player("mario.png", new Vector2(250, 300),new Vector2(playerWidth, playerHeight)) ;
}
@Override
public void render(float delta) {
Gdx.gl.glClearColor(1,1,1,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
// Only draw if the mouse is hover on the image.
if (Gdx.input.getX() > player.getPosition().x && Gdx.input.getX() < player.getPosition().x + playerWidth){
if (scHeight - Gdx.input.getY() > player.getPosition().y && scHeight - Gdx.input.getY() < player.getPosition().y + playerHeight)
{
player.setPosition(new Vector2(Gdx.input.getX() - playerWidth/2,
scHeight - Gdx.input.getY() - playerHeight/2));
player.draw(batch);
} else{
player.draw(batch);
}
} else{
player.draw(batch);
}
batch.end();
player.update(); // Update the bound
}
}
Player类也是:
package com.jiajunyang.emosonicsgame;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
public class Player extends Image {
Vector2 position, size;
Texture player;
Rectangle bounds;
public Player(String fileName, Vector2 position, Vector2 size){
super(new Texture(Gdx.files.internal(fileName)));
this.position = position;
this.size = size;
bounds = new Rectangle(position.x, position.y, size.x, size.y);
// player = new Texture(Gdx.files.internal(fileName)); }
public void update(){
bounds.set(position.x, position.y, size.x, size.y);
}
public void draw(SpriteBatch batch){
batch.draw(player, position.x, position.y, size.x, size.y);
}
public Vector2 getPosition() {
return position;
}
public void setPosition(Vector2 position) {
this.position = position;
}
public Vector2 getSize() {
return size;
}
public void setSize(Vector2 size) {
this.size = size;
}
public Rectangle getBounds() {
return bounds;
}
public void setBounds(Rectangle bounds) {
this.bounds = bounds;
}
}
答案 0 :(得分:0)
嘉俊,创建一个舞台并让你的玩家扩展图像。然后在show中调用stage.addActor(player)。在render call stage.act()和stage.draw()中。使用Image的构造函数将纹理传递给。最后,在Player的构造函数中,调用它:
addListener(new DragListener() {
@Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
return true;
}
@Override
public void touchDragged(InputEvent event, float x, float y, int pointer) {
moveBy(x - getWidth()/2, y - getHeight()/2);
}
});