Friday, January 4, 2019

How to make a sprite jump up and then return to original position android java


I am just starting out in game development and I am trying to make a simple android game using GDXLib. I want to make my sprite "ball" jump straight up in the air and then return to where it originally was. How would I do this? I have looked at multiple other answers from similar questions but none seem to work with my code. This is my code so far:


@Override
public void create () {
batch = new SpriteBatch();
background = new Texture("gamebackground.png");

ball = new Texture("ball2.png");
ball.setFilter(Texture.TextureFilter.Nearest, Texture.TextureFilter.Nearest);


spike1 = new Texture("spike1.png");
spike1.setFilter(Texture.TextureFilter.Nearest, Texture.TextureFilter.Nearest);
spike2 = new Texture("spike2.png");

}

@Override
public void render () {

batch.begin();

float scaleFactor = 2.0f;
batch.draw(background, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.draw(ball, 80, 145, ball.getWidth() * scaleFactor, ball.getHeight() * scaleFactor);
batch.end();

Gdx.input.setInputProcessor(new InputAdapter () {
@Override
public boolean keyDown (int keycode) {
if(keycode==Keys.UP)
{

ball.setHeight(ball.getHeight()+50);
}
return true;

}


@Override
public void dispose () {


}

}



Answer



First of all, your ball shoul not be a texture. IMHO it should have a texture. That means you should create an ball object which has a texture as an attribute. This object can then have x and y attributes as well as width and height attributes that you can change at will.


If you look at the libgdx documentation you see that Texture has no such thing as a setHeight method, and that makes sense as your texture has a set width and height.


When you have your ball object, it is not the height you should change, but rather the position (y).


Gdx.input.setInputProcessor(new InputAdapter () {
@Override
public boolean keyDown (int keycode) {

if(keycode==Keys.UP)
{
ball.setY(ball.getY() + 50);
}
return true;
}
}

Like this your ball with elevate itself as long as you keep UP pressed. (If it is going down instead it means the y origin is at the top so you should do -50 instead).


Finally you can draw the ball like this



batch.draw(ball, ball.x, ball.y, ball.getWidth() * scaleFactor, ball.getHeight() * scaleFactor);

Try making this work first, and then you can think about making the ball go down to the origin or about making the jump more "natural".


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...