Quantcast
Channel: Question and Answer » libgdx
Viewing all articles
Browse latest Browse all 434

LibGDX: Its there any way to calculate the speed of a repeated scrolling background?

$
0
0

I’m trying to calculate the scrolling speed of an background, I’m doing something like this on the background class:

private Texture texture = new Texture(Gdx.files.internal("backgound.png"));
private Sprite sprite;

private float scrollTimer = 0.0f;
private static float scrollFactor = 0.2f;


public Background() {
    texture.setWrap(TextureWrap.Repeat, TextureWrap.Repeat);
    int width = texture.getWidth();
    int height = texture.getHeight();
    sprite = new Sprite(texture, 0, 0, width, height);
    sprite.setSize(1280, 320);

}

@Override
public void act(float delta) {
    updateScrollFactor();
    scrollTimer += delta * scrollFactor;

    if (scrollTimer > 1.0f) {
        scrollTimer = 0.0f;
    }

    sprite.setU(scrollTimer);
    sprite.setU2(scrollTimer + 2);
}

@Override
public void draw(Batch batch, float alpha) {
    sprite.draw(batch, alpha);
}

private void updateScrollFactor() {
    //Increase scroll factor when the game score being higher.
}

public static float getScrollFactor() {
    return scrollFactor;
}

And in another class I’m trying to calculate the speed of this background above because I need the same speed to apply in the entity of mentioned class, that is described below:

private Texture texture;
private Sprite sprite;

public Item(String textureName) {
    texture = new Texture(Gdx.files.internal(textureName));
    int width = texture.getWidth();
    int height = texture.getHeight();
    sprite = new Sprite(texture, 0, 0, width, height);
    sprite.setSize(30f, 50f);
    //Sets initial position, the entity will be scrolled from the screen width to zero  
    sprite.setPosition(Gdx.app.getWidth() - 10, 10);
}

@Override
public void act(float delta) {
    scrollTimer = delta * Background.getScrollFactor();

    if (scrollTimer > 1.0f) {
        scrollTimer = 0.0f;
    }

    float x = sprite.getX();
    if (x + sprite.getWidth() > 0) {
        sprite.setX(x - Gdx.graphics.getWidth() * scrollTimer);
    } else {
        //sets to initial position when the entity vanish thru the window left side.
        sprite.setX(Gdx.graphics.getWidth() - 10);
    }
}

@Override
public void draw(Batch batch, float alpha) {
    sprite.draw(batch, alpha);
}

}

The case is the entity don’t run sync with background but i need this separated from the background because it is a clickable entity.

Thoughts?


Viewing all articles
Browse latest Browse all 434

Trending Articles