This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
For some reason, when I try to pass through Gdx.graphics.getDeltaTime() into my player class, the float delta time is null giving a null pointer exception. I already tried to check if the getDeltaTime method worked, and its counting, but when i try to pass through the function it doesn't work.
My Main Code
public class MyGdxGame extends ApplicationAdapter implements InputProcessor {
SpriteBatch batch;
private Player1 player1;
private TiledMap iceLevel;
private OrthogonalTiledMapRenderer renderer;
private OrthographicCamera camera;
float elaspedTime;
#Override
public void create() {
batch = new SpriteBatch();
Gdx.input.setInputProcessor(this);
TmxMapLoader loader = new TmxMapLoader();
iceLevel = loader.load("IceLevel.tmx");
renderer = new OrthogonalTiledMapRenderer(iceLevel);
camera = new OrthographicCamera();
camera.setToOrtho(false);
player1 = new Player1(new Sprite(new Texture("player1Right.png")), (TiledMapTileLayer) iceLevel.getLayers().get("Land"));
player1.setPosition(player1.getCollisionLayer().getTileWidth(), 6 * player1.getCollisionLayer().getTileHeight());
}
#Override
public void render() {
player1.update(Gdx.graphics.getDeltaTime());
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
camera.update();
renderer.setView(camera);
renderer.render();
renderer.getBatch().begin();
player1.draw(renderer.getBatch());
renderer.getBatch().end();
batch.end();
}
#Override
public void dispose() {
batch.dispose();
iceLevel.dispose();
renderer.dispose();
player1.getTexture().dispose();
}
A part of my player class
public class Player1 extends Sprite implements InputProcessor {
private Vector2 velocity;
private float speed = 60 * 2;
private float gravity = 60 * 1.8f;
private TiledMapTileLayer collisionLayer;
public Player1(Sprite sprite, TiledMapTileLayer collisionLayer) {
super(sprite);
this.collisionLayer = collisionLayer;
}
public void draw(SpriteBatch spriteBatch) {
update(Gdx.graphics.getDeltaTime());
super.draw(spriteBatch);
}
public void update(float delta) {
//gravity
velocity.y -= gravity * delta;
//set limit
if (velocity.y > speed) {
velocity.y = speed;
} else if (velocity.y < -speed) {
velocity.y = -speed;
}
// save old position
float oldX = getX();
float oldY = getY();
boolean collisionX = false;
boolean collisionY = false;
// move on x
setX(getX() + velocity.x * delta);
if (velocity.x < 0) { //going left
collisionX = collidesLeft();
} else if (velocity.x > 0) { //going right
collisionX = collidesRight();
}
// react to x collision
if (collisionX) {
setX(oldX);
velocity.x = 0;
}
// move on y
setY(getY() + velocity.y * delta * 5f);
if (velocity.y < 0) { // going down
collisionY = collidesBottom();
} else if (velocity.y > 0) { // going up
collisionY = collidesTop();
}
if (collisionY) {
setY(oldY);
velocity.y = 0;
}
}
Just to rule out delta time refactor you code like this:-
#Override
public void render() {
float delta = Gdx.graphics.getDeltaTime();
// Log or print this
if(delta > 0){
player1.update(Gdx.graphics.getDeltaTime());
Gdx.gl.glClearColor(1, 0, 0, 1);
.......
.......
}
Sounds like your player class update() method is the issue, but not the float delta. Looks like it is velocity. It is null.
private Vector2 velocity;
...
//gravity
velocity.y -= gravity * delta;
You are trying to set the y public float value of velocity (Vector2) but you don't have a velocity object instantiated.
Try
private Vector2 velocity = new Vector2();
Related
I'm trying to develop a small tower defense game with libGDX and am getting the following exception:
Exception in thread "LWJGL Application" java.lang.NullPointerException
at com.badlogic.gdx.graphics.g2d.SpriteBatch.switchTexture(SpriteBatch.java:1067)
at com.badlogic.gdx.graphics.g2d.SpriteBatch.draw(SpriteBatch.java:558)
at com.badlogic.gdx.graphics.g2d.Sprite.draw(Sprite.java:517)
at levels.AISprite.draw(AISprite.java:33)
at levels.levelGenerator.render(levelGenerator.java:44)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:232)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:127)
I understand that there is something that is not initialized, but what? Would be really happy if you could help me and explain whats the issue.
I would also be glad if you could improve my code! Thanks in advance
Code (only where the magic happens):
levelGenerator Class
public class levelGenerator extends ApplicationAdapter {
private final String level;
SpriteBatch batch;
Texture img;
Scorpion scorpion;
private Array<AISprite> aiSprites;
public levelGenerator(String level){
this.level = level;
}
#Override
public void create () {
Gdx.graphics.setTitle("Tower Defense Game");
scorpion = new Scorpion();
img = new Texture(level);
scorpion.createImage();
aiSprites = new Array<AISprite>();
aiSprites.add(new AISprite(scorpion, LevelOne.levelOnePath()));
}
public void render () {
batch = new SpriteBatch();
batch.begin();
//just the level image background
batch.draw(img, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
scorpion.renderImage();
for(AISprite aiSprite: aiSprites){
aiSprite.draw(batch);
}
for(AISprite aiSprite: aiSprites){
Vector2 previous = aiSprite.getPath().first();
for(Vector2 waypoint: aiSprite.getPath()){
previous = waypoint;
}
}
}
#Override
public void dispose () {
batch.dispose();
img.dispose();
scorpion.disposeImage();
}
}
Entity Class:
public class Entity extends Sprite {
String atlasPath;
private Animation<TextureRegion> animation;
private TextureAtlas entityAtlas;
private float timePassed = 0;
SpriteBatch batch;
public Entity(String atlasPath){
this.atlasPath = atlasPath;
}
public void createImage(){
// path for scorpion atlas file: "assetsPack/scorpions/scorpionRunning/scorpionPack.atlas"
entityAtlas = new TextureAtlas(Gdx.files.internal(atlasPath));
animation = new Animation<TextureRegion>(1/40f, entityAtlas.getRegions());
}
public void renderImage(){
batch = new SpriteBatch();
batch.begin();
timePassed += Gdx.graphics.getDeltaTime();
batch.draw(animation.getKeyFrame(timePassed, true), 0, 0);
batch.end();
}
public void disposeImage(){
entityAtlas.dispose();
}
}
Scorpion (Entity) Class:
public class Scorpion extends Entity {
public Scorpion(){
super("assetsPack/scorpions/scorpionRunning/scorpionPack.atlas");
}
Next class is the one for the pathfinding of the entities
public class AISprite extends Sprite {
private Vector2 velocity = new Vector2();
private float speed = 100, tolerance = 3;
public Array<Vector2> getPath() {
return path;
}
private Array<Vector2> path;
private int waypoint = 0;
public AISprite(Entity entity, Array<Vector2> path){
super(entity);
this.path = path;
}
public void draw(SpriteBatch spriteBatch){
update(Gdx.graphics.getDeltaTime());
super.draw(spriteBatch);
}
public void update(float delta){
float angle = (float) Math.atan2(path.get(waypoint).y - getY(), path.get(waypoint).x - getX());
velocity.set((float) Math.cos(angle) * speed, (float) Math.sin(angle) * speed);
setPosition(getX() + velocity.x * delta, getY() + velocity.y * delta);
if(isWaypointReached()){
setPosition(path.get(waypoint).x, path.get(waypoint).y);
if(waypoint + 1 >= path.size){
waypoint = 0;
}
else{
waypoint++;
}
}
}
public boolean isWaypointReached(){
return path.get(waypoint).x - getX() <= speed / tolerance * Gdx.graphics.getDeltaTime() && path.get(waypoint).y - getY() <= speed / tolerance * Gdx.graphics.getDeltaTime() ;
}
}
use a debugger, set a breakpoint on levels.levelGenerator.render(levelGenerator.java:44), and check what causes the erro .... if you never used a debugger, I strongly(!!!) recommend you learn how to use one before you continue with libgdx
Make sure that all your Gdx calls are made after the create() method is called. All gdx objects are null before that point, so calls such as Gdx.graphics.(...) or Gdx.app.(...) or Gdx.audio.(...) etc. will throw a NPE
I have a animation which i want to flip to the left if key LEFT is pressed, but it doesnt stay flipped. It only flips like 1 frame then turns back again.
Here is my GameScreen where i draw everything:
public class GameScreen extends ScreenManager{
//For the view of the game and the rendering
private SpriteBatch batch;
private OrthographicCamera cam;
//DEBUG
private Box2DDebugRenderer b2dr;
//World, Player and so on
private GameWorld world;
private Player player;
private Ground ground;
//player animations
private TextureRegion currFrame;
public static float w, h;
public GameScreen(Game game) {
super(game);
//vars
w = Gdx.graphics.getWidth();
h = Gdx.graphics.getHeight();
//view and rendering
batch = new SpriteBatch();
cam = new OrthographicCamera();
cam.setToOrtho(false, w/2, h/2);
//debug
b2dr = new Box2DDebugRenderer();
//world, bodies ...
world = new GameWorld();
player = new Player(world);
ground = new Ground(world);
}
#Override
public void pause() {
}
#Override
public void show() {
}
#Override
public void render(float delta) {
//clearing the screen
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
//updating
update(Gdx.graphics.getDeltaTime());
player.stateTime += Gdx.graphics.getDeltaTime();
//render
batch.setProjectionMatrix(cam.combined);
currFrame = Player.anim.getKeyFrame(Player.stateTime, true);
batch.begin();
batch.draw(currFrame, Player.body.getPosition().x * PPM - 64, Player.getBody().getPosition().y * PPM- 72);
batch.end();
//debug
b2dr.render(GameWorld.getWorld(), cam.combined.scl(PPM));
}
#Override
public void resize(int width, int height) {
}
#Override
public void hide() {
}
#Override
public void dispose() {
}
#Override
public void onKlick(float delta) {
}
public void update(float delta){
world.update(delta);
updateCam(delta);
Player.keyInput(delta);
System.out.println("X-POS" + Player.getBody().getPosition().x);
System.out.println("Y-POS" + Player.getBody().getPosition().y);
}
public void updateCam(float delta){
Vector3 pos = cam.position;
pos.x = Player.getBody().getPosition().x * PPM;
pos.y = Player.getBody().getPosition().y * PPM;
cam.position.set(pos);
cam.update();
}
}
and this is the Player class where the animation is:
public class Player {
public static Body body;
public static BodyDef def;
private FixtureDef fd;
//textures
public static Texture texture;
public static Sprite sprite;
public static TextureRegion[][] region;
public static TextureRegion[] idle;
public static Animation<TextureRegion> anim;
public static float stateTime;
//set form
private PolygonShape shape;
private GameScreen gs;
public Player(GameWorld world){
texture = new Texture(Gdx.files.internal("player/char_animation_standing.png"));
region = TextureRegion.split(texture, texture.getWidth() / 3, texture.getHeight() / 2);
idle = new TextureRegion[6];
int index = 0;
for(int i = 0; i < 2; i++){
for(int j = 0; j < 3; j++){
sprite = new Sprite(region[i][j]);
idle[index++] = sprite;
}
}
anim = new Animation<TextureRegion>(1 / 8f, idle);
stateTime = 0f;
def = new BodyDef();
def.fixedRotation = true;
def.position.set(gs.w / 4, gs.h / 4);
def.type = BodyType.DynamicBody;
body = world.getWorld().createBody(def);
shape = new PolygonShape();
shape.setAsBox(32 / 2 / PPM, 64/ 2 / PPM);
fd = new FixtureDef();
fd.shape = shape;
fd.density = 30;
body.createFixture(fd);
shape.dispose();
}
public static Body getBody() {
return body;
}
public static BodyDef getDef() {
return def;
}
public static Texture getTexture() {
return texture;
}
public static void keyInput(float delta){
int horizonForce = 0;
if(Gdx.input.isKeyJustPressed(Input.Keys.UP)){
body.applyLinearImpulse(0, 300f, body.getWorldCenter().x, body.getWorldCenter().y, true);
//body.applyForceToCenter(0, 1200f, true);
System.out.println("PRESSED");
}
if(Gdx.input.isKeyPressed(Input.Keys.LEFT)){
horizonForce -= 1;
sprite.flip(!sprite.isFlipX(), sprite.isFlipY());
}
if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)){
horizonForce += 1;
}
body.setLinearVelocity(horizonForce * 20, body.getLinearVelocity().y);
}
}
thank you in advance and any answer is appreciated :D
Your sprite variable contain only one frame at the time of pressing left key. So, it flip that current sprite of your animation frame.
To solve the Problem you have to flip all the animation frame on pressing the left key.
You're only flipping last frame of Animation by sprite reference, You need to flip all frames of your Animation anim. You can flip in this way :
if(keycode== Input.Keys.RIGHT) {
for (TextureRegion textureRegion:anim.getKeyFrames())
if(!textureRegion.isFlipX()) textureRegion.flip(true,false);
}
else if(keycode==Input.Keys.LEFT) {
for (TextureRegion textureRegion:anim.getKeyFrames())
if(textureRegion.isFlipX()) textureRegion.flip(true,false);
}
I'm currently programming a game where you have to avoid asteroids. I had to deal with some messed up coordinates and I had to guess the coordinates for sprites. I now have arbitrary units that describe my world. Unfortunately, my game screen does not work fully. When I want to render my asteroids the game screen shows a black screen.
public class GameScreen extends Screen {
private OrthographicCamera cam;
private Spaceship spaceship;
private Asteroids asteroids;
private Background bg;
#Override
public void create() {
// TODO Auto-generated method stub
bg = new Background();
spaceship = new Spaceship();
asteroids = new Asteroids();
float aspectratio = 16/10;
cam = new OrthographicCamera(100, 100 * aspectratio);
cam.position.set(cam.viewportWidth / 2f, cam.viewportHeight / 2f, 0);
cam.update();
}
#Override
public void render(SpriteBatch batch) {
// TODO Auto-generated method stub
cam.update();
batch.setProjectionMatrix(cam.combined);
batch.begin();
bg.render(batch);
spaceship.render(batch);
batch.end();
}
The shown code above works just fine and shows me this:
When I add the render method for the asteroids in the GameScreen class the GameScreen is just black:
#Override
public void render(SpriteBatch batch) {
// TODO Auto-generated method stub
cam.update();
batch.setProjectionMatrix(cam.combined);
batch.begin();
bg.render(batch);
spaceship.render(batch);
batch.end();
}
Asteroid Class:
public class Asteroid {
private Vector2 p;
private Vector2 v;
private float mass;
private float radius;
public final float maxV = 200;
public final float minV = 50;
public final float rMin = 10;
public final float rMax = 30;
public final float minX = MyGdxGame.WIDTH;
public final float minY = MyGdxGame.HEIGHT;;
float alpha = MathUtils.random(0, 360);
public Asteroid(float maxX, float maxY, List<Asteroid> asteroids) {
do {
radius = MathUtils.random(rMin, rMax);
masse = radius * radius * radius;
float alpha = MathUtils.random(0, 360);
p = new Vector2(MathUtils.random(minX, maxX), MathUtils.random(minY,
maxY));
float vBetrag = MathUtils.random(minV, maxV);
v = new Vector2(vBetrag * MathUtils.cosDeg(alpha),
vBetrag * MathUtils.cosDeg(alpha));
} while (ueberlappMit(asteroids));
}
private boolean ueberlappMit(List<Asteroid> asteroids) {
for(Asteroid a: asteroids){
if(abstand(a) < radius + a.radius + 10){ //!
return true;
}
}
return false;
}
public void update(float deltaT, float xMin, float xMax, float yMin, float yMax) {
p.x += v.x * deltaT;
p.y += v.y * deltaT;
while(p.x > xMax)
{
p.x -= (xMax - xMin);
}
while(p.x < xMin)
{
p.x += (xMax - xMin);
}
while(p.y > yMax)
{
p.y -= (yMax - yMin);
}
while(p.y < yMin)
{
p.y += (yMax - yMin);
}
}
public float abstand(Asteroid a2) {
return p.dst(a2.p);
}
Asteroids Class:
public class Asteroids extends Entity {
private final int numberofAsteroids = 150;
private float xMin, xMax, yMin, yMax;
private List<Asteroid> asteroids = new ArrayList<Asteroid>();
private final int cyclicBoundaryConditionsMultiple = 2;
public Asteroids() {
xMin = MyGdxGame.WIDTH * (-cyclicBoundaryConditionsMultiple);
xMax = MyGdxGame.WIDTH * (cyclicBoundaryConditionsMultiple);
yMin = MyGdxGame.HEIGHT * (-cyclicBoundaryConditionsMultiple);
yMax = MyGdxGame.HEIGHT * (cyclicBoundaryConditionsMultiple);
for (int i = 0; i < anzahl; i++) {
Asteroid a = new Asteroid( xMax, yMax, asteroids);
asteroids.add(a);
}
}
#Override
public void update() {
for (Asteroid a : asteroids) {
a.update(Gdx.graphics.getDeltaTime(), xMin, xMax, yMin, yMax);
}
for (int i = 0; i < numberofAsteroids; i++) {
Asteroid a1 = asteroids.get(i);
for (int j = i + 1; j < anzahl; j++) {
Asteroid a2 = asteroids.get(j);
float abstand = a1.abstand(a2);
if (abstand < a1.getRadius() + a2.getRadius()) {
calculateCollision(a1, a2);
}
}
}
}
}
#Override
public void render(ShapeRenderer renderer) {
for (Asteroid a : asteroids) {
System.out.println("RENDER A");
renderer.setColor(0, 0, 0, 1);
renderer.circle(a.getP().x, a.getP().y, a.getRadius());
}
}
Thx alot for your help Guys, i solved the problem. The method private boolean ueberlappMit(List asteroids) checks if the asteroids overlap and if its the case the Asteroids shoud be created again. The Problem was that by selecting a too high radius the Game got stuck in the do while loop in the Asteroid class.
So I'm having this issue with my game that I'm working on for practice and one of the things that I'm struggling with is having this random color change between these four colors red, green, blue, yellow. My objective is to have this ball bounce around the screen while changing between the four colors but I would like to have a delay or pause in between the swapping of the colors like for at least 3 or 5 seconds. So far in the code the ball seems to change but without delay I've tried using a few delay methods like Timer.Schedule but eveytime I use this the ball bounces around the screen but its all black and no color I would really appreciate any help? I felt silly asking a question like this because I have a feeling it may be a small issue.
public class Play implements Screen {
Game game;
private Rectangle field = new Rectangle();
private Ball ball = new Ball();
private Paddle paddle1 = new Paddle(), paddle2 = new Paddle();
private ShapeRenderer ballRenderer, paddleRenderer;
private float fieldTop, fieldBottom, fieldRight, fieldLeft;
private Color ballColor = new Color();
private Random rnd = new Random();
public Play(Game game){
this.game = game;
}
#Override
public void render(float delta) {
float dt = Gdx.graphics.getRawDeltaTime();
update(dt);
draw(dt);
}
private void update(float dt) {
updateBall(dt);
updatepaddle1(dt);
}
private void updatepaddle1(float dt) {
boolean moveLeft = false, moveRight = false;
if(Gdx.input.isTouched()){
moveLeft = true;
moveRight = false;
}
if(Gdx.input.isTouched()){
moveRight = true;
moveLeft = false;
}
if(moveRight){
paddle1.setVelocity(350f, 0f);
}else if(moveLeft){
paddle1.setVelocity(-350f, 0f);
}else{
paddle1.setVelocity(0, 0);
}
paddle1.Intergrate(dt);
}
private void updateBall(float dt) {
// TODO Auto-generated method stub
ball.Intergrate(dt);
ball.updateBounds();
if(ball.left() < fieldLeft){
ball.move(fieldLeft, ball.getY());
ball.reflect(true, false);
}
if(ball.right() > fieldRight){
ball.move(fieldRight - ball.getWidth(), ball.getVelocityX());
ball.reflect(true, false);
}
if(ball.bottom() < fieldBottom){
ball.move(ball.getX(), fieldBottom);
ball.reflect(false, true);
}
if(ball.top() > fieldTop){
ball.move(ball.getX(), fieldTop - ball.getHeight());
ball.reflect(false, true);
}
}
public void reset(){
ball.move(field.x + (field.width - ball.getWidth()) / 2, field.y + (field.height - ball.getHeight()) / 2);
Vector2 velocity = ball.getVelocity();
velocity.set(330f, 0f);
velocity.setAngle(360f-45f);
ball.setVelocity(velocity);
//set paddle
paddle1.move(field.x + (field.width * .4f), 0);
paddle2.move(field.x + (field.width * .4f), field.y + (field.height - paddle1.getHeight()));
}
private void draw(float dt) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
paddleRenderer.begin(ShapeType.Filled);
drawPaddles(dt);
paddleRenderer.end();
ballRenderer.begin(ShapeType.Filled);
ballColorSwap(ballColor);
drawBall(dt);
ballRenderer.end();
}
private void drawPaddles(float dt) {
paddleRenderer.rect(paddle1.getX(), paddle1.getY(), paddle1.getWidth(), paddle1.getHeight());
paddleRenderer.rect(paddle2.getX(), paddle2.getY(), paddle2.getWidth(), paddle2.getHeight());
}
int THRESHOLD = 4000;
long lastChanged = 0;
private void ballColorSwap(Color ballColor){
int rnd = (int)(Math.random() * 4);
if(rnd == 1){
ballColor.set(Color.RED);
}
if(rnd == 2){
ballColor.set(Color.BLUE);
}
if(rnd == 3){
ballColor.set(Color.GREEN);
}
if(rnd == 4){
ballColor.set(Color.YELLOW);
}
lastChanged = System.currentTimeMillis();
}
private void drawBall(float dt) {
if(System.currentTimeMillis() - lastChanged > THRESHOLD)
ballColorSwap(ballColor);
ballRenderer.circle(ball.getX(), ball.getY(), 20);
ballRenderer.setColor(ballColor);
}
#Override
public void resize(int width, int height) {
}
#Override
public void show() {
field.set(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
fieldLeft = field.x;
fieldRight = field.x + field.width;
fieldBottom = field.y;
fieldTop = field.y + field.height;
paddleRenderer = new ShapeRenderer();
ballRenderer = new ShapeRenderer();
reset();
}
#Override
public void hide() {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
}
}
Can you just add one more variable to save a timestamp?
int THRESHOLD = 4000; // 4 seconds
long lastChanged = 0; // timestamp
public void ballColorSwap(){
// maybe call it here?
if(System.currentTimeMillis() - lastChanged < THRESHOLD)
return;
int rnd = (int)(Math.random() * 4);
if(rnd == 1){
ballColor.set(Color.RED);
}
if(rnd == 2){
ballColor.set(Color.BLUE);
}
if(rnd == 3){
ballColor.set(Color.GREEN);
}
if(rnd == 4){
ballColor.set(Color.YELLOW);
}
// set the timestamp
lastChanged = System.currentTimeMillis();
}
private void drawBall(float dt) {
ballRenderer.circle(ball.getX(), ball.getY(), 20);
ballRenderer.setColor(ballColor);
}
Note: I haven't tested this code. It might need some modification but hope you get the idea.
I'm new to libgdx, I'm trying to make a sprite move while the camera follows. I can make the sprite move perfectly until I attach the camera to it. When I click, the sprite will move wherever it feels like (it seems) and the camera will follow properly. I've tried a few different things but at this point its just guessing and checking.
public class MyGdxGame implements ApplicationListener {
OrthographicCamera mCamera;
SpriteBatch mBatch;
Texture mTexture, mMap;
Sprite sprite;
float touchX, touchY;
float spriteX, spriteY, speed = 5;
#Override
public void create() {
float CAMERA_WIDTH = 480, CAMERA_HEIGHT = 320;
mBatch = new SpriteBatch();
mTexture = new Texture(Gdx.files.internal("data/logo.png"));
mMap = new Texture(Gdx.files.internal("data/sc_map.png"));
mCamera = new OrthographicCamera(CAMERA_WIDTH, CAMERA_HEIGHT);
mCamera.setToOrtho(false, CAMERA_WIDTH, CAMERA_HEIGHT);
}
#Override
public void dispose() {
}
#Override
public void render() {
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
mBatch.setProjectionMatrix(mCamera.combined);
mCamera.update();
mBatch.begin();
updateInput();
drawD();
mBatch.end();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
public void drawD() {
mCamera.position.set(spriteX, spriteY, 0);
mBatch.draw(mMap, 0, 0);
mBatch.draw(mTexture, spriteX, spriteY);
}
public void updateInput() {
if (Gdx.input.justTouched()) {
touchX = Gdx.input.getX();
touchY = Gdx.input.getY();
}
if (touchX != spriteX) {
if (spriteX < touchX) {
spriteX += speed;
}
if (spriteX > touchX) {
spriteX -= speed;
}
}
if (touchY != spriteY) {
if (spriteY > Gdx.graphics.getHeight() - touchY) {
spriteY -= 10;
}
if (spriteY < Gdx.graphics.getHeight() - touchY) {
spriteY += 10;
}
}
}
}
Since you have spent a decent amount of time and are trying to get it working, I will give you a little push forward closer to what you are looking for. Look over the changes I made and below I will outline what I did to help you understand the code better.
Orthographic Camera, when you setup the camera 0,0 is the center of the screen. The width and the height are what you specified into the constructor. So the top edge would be x, 160 and the bottom edge would be x, -160. The left edge would be -240, y and the right edge would be 240, y.
drawD() Notice that I'm drawing the sprite in the middle of the image and it isn't moving. I instead move the map around in the opposite direction (y is inverted).
updateInput() Notice I pass in a delta value (this is the time in seconds between frames) this allows you to smoothly move things. The speed is 120, so this will smoothly move your character at a rate of 120/second.
The if condition is basically a simply way to compare the float values so it stops when it gets close enough. This prevents it from over shooting the target position and then bouncing back and forth because it might not be able to get to the exact value.
I added dispose calls for the textures you loaded, these are important as you don't want to fill up your memory.
I hope this helps get you started and pointed in the right direction. Working on games is a lot of work and takes time, so be patient and be ready to learn lots along the way!
Based on your comment I believe what you are looking for is something closer to this:
public class MyGdxGame implements ApplicationListener {
OrthographicCamera mCamera;
SpriteBatch mBatch;
Texture mTexture, mMap;
float touchX, touchY;
float spriteX, spriteY, speed = 120;
final float CAMERA_WIDTH = 480, CAMERA_HEIGHT = 320;
#Override public void create() {
mCamera = new OrthographicCamera(CAMERA_WIDTH, CAMERA_HEIGHT);
mBatch = new SpriteBatch();
mTexture = new Texture(Gdx.files.internal("data/logo.png"));
mMap = new Texture(Gdx.files.internal("data/sc_map.png"));
}
#Override public void dispose() {
mTexture.dispose();
mMap.dispose();
}
#Override public void render() {
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
updateInput(Gdx.graphics.getDeltaTime());
mCamera.update();
mBatch.setProjectionMatrix(mCamera.combined);
mBatch.begin();
drawD();
mBatch.end();
}
#Override public void resize(final int width, final int height) {}
#Override public void pause() {}
#Override public void resume() {}
public void drawD() {
mBatch.draw(mMap, -spriteX - (mMap.getWidth() / 2), spriteY - (mMap.getHeight() / 2));
mBatch.draw(mTexture, -32, -32, 64, 64);
}
public void updateInput(final float delta) {
if (Gdx.input.justTouched()) {
touchX = Gdx.input.getX() - (Gdx.graphics.getWidth() / 2);
touchY = Gdx.input.getY() - (Gdx.graphics.getHeight() / 2);
}
final float dv = delta * speed;
if (Math.abs(touchX - spriteX) > 1) {
if (spriteX < touchX) {
spriteX += dv;
}
if (spriteX > touchX) {
spriteX -= dv;
}
}
if (Math.abs(touchY - spriteY) > 1) {
if (spriteY > touchY) {
spriteY -= dv;
}
if (spriteY < touchY) {
spriteY += dv;
}
}
}
}