The text drawn by font and drawn in List inside Scrollpane seem with different sizes. This is how I draw text:
font.draw(batch, "score", 500, 700);
And how I draw text in List inside ScrollPane:
tfBackground = new Texture(Gdx.files.internal("tfbackground.png"));
knob_scroll = new Texture(Gdx.files.internal("knob_scroll.png"));
scroll_horizontal = new Texture(Gdx.files.internal("scroll_horizontal.png"));
sps.background = new TextureRegionDrawable(new TextureRegion(tfBackground));
sps.vScroll = new TextureRegionDrawable(new TextureRegion(scroll_horizontal));
sps.vScrollKnob = new TextureRegionDrawable(new TextureRegion(knob_scroll));
listS = new List.ListStyle();
listS.font = font;
listS.fontColorSelected = Color.BLACK;
listS.fontColorUnselected = Color.GRAY;
listS.selection = new TextureRegionDrawable(new TextureRegion(tfBackground));
scoreList = new List<String>(listS);
items = new Array<String>();
res += "score 1, score 2, score 3, score 4, score 5, score 6, score 7, score 8, score 9, score 10";
String name_score[] = res.split(",");
for(String s: name_score)
{
items.add(s);
}
scoreList.setItems(items);
scoreList.pack();
scrollPane = new ScrollPane(scoreList, sps);
addActor(scrollPane);
And this is the weird(?) result:
It seems that scrollpane is scaling somehow. I don't want it the text inside scrollpane to be scaled.
This is the whole code:
public class ResultScreen extends AbstractScreen{
private OrthographicCamera camera;
private Viewport viewport;
private BitmapFont font;
private SpriteBatch batch;
private String res;
private float time = 10;
private Texture tfBackground, knob_scroll, scroll_horizontal;
private List<String> scoreList;
private ScrollPane scrollPane;
private List.ListStyle listS;
private ScrollPane.ScrollPaneStyle sps;
private Array<String> items;
public ResultScreen(float time, String res) {
this.time = time;
font = new BitmapFont(Gdx.files.internal("aw.fnt"));
font.setColor(Color.BLACK);
camera = new OrthographicCamera();
viewport = new StretchViewport(800, 1024, camera);
//viewport = new FitViewport(1240, 800, camera);
batch = new SpriteBatch();
camera.position.x = 400;
camera.position.y = 512;
viewport.update(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
this.res = res;
fillList();
}
#Override
public void buildStage() {
// TODO Auto-generated method stub
}
#Override
public void resize(int width, int height) {
viewport.update(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
}
#Override
public void render(float delta) {
super.render(delta);
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined);
batch.begin();
font.draw(batch, "score", 500, 700);
batch.end();
draw();
act();
}
private void fillList()
{
sps = new ScrollPane.ScrollPaneStyle();
tfBackground = new Texture(Gdx.files.internal("tfbackground.png"));
knob_scroll = new Texture(Gdx.files.internal("knob_scroll.png"));
scroll_horizontal = new Texture(Gdx.files.internal("scroll_horizontal.png"));
sps.background = new TextureRegionDrawable(new TextureRegion(tfBackground));
sps.vScroll = new TextureRegionDrawable(new TextureRegion(scroll_horizontal));
sps.vScrollKnob = new TextureRegionDrawable(new TextureRegion(knob_scroll));
listS = new List.ListStyle();
listS.font = font;
listS.fontColorSelected = Color.BLACK;
listS.fontColorUnselected = Color.GRAY;
listS.selection = new TextureRegionDrawable(new TextureRegion(tfBackground));
scoreList = new List<String>(listS);
items = new Array<String>();
res += "score 1, score 2, score 3, score 4, score 5, score 6, score 7, score 8, score 9, score 10";
String name_score[] = res.split(",");
for(String s: name_score)
{
items.add(s);
}
scoreList.setItems(items);
scoreList.pack();
scrollPane = new ScrollPane(scoreList, sps);
scrollPane.setWidth(300);
System.out.println(Gdx.graphics.getWidth());
addActor(scrollPane);
}
}
PS: Abstract screen extends Stage and implements Screen.
Your constructor doesn't call through to a superclass constructor, which would also need to call through to one of the Stage constructors to make sure your Stage is properly set up.
What's going on here is that you set up a camera and viewport (and SpriteBatch, although not part of the issue) that are used only for your font.draw and are distinct from what the Stage uses.
Your class needs to look something like this:
public class ResultScreen extends AbstractScreen{
private OrthographicCamera camera;
private Viewport viewport;
private BitmapFont font;
private Batch batch; //<------------changed
private String res;
private float time = 10;
private Texture tfBackground, knob_scroll, scroll_horizontal;
private List<String> scoreList;
private ScrollPane scrollPane;
private List.ListStyle listS;
private ScrollPane.ScrollPaneStyle sps;
private Array<String> items;
public ResultScreen(float time, String res) {
super(new StretchViewport(800, 1024)); //Call an AbstractScreen constructor that calls a Stage constructor
this.time = time;
font = new BitmapFont(Gdx.files.internal("aw.fnt"));
font.setColor(Color.BLACK);
camera = getCamera(); //<------------changed
viewport = getViewport(); //<------------changed
batch = getBatch(); //<------------changed
camera.position.x = 400;
camera.position.y = 512;
// unnecessary can remove because this is called in resize: viewport.update(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
this.res = res;
fillList();
}
}
For example, AbstractScreen could have a constructor like this:
public AbstractScreen(Viewport viewport){
super(viewport);
}
Related
Im new with libgdx. Im going to code a android game. The Player is moving by itself, but if you touch the screen(or click with the mouse) the player will stop. I want to add a pause button. It do render, but if I touch/click on the button the listener doesnt react, just the player stops.
Thats the class with the imporant methods about the button:
public class PlayState extends State {
private EntityManager entityManager;
private Player player;
private Texture background;
private Texture filter;
private BitmapFont font;
private Sound click, boost;
private Drug drug;
private Border border;
private House house;
public static final int FIELD_SIZE_HEIGHT = 1000;
public static final int FIELD_SIZE_WIDTH = 500;
private int collectedDrugs;
private boolean pause, renderLost;
private boolean boostSound;
private ImageButton button;
private Drawable drawable;
private Texture textureBtn;
public PlayState(GameStateManager gsm) {
super(gsm);
entityManager = new EntityManager();
player = new Player(this, 100, 100);
border = new Border();
background = new Texture("bggame.png");
filter = new Texture("filter.png");
cam.setToOrtho(false, MinniMafia.WIDTH, MinniMafia.HEIGHT);
click = Gdx.audio.newSound(Gdx.files.internal("Click.mp3"));
boost = Gdx.audio.newSound(Gdx.files.internal("boost.mp3"));
drug = new Drug();
house = new House();
collectedDrugs = 0;
font = new BitmapFont();
entityManager.addEntity(player);
entityManager.addEntity(drug);
entityManager.addEntity(border);
entityManager.addEntity(house);
pause = false;
renderLost = false;
boostSound = false;
Stage stage;
textureBtn = new Texture("pausebtn.png");
drawable = new TextureRegionDrawable(new TextureRegion(textureBtn));
button = new ImageButton(drawable);
button.setPosition(cam.position.x + cam.viewportWidth/2 - 50, cam.position.y + cam.viewportHeight/2 - 50);
button.addListener(new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
System.out.println("Button Pressed");
}
});
}
#Override
protected void handleInput() {
if (Gdx.input.justTouched()) {
click.play(0.2f);
}
if (Gdx.input.isTouched()) {
player.setStop(true);
boostSound = false;
} else {
if (!boostSound) {
boost.play(0.2f);
boostSound = true;
}
player.setStop(false);
}
}
#Override
public void update(float dt) {
if (!pause) {
handleInput();
entityManager.updateEntities(dt);
setCam();
button.setPosition(cam.position.x + cam.viewportWidth/2 - 60, cam.position.y + cam.viewportHeight/2 - 60);
if (drug.collides(player.getBounds())) {
entityManager.disposeEntity(drug);
player.setGotDrug(true);
}
if (border.collides(player.getBounds()) && !border.isOpen()) {
pause = true;
renderLost = true;
}
if (house.collides(player.getBounds()) && player.isGotDrug()) {
player.setGotDrug(false);
collectedDrugs++;
drug = new Drug();
entityManager.addEntity(drug);
}
} else if (renderLost = true) {
if (Gdx.input.isTouched()) {
gsm.set(new MenuState(gsm));
dispose();
}
}
}
#Override
public void render(SpriteBatch sb) {
sb.setProjectionMatrix(cam.combined);
sb.begin();
sb.draw(background, 0, 0);
entityManager.renderEntities(sb);
button.draw(sb, 10f);
font.draw(sb, "" + collectedDrugs, cam.position.x - cam.viewportWidth / 2 + 10, cam.position.y - cam.viewportHeight / 2 + 20);
if (renderLost) {
sb.draw(filter, cam.position.x - cam.viewportWidth / 2, cam.position.y - cam.viewportHeight / 2);
font.draw(sb, "LOST! SCORE:" + collectedDrugs, cam.position.x - 50, cam.position.y);
}
sb.end();
}
I suppose that there is missing sth, but I can not figure it out. Can sb help me please?
LG bttl
You have to set your Stage as InputProcessor for Scene2d to work. Documentation
For using Stage and your own code as InputProcessor, add both to an InputMultiplexer and use this.
I'm writing a javafx image generator for .STL files. I'm using StlMeshImporter to import the STL file. However, when I import files in my javafx scene and try to take a snapshot, I get different result for each file because they are not center in the scene.
I would like to be able to scale it or center it, in the scene dynamically to take a snapshot. Is there a way to get the width and height of the object so I could set a scale factor, and offset automatically?
Here is my class:
public class STLImageGenerator extends Application {
private static final String MESH_FILENAME
= "./9sk02_flex_r02.stl";
private static final int VIEWPORT_SIZE = 800;
private static final double MODEL_SCALE_FACTOR = 3;
private static final double MODEL_X_OFFSET = 0;
private static final double MODEL_Y_OFFSET = 0;
private static final double MODEL_Z_OFFSET =0 ;
// private static final int VIEWPORT_SIZE = 4096;
private static final Color lightColor = Color.rgb(204, 204, 204);
private static final Color jewelColor = Color.rgb(0, 100, 204);
final static int CANVAS_WIDTH = 512;
final static int CANVAS_HEIGHT = 512;
private Group root;
private PointLight pointLight;
Canvas canvas = null;
PerspectiveCamera perspectiveCamera = null;
static MeshView[] loadMeshViews() {
File file = new File(MESH_FILENAME);
StlMeshImporter importer = new StlMeshImporter();
importer.read(file);
Mesh mesh = importer.getImport();
return new MeshView[]{new MeshView(mesh)};
}
private Group buildScene() {
MeshView[] meshViews = loadMeshViews();
System.out.println("MESHVIEWS: " + meshViews.length);
for (int i = 0; i < meshViews.length; i++) {
System.out.println("meshViews[i].getLayoutX():"+meshViews[i].getLayoutX());
meshViews[i].setScaleX(MODEL_SCALE_FACTOR);
meshViews[i].setScaleY(MODEL_SCALE_FACTOR);
meshViews[i].setScaleZ(MODEL_SCALE_FACTOR);
meshViews[i].setTranslateX((VIEWPORT_SIZE / 2) + MODEL_X_OFFSET-MODEL_SCALE_FACTOR);
meshViews[i].setTranslateY((VIEWPORT_SIZE / 2) + MODEL_Y_OFFSET-MODEL_SCALE_FACTOR);
meshViews[i].setTranslateZ((VIEWPORT_SIZE / 2) + MODEL_Z_OFFSET);
PhongMaterial sample = new PhongMaterial(jewelColor);
sample.setSpecularColor(lightColor);
sample.setSpecularPower(16);
meshViews[i].setMaterial(sample);
//meshViews[i].getTransforms().setAll(new Rotate(38, Rotate.Z_AXIS), new Rotate(20, Rotate.X_AXIS));
}
pointLight = new PointLight(lightColor);
pointLight.setTranslateX(VIEWPORT_SIZE * 3 / 4);
pointLight.setTranslateY(VIEWPORT_SIZE / 2);
pointLight.setTranslateZ(VIEWPORT_SIZE / 2);
PointLight pointLight2 = new PointLight(lightColor);
pointLight2.setTranslateX(VIEWPORT_SIZE * 1 / 4);
pointLight2.setTranslateY(VIEWPORT_SIZE * 3 / 4);
pointLight2.setTranslateZ(VIEWPORT_SIZE * 3 / 4);
PointLight pointLight3 = new PointLight(lightColor);
pointLight3.setTranslateX(VIEWPORT_SIZE * 5 / 8);
pointLight3.setTranslateY(VIEWPORT_SIZE / 2);
pointLight3.setTranslateZ(0);
Color ambientColor = Color.rgb(80, 80, 80, 0);
AmbientLight ambient = new AmbientLight(ambientColor);
root = new Group(meshViews);
root.getChildren().add(pointLight);
root.getChildren().add(pointLight2);
root.getChildren().add(pointLight3);
root.getChildren().add(ambient);
//root.setAutoSizeChildren(true);
return root;
}
private PerspectiveCamera addCamera(Scene scene) {
perspectiveCamera = new PerspectiveCamera();
System.out.println("Near Clip: " + perspectiveCamera.getNearClip());
System.out.println("Far Clip: " + perspectiveCamera.getFarClip());
System.out.println("FOV: " + perspectiveCamera.getFieldOfView());
perspectiveCamera.setFieldOfView(5);
scene.setCamera(perspectiveCamera);
return perspectiveCamera;
}
#Override
public void start(Stage primaryStage) {
//canvas = new Canvas(VIEWPORT_SIZE, VIEWPORT_SIZE);
Group group = buildScene();
Scene scene = new Scene(group, VIEWPORT_SIZE, VIEWPORT_SIZE, true, SceneAntialiasing.BALANCED);
scene.setFill(Color.rgb(255, 255, 255));
group.setAutoSizeChildren(true);
addCamera(scene);
//root.getChildren().add(canvas);
primaryStage.setMaxHeight(CANVAS_HEIGHT);
primaryStage.setMaxWidth(CANVAS_WIDTH);
String fname = MESH_FILENAME.substring(0, MESH_FILENAME.length() - 3) + "png";
File file = new File(fname);
primaryStage.setTitle("Jewel Viewer");
primaryStage.setScene(scene);
primaryStage.show();
try {
SnapshotParameters s = new SnapshotParameters();
// s.setCamera(perspectiveCamera);
// s.setViewport(Rectangle2D.EMPTY);
WritableImage wim = new WritableImage(1024, 1024);
scene.snapshot(wim);
// WritableImage writableImage = root.snapshot(new SnapshotParameters(), null);
RenderedImage renderedImage = SwingFXUtils.fromFXImage(wim, null);
ImageIO.write(renderedImage, "png", file);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
System.setProperty("prism.dirtyopts", "false");
Platform.setImplicitExit(false);
launch(args);
}
Im trying to do a little game in LibGdx, right now i have a spaceship that can move with a touchpad in every directions and the camera follows it.
Im tryng to accomplish a parallax background made of stars that moves depending of where the spaceship is going.
Here it is the code, Im giving you all the class just to be sure to not mess up, for im new with this programming code.
public class TouchPadTest extends OrthographicCamera implements ApplicationListener {
public static final int WIDTH=480;
public static final int HEIGHT=800;
private OrthographicCamera camera;
private Stage stage;
private SpriteBatch batch;
private Touchpad touchpad;
private TouchpadStyle touchpadStyle;
private Skin touchpadSkin;
private Drawable touchBackground;
private Drawable touchKnob;
private Texture blockTexture;
private Sprite blockSprite;
private float blockSpeed;
public void create() {
batch = new SpriteBatch();
//Create camera
float aspectRatio = (float) Gdx.graphics.getWidth() / (float) Gdx.graphics.getHeight();
camera = new OrthographicCamera();
camera.setToOrtho(false, TouchPadTest.WIDTH, TouchPadTest.HEIGHT);
//Create a touchpad skin
touchpadSkin = new Skin();
//Set background image
touchpadSkin.add("touchBackground", new Texture("data/touchBackground.png"));
//Set knob image
touchpadSkin.add("touchKnob", new Texture("data/touchKnob.png"));
//Create TouchPad Style
touchpadStyle = new TouchpadStyle();
//Create Drawable's from TouchPad skin
touchBackground = touchpadSkin.getDrawable("touchBackground");
touchKnob = touchpadSkin.getDrawable("touchKnob");
//Apply the Drawables to the TouchPad Style
touchpadStyle.background = touchBackground;
touchpadStyle.knob = touchKnob;
//Create new TouchPad with the created style
touchpad = new Touchpad(10, touchpadStyle);
//setBounds(x,y,width,height)
touchpad.setBounds(15, 15, 200, 200);
//Create a Stage and add TouchPad
stage = new Stage(new FitViewport(Gdx.graphics.getWidth(),Gdx.graphics.getHeight()));
stage.addActor(touchpad);
Gdx.input.setInputProcessor(stage);
//Create block sprite
blockTexture = new Texture(Gdx.files.internal("data/shuttle2.png"));
blockSprite = new Sprite(blockTexture);
//Set position to centre of the screen
blockSprite.setPosition(Gdx.graphics.getWidth()/2-blockSprite.getWidth()/2, Gdx.graphics.getHeight()/2-blockSprite.getHeight()/2);
blockSpeed=5;
}
public void movePlayer(){
Vector2 v = new Vector2(touchpad.getKnobPercentX(), touchpad.getKnobPercentY());
float angle = v.angle();
if (touchpad.isTouched()){
blockSprite.setRotation(angle);
}
blockSprite.setX(blockSprite.getX() + touchpad.getKnobPercentX()*blockSpeed);
blockSprite.setY(blockSprite.getY() + touchpad.getKnobPercentY()*blockSpeed);
//Draw
camera.position.set(blockSprite.getX() + blockSprite.getWidth() / 2, blockSprite.getY() + blockSprite.getHeight() / 2, 0);
camera.update();
batch.setProjectionMatrix(camera.combined);
}
public void renderBackground() {
//---------------PARALLAX BACKGROUND---------------------//
}
public void dispose() {
}
public void render() {
Gdx.gl.glClearColor(0/255f,5/255f,15/255f,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
//Move blockSprite with TouchPad
movePlayer();
batch.begin();
renderBackground();
blockSprite.draw(batch);
batch.end();
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void resize(int width, int height) {
}
}
For a better exemple, this is the kind of result that i want to achieve: https://www.youtube.com/watch?v=zA91SaOR-Io, if you can help me it will be amazing. Thank You.
This working example of a 3 layer parallax background was adapted from the LibGdx Parallax test and should give you an idea on how to implement a parallax effect. The three images used are all 1024x1024px.
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector3;
public class Test extends ApplicationAdapter implements InputProcessor{
private SpriteBatch batch;
private ParallaxCamera camera;
private Texture bgClose;
private Texture bgMid;
private Texture bgFar;
final Vector3 curr = new Vector3();
final Vector3 last = new Vector3(-1, -1, -1);
final Vector3 delta = new Vector3();
#Override
public void create () {
bgClose = new Texture(Gdx.files.internal("starbg-close.png"));
bgMid = new Texture(Gdx.files.internal("starbg-mid.png"));
bgFar = new Texture(Gdx.files.internal("starbg-far.png"));
camera = new ParallaxCamera(1920,1080);
batch = new SpriteBatch();
Gdx.input.setInputProcessor(this);
}
#Override
public void render () {
//clear screen
Gdx.gl.glClearColor(0f, 0f, 0f, 1f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// background layer, no parallax, centered around origin
batch.setProjectionMatrix(camera.calculateParallaxMatrix(0, 0));
batch.disableBlending();
batch.begin();
batch.draw(bgFar, -(int)(bgFar.getWidth() / 2), -(int)(bgFar.getHeight() / 2));
batch.end();
batch.enableBlending();
batch.setProjectionMatrix(camera.calculateParallaxMatrix(0.25f, 0.25f));
batch.begin();
for (int i = 0; i < 9; i++) {
batch.draw(bgMid, i * bgClose.getWidth() - 512, -512);
}
batch.end();
batch.setProjectionMatrix(camera.calculateParallaxMatrix(.5f, .5f));
batch.begin();
for (int i = 0; i < 9; i++) {
batch.draw(bgClose, i * bgClose.getWidth() - 512, -512);
}
batch.end();
}
//.. omitted empty methods ..//
#Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
last.set(-1, -1, -1);
return false;
}
#Override
public boolean touchDragged(int x, int y, int pointer) {
camera.unproject(curr.set(x, y, 0));
if (!(last.x == -1 && last.y == -1 && last.z == -1)) {
camera.unproject(delta.set(last.x, last.y, 0));
delta.sub(curr);
camera.position.add(delta.x, delta.y, 0);
}
last.set(x, y, 0);
return false;
}
private class ParallaxCamera extends OrthographicCamera {
Matrix4 parallaxView = new Matrix4();
Matrix4 parallaxCombined = new Matrix4();
Vector3 tmp = new Vector3();
Vector3 tmp2 = new Vector3();
public ParallaxCamera (float viewportWidth, float viewportHeight) {
super(viewportWidth, viewportHeight);
}
public Matrix4 calculateParallaxMatrix (float parallaxX, float parallaxY) {
update();
tmp.set(position);
tmp.x *= parallaxX;
tmp.y *= parallaxY;
parallaxView.setToLookAt(tmp, tmp2.set(tmp).add(direction), up);
parallaxCombined.set(projection);
Matrix4.mul(parallaxCombined.val, parallaxView.val);
return parallaxCombined;
}
}
}
I am having trouble for the last 2 days to figure out what is wrong with my application. I'm trying to build a game, a platformer where the player needs to go up, (somewhat like doodlejump). I have build my testmap in tmx format. I have been trying to start the camera and the viewport to show the left-bottom of the world, so the player can move to the right and also upward. But this seems to difficult for a beginning libgdx learner!
I am using a Playscreen, a HUD and a MainActivity:
PlayScreen
private MainActivity game;
private OrthographicCamera gamecam;
private Viewport gameport;
private HUD hud;
private TmxMapLoader mapLoader;
private TiledMap map;
private OrthogonalTiledMapRenderer renderer;
private World world;
private Box2DDebugRenderer b2dr;
private Jack player;
public PlayScreen(MainActivity game){
// Initiates the game, camera, viewport and HUD
this.game = game;
gamecam = new OrthographicCamera();
hud = new HUD(game.batch);
gameport = new FitViewport(MainActivity.V_WIDTH, MainActivity.V_HEIGHT, gamecam);
// loading the map
mapLoader = new TmxMapLoader();
map = mapLoader.load("level1revised.tmx");
renderer = new OrthogonalTiledMapRenderer(map, 1 / MainActivity.PPM);
//initially set our gamecam to be centered correctly at the start of of map
gamecam.position.set(gameport.getWorldWidth() / 2, gameport.getWorldHeight() / 2, 0);
// Box2D world (graphics)
world = new World(new Vector2(0, -10), true);
b2dr = new Box2DDebugRenderer();
// New Jack
player = new Jack(world);
BodyDef bdef = new BodyDef();
PolygonShape shape = new PolygonShape();
FixtureDef fdef = new FixtureDef();
Body body;
// The ground as an object is defined
for(MapObject object: map.getLayers().get(2).getObjects().getByType(RectangleMapObject.class)){
Rectangle rect = ((RectangleMapObject) object).getRectangle();
bdef.type = BodyDef.BodyType.StaticBody;
bdef.position.set((rect.getX() + rect.getWidth()/2)/MainActivity.PPM, (rect.getY() + rect.getHeight()/2) /MainActivity.PPM);
body = world.createBody(bdef);
shape.setAsBox(rect.getWidth()/2, rect.getHeight()/2);
fdef.shape = shape;
body.createFixture(fdef);
}
public void update(float dt){
handleInput(dt);
world.step(1 / 60f, 6, 2);
//gamecam.position.x = player.b2body.getPosition().x;
gamecam.update();
renderer.setView(gamecam);
}
#Override
public void render(float delta) {
update(delta);
// Clear the screen
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// render the map
renderer.render();
// render the box2d
b2dr.render(world, gamecam.combined);
game.batch.setProjectionMatrix(hud.stage.getCamera().combined);
hud.stage.draw();
}
#Override
public void resize(int width, int height) {
gamecam.viewportWidth = width;
gamecam.viewportHeight = height;
}
HUD & Mainactivity
public HUD(SpriteBatch sb){
worldTimer = 300;
timeCount = 0;
score = 0;
viewport = new FitViewport(MainActivity.V_WIDTH, MainActivity.V_HEIGHT, new OrthographicCamera());
stage = new Stage(viewport, sb);
Table table = new Table();
table.top();
table.setFillParent(true);
countdownlabel = new Label(String.format("%03d", worldTimer), new Label.LabelStyle(new BitmapFont(), Color.RED));
scoreLabel = new Label(String.format("%06d", score), new Label.LabelStyle(new BitmapFont(), Color.RED));
timeLabel = new Label("TIME", new Label.LabelStyle(new BitmapFont(), Color.RED));
levelLabel = new Label("level 1", new Label.LabelStyle(new BitmapFont(), Color.RED));
table.add(timeLabel).expandX().padTop(10);
table.add(levelLabel).expandX().padTop(10);
table.row();
table.add(scoreLabel).expandX().padTop(10);
stage.addActor(table);
}
public class MainActivity extends Game {
public SpriteBatch batch;
public static final int V_WIDTH = 720;
public static final int V_HEIGHT = 480;
public static final float PPM = 1;
public static final String TITLE = "Jack the Pirate";
#Override
public void create () {
batch = new SpriteBatch();
setScreen(new PlayScreen(this));
}
#Override
public void render () {
super.render();
}
}
I have no clue where to look anymore, been through the basics countless times :( My tmx tilemap is 14 tiles wide, and 70 tiles high. The tiles themselves are 16x16. My test device is a Samsung Galaxy S3, and i wanted to use it in portrait mode.
Any ideas where to look? Thanks in advance for help!
I am developing a game with libgdx and i got stuck at a point. So My SpriteBatch draws for all the Rectangles that are in an array with the same texture but I want that every single one has its own texture. MY Code looks like this
public class GameScreen implements Screen{
final MrJetpack game;
OrthographicCamera camera;
SpriteBatch batch;
ShapeRenderer rend;
private Array<Rectangle> raindrops;
Texture enemy1,enemy2,enemy3,enemy4,endScreen;
TextureRegion[] enemys = new TextureRegion[4];
private int random;
public GameScreen(final MrJetpack game){
this.game = game;
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
enemy1 = new Texture(Gdx.files.internal("boxk.png"));
enemy2 = new Texture(Gdx.files.internal("boxg.png"));
enemy3 = new Texture(Gdx.files.internal("kugel.png"));
enemy4 = new Texture(Gdx.files.internal("kugelk.png"));
enemys[0] = new TextureRegion(enemy1);
enemys[1] = new TextureRegion(enemy2);
enemys[2] = new TextureRegion(enemy3);
enemys[3] = new TextureRegion(enemy4);
raindrops = new Array<Rectangle>();
rend = new ShapeRenderer();
batch = new SpriteBatch();
}
#Override
public void render(float delta) {
// TODO Auto-generated method stub
//Gdx.gl.glClearColor(0, (float)148/255,(float) 255/255, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
batch.setProjectionMatrix(camera.combined);
rend.begin(ShapeType.Filled);
rend.rect(0, 0, 800, 10);
rend.rect(0, 160, 800, 10);
rend.rect(0, 320, 800, 10);
rend.setColor(Color.ORANGE);
rend.end();
batch.begin();
for(Rectangle raindrop: raindrops) {
batch.draw(enemys[random], raindrop.x - 10, raindrop.y);
}
batch.end();
if(TimeUtils.nanoTime() - lastDropTime > spawnTime){
spawnRaindrop();
}
Iterator<Rectangle> iter = raindrops.iterator();
while(iter.hasNext()) {
Rectangle raindrop = iter.next();
raindrop.x -= 20 * Gdx.graphics.getDeltaTime();
if(raindrop.x < 0) {
spawnRaindrop();
iter.remove();
}
}
}
private void spawnRaindrop() {
Rectangle raindrop = new Rectangle();
raindrop.x = 800;
stages = MathUtils.random(1, 3);
random = MathUtils.random(0, 3);
raindrop.width = 30;
raindrop.height = 53;
raindrops.add(raindrop);
lastDropTime = TimeUtils.nanoTime();
}
So what actually happening is that everytime a new Rectangle spawns in the screen the other ones who were already displayed change the Texture so every Rectangle got the same Texture . Any solutions or examples?
EDIT: http://imgur.com/46ywYyy
This is my problem for people who understood my question false :)
Like you can see the texture is changing for all the other rectangles but i want everyone to have their static texture
They told you, one way to do it, but I see you do not clear, I'll put more or less as you might do.
I'll try to make the form more similar to what you already have in your code.
note
this code may have syntax error, among others, becouse I'm doing from the editor StackOverflow.
1- create a class that is derived from sprite, for example something like:
public class SpriteRaindrop extends Sprite{
Rectangle raindrop = new Rectangle();
public SpriteRaindrop(Texture t, int srcWidth,
int srcHeigth,
float posX,
float posY){
super(t, srcWidth, srcHeigth);
raindrop.x = posX;
raindrop.y = posY;
raindrop.width = srcWidth;
raindrop.height = srcHeigth;
setPosition(posX, posY);
}
public void updateR(){
raindrod.x = getX();
raindrod.y = getY();
}
}
This your code with with any changes
public class GameScreen implements Screen{
final MrJetpack game;
OrthographicCamera camera;
SpriteBatch batch;
ShapeRenderer rend;
private Array<SpriteRaindrop> raindrops;
Texture enemy1,enemy2,enemy3,enemy4,endScreen;
TextureRegion[] enemys = new TextureRegion[4];
private int random;
public GameScreen(final MrJetpack game){
this.game = game;
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
enemy1 = new Texture(Gdx.files.internal("boxk.png"));
enemy2 = new Texture(Gdx.files.internal("boxg.png"));
enemy3 = new Texture(Gdx.files.internal("kugel.png"));
enemy4 = new Texture(Gdx.files.internal("kugelk.png"));
enemys[0] = new TextureRegion(enemy1);
enemys[1] = new TextureRegion(enemy2);
enemys[2] = new TextureRegion(enemy3);
enemys[3] = new TextureRegion(enemy4);
raindrops = new Array<SpriteRaindrop>();
rend = new ShapeRenderer();
batch = new SpriteBatch();
}
#Override
public void render(float delta) {
// TODO Auto-generated method stub
//Gdx.gl.glClearColor(0, (float)148/255,(float) 255/255, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
batch.setProjectionMatrix(camera.combined);
rend.begin(ShapeType.Filled);
rend.rect(0, 0, 800, 10);
rend.rect(0, 160, 800, 10);
rend.rect(0, 320, 800, 10);
rend.setColor(Color.ORANGE);
rend.end();
batch.begin();
for(SpriteRaindrop raindrop: raindrops) {
//raindrop.translatex(-10f);
//what is raindrop.y value
raindrop.updateR();
raindrop.draw(batch);
}
batch.end();
if(TimeUtils.nanoTime() - lastDropTime > spawnTime){
spawnRaindrop();
}
Iterator<SpriteRaindrop> iter = raindrops.iterator();
while(iter.hasNext()) {
SpriteRaindrop raindrop = iter.next();
raindrop.translateX(-20f * Gdx.graphics.getDeltaTime());
if(raindrop.getX() < 0) {
spawnRaindrop();
iter.remove();
}
}
}
private void spawnRaindrop() {
stages = MathUtils.random(1, 3);
random = MathUtils.random(0, 3);
lastDropTime = TimeUtils.nanoTime();
SpriteRaindrop raindrop = new SpriteRaindrop(enemys[random],
30, 53,
800, 0);
raindrops.add(raindrop);
}
this is just an idea, but I think it can work, I hope you help
The variable random is global for class, once a new sprite spawns it sets the value to new random value and all of them are draw by:
batch.draw(enemys[random], raindrop.x - 10, raindrop.y);
You need to track this together with location per instance.