I am trying to bounce a ball in an android project using the libGDX game engine.
ball = new Texture("football.jpg");
batch = new SpriteBatch();
sprite = new Sprite(ball);
render(float delta)
{
batch.begin();
sprite.draw(batch);
batch.end();
stage.draw();
jumpUp(); //here i call the jump function..
}
The jump function looks like this:
public void jumpUp()
{
sprite.setY(sprite.getY()+2);
dem=sprite.getY();
if(dem==100.0f)
{
jumpDown();
}
}
public void jumpDown()
{
sprite.setY(sprite.getY()-1);
}
The ball is actually moving upward but it's not coming down again.
Should I also call jumpDown() in the render() method?
The official wiki libgdx lifecycle states that game logic updates are also done in the render() function. So, yes you should also call jumpDown() there. I would however propose that you keep it simple and only use one function like this:
private Texture ballTexture;
private Sprite ballSprite;
private SpriteBatch batch;
private dirY = 2;
create(){
ballTexture = new Texture("football.jpg");
ballSprite = new Sprite(ballTexture);
batch = new SpriteBatch();
}
render(float delta){
recalculateBallPos(delta);
batch.begin();
sprite.draw(batch);
batch.end();
stage.draw();
}
private void recalculateBallPos(delta){
float curPos = ballSprite.getY();
if(curPos + dirY > 100 || curPos + dirY < 0){
dirY = dirY * -1 //Invert direction
}
ballSprite.setY(curPos+dirY)
}
This still might look a bit choppy but I hope it's a good way to start.
The problem is the following:
Your Ball goes up, until it's y-value is exactly 100.0f. If thats the case, you decrease it by 1, which results in an y-value of 99.0f.
In the next render you call jumpUp again, which results in a y-value of 101.
This time your condition is not met, the jumpDown() is not called.
Even if you change your condition to >= 100.0f, your Ball will always move up by 2 and down by 1, which results in an increasing y-value.
Instead you should call the method something like updateBallPos and store a boolean up.
In updateBallPos you can simply check the boolean up, if it is true, increase the y-value, if it is fales, decrease it.
Also you need to update this boolean up in the updateBallPos method:
if (up && sprite.getY() >= 100.0f)
up = false
else if (!up && sprite.getY() <= 0.0f)
up = true
Related
I have been playing around with LibGDX for a good bit now and haven't found a problem I couldn't solve until now. When I run my project sometimes everything works perfectly fine but about 1 out of 10 times the camera will just refuse to update it seems unless the game window is either over another programs existing window or I physically grab the window with my mouse and move it around while moving my sprite around so that I can see it updating. anyone have any ideas what could be causing this?
#Override
public void create () {
int tileSize = 16;
int w = 30 * tileSize;
int h = 17 * tileSize;
viewport.setScreenSize(w, h);
camera = new OrthographicCamera();
camera.setToOrtho(false,viewport.getScreenWidth(),viewport.getScreenHeight());
camera.update();
mapGenerator = new MapGenerator();
tiledMapRenderer = new OrthogonalTiledMapRenderer(mapGenerator.getTiledMap());
spawner = new EntitySpawner(mapGenerator.getMapObjects());
spawner.spawn();//there is a to do in the entity spawner class to move this else where
sb = new SpriteBatch();
hud = new Hud(camera);
Gdx.input.setInputProcessor(this);
Gdx.graphics.setResizable(false);//makes it so you can't just drag the game window to any size since its easy to distort it
Gdx.graphics.setWindowedMode(1280,720);//resolution size windowed
}
#Override
public void render () {
Gdx.gl.glClearColor(1, 0, 0, 1);//background color
Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
//update the camera
camera.position.x = spawner.player.sprite.getX();
camera.position.y = spawner.player.sprite.getY();
camera.update();
tiledMapRenderer.setView(camera);
tiledMapRenderer.render();
timeElapsed += Gdx.graphics.getDeltaTime();//simply time that has passed based off delta time
sb.setProjectionMatrix(camera.combined);
sb.begin(); //start the sprite batch
spawner.draw(sb);//draw any entities with the spawner
hud.draw(sb);//draw the HUD
sb.end();//end the sprite batch
}
I'm creating a Minecraft clone menu, the yellow text on the logo is causing problems. It is a sprite and I'm using the scale methods to scale it up and down like in the actually menu of the game. This scaling uses Delta Time so it is runs smoothly. But whenever I seem to move the window it pauses my game momentarilly and creates an inaccurate Delta Time such as: 3.0482762
9.7077E-4
4.25514E-4
. These inaccuraces make my text scale more than I want, here is my code I am using LibGdx:
#Override
public void render(float delta) {
// Update
System.out.println(delta);
if(titleEnlargement)
{
if(title.getScaleX() < 1.1)
title.setScale(title.getScaleX() + (delta * 0.4f));
else
titleEnlargement = false;
}
else if(!titleEnlargement)
{
title.setScale(title.getScaleX() - (delta * 0.4f));
if(title.getScaleX() <= 1)
titleEnlargement = true;
}
// Render
batch.draw(background, 0, 0);
logo.draw(batch);
title.draw(batch);
}
You can clip the delta so that it never exceeds a certain value. This is what Stage does to prevent jitters with actions.
Place the following at the start of your render method:
delta = Math.min(delta, 1 / 30f);
I have a bug object that I want to move across the screen as soon as the game starts. The bug starts from the bottom left of the screen and is supposed to move to the top right and stop. What I have is the bug never really gets to the top right because the game screen(X and Y) size are not equal. How do I make the bug move to that position?
This is what I have.
public void create() {
spriteBatch = new SpriteBatch();
bug = new Sprite(new Texture("EnemyBug.png"));
bug.setSize(50, 85);
bug.setPosition(0,0);
}
public void render() {
xdeg++;
ydeg++;
Gdx.gl.glClearColor(0.7f, 0.7f, 0.2f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
spriteBatch.begin();
bug.translate(xdeg, ydeg);
bug.draw(spriteBatch);
spriteBatch.end();
}
I'll assume that you know your window width (W) and height (H). First find the W / H ratio:
float ratio = screenWidth / screenHeight;
Then update your bug position accordingly:
bug.translate(ratio, 1);
This will make the sprite move through the screen diagonal.
pretty much i want my texture to move to a random position on the screen when its touched and when its missed i want to system.out("missed"). I cant figure out how to see if its touched. right now i can only get if the screen is touch and it records about 10 touches for every one touch because it renders so fast.
public void render(float delta) {
Gdx.gl.glClearColor(0,1,0,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
game.batch.setProjectionMatrix(camera.combined);
game.batch.begin();
if(Gdx.input.isTouched()) {
int randomX2 = (int)MathUtils.random(100,500);
int randomY2 = (int)MathUtils.random(100,500);
game.batch.draw(boxImage, randomX2, randomY2);
}
game.batch.end();
}
If randomX2 and randomY2 are your coordinates for the texture, you can check with this code:
Rectangle bounds = new Rectangle(randomX2, randomY2, boxImage.getWidth(), boxImage.getHeight());
Vector3 tmp = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(tmp);
if (bounds.contains(tmp.x, tmp.y)) {
System.out.println("Is touched");
}
I could solve this without using Vector3.
var upArrowCircle = Circle(randomX, randomY, radius)
if(upArrowCircle.contains(Gdx.input.getX().toFloat(), Gdx.input.getY().toFloat()))
{
Gdx.app.log("upArrow", "contains")
}
For me it works perfectly.
I have been making a game in which there is number of objects in negative 'y' for which I had taken the arrayList and I am moving the main character in downward direction.But when the camera move with the character the objects are not moving smooth, they are getting jerks after some interval of time.The code for that is following
#Override
public void create() {
camera = new OrthographicCamera(480, 720);
camera.position.set(480 / 2, 720 / 2, 0);
batch = new SpriteBatch();
int i;
this.baloonArrList = new ArrayList<Baloon>();
for (i = 0; i < 3000; i += 300) {
Baloon baloon = new Baloon(200, i);
baloonArrList.add(baloon);
System.out.println(baloon.balloon_y);
}
texture1 = new Texture(Gdx.files.internal("data/sheet_final.png"));
textureRegion1 = new TextureRegion(texture1, 561, 156, 115, 101);
}
#Override
public void render() {
GLCommon gl = Gdx.gl;
Gdx.gl.glClearColor(1, 1, 1, 1);
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
camera.position.y += 4;
camera.update();
batch.setProjectionMatrix(camera.combined);
batch.begin();
int len = baloonArrList.size();
for (int i = 0; i < len; i++) {
batch.draw(textureRegion1, baloonArrList.get(i).balloon_x,
baloonArrList.get(i).balloon_y, 100, 100);
}
batch.end();
}
So, how can I make the motion of objects smooth.
I believe the source of your issue is the following line:
camera.position.y += 4;
You should instead change it to a smaller value, or better, make it based on the speed of the frame rate:
camera.position.y += 4 * Gdx.graphics.getDeltaTime();
This way your camera will move in the y direction 4 pixels every second, instead of 4 pixels every frame. (Of course you may need to increase the 4 to make it faster, but it will keep it quite smooth.)
If the rendering is jerky and inconsistent (use the builtin FPSLogger to find out what framerate you're getting), then something is taking more/variable amounts of time during rendering. You should use a profiler to figure out where time is going. The Android DDMS tools included with Eclipse are pretty good. Too-frequent garbage collection is often a source of variable runtimes, but its best to understand what is going on before trying to fix it.
That said, #Jyro117's suggestion to make your state updates frame-rate independent is always a good idea.