FreshRSS

Normální zobrazení

Jsou dostupné nové články, klikněte pro obnovení stránky.
PředevčíremHlavní kanál

Libgdx Bullet Physics not applying gravity to model instance

I create a modelinstance in Libgdx that I call yellowInstance. The modelinstance is defined as follows: I need it to fall down under the force of gravity, But it just stays in the air!

 ModelBuilder yellowBuilder = new ModelBuilder();
            yellowBuilder.begin();
            Node nod = yellowBuilder.node();
            nod.id = "yellowboxy";
            Material yellowMat = new Material();
            yellowMat.set(PBRColorAttribute.createBaseColorFactor(Color.YELLOW));
            MeshPartBuilder yellowPartBuilder = yellowBuilder.part("yellowboxy", GL20.GL_TRIANGLES, VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal, yellowMat);
            BoxShapeBuilder.build(yellowPartBuilder, 10f, 20f, 10f, 2f, 2f, 2f);
            yellowInstance = new ModelInstance(yellowBuilder.end());

I create the physics for it using Bullet Physics library as such:

btCollisionShape btBox = new btBoxShape(new Vector3(1,1,1)); //notice we take halves!
    Vector3 localInertia = new Vector3();
    btBox.calculateLocalInertia(5f,localInertia);

    //MotionStateForPhys msphys = new MotionStateForPhys(yellowInstance.transform);

    btRigidBody.btRigidBodyConstructionInfo info = new btRigidBody.btRigidBodyConstructionInfo(5f,null,btBox,localInertia);
    btRigidBody btYellowBody = new btRigidBody(info);

    /*btYellowBody.setMotionState(msphys);*/

    btYellowBody.setWorldTransform(yellowInstance.transform);

    dynamicsWorld.addRigidBody(btYellowBody);

    btYellowBody.activate(true);

here are the definitions for the important physics variables needed by the library

private btCollisionConfiguration collisionConfiguration;
private com.badlogic.gdx.physics.bullet.collision.btDispatcher btDispatcher;
private btDiscreteDynamicsWorld dynamicsWorld;
private btSequentialImpulseConstraintSolver solver;

collisionConfiguration = new btDefaultCollisionConfiguration();
    btDispatcher = new btCollisionDispatcher(collisionConfiguration);
    btInterface = new btDbvtBroadphase();
    solver = new btSequentialImpulseConstraintSolver();
    dynamicsWorld = new 
btDiscreteDynamicsWorld(btDispatcher,btInterface,solver,collisionConfiguration);
    dynamicsWorld.setGravity(new Vector3(0,-10f,0));

Here is how I update the timeStep for the Physics library:

private void update(float deltatime){
btYellowBody.activate(true);
    dynamicsWorld.stepSimulation(deltatime , 5 , 1/60f);

} 

Here is my render method that calls the update method where my Physics variables are:

inputHandler.UpdateAfterKeyPress(Gdx.graphics.getDeltaTime(),"levelone");
    
    worldBuilder.update(delta); //will update the physics in levelone!

    Gdx.gl.glClearColor(0, .25f, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    ScreenUtils.clear(BACKGROUND_COLOUR, true);

managerScenes.update(Gdx.graphics.getDeltaTime());
    managerScenes.render();

if (Gdx.input.isKeyJustPressed(Input.Keys.ESCAPE))
        Gdx.app.exit();

EDIT: IF I REMOVE THE FLOOR FROM THE PHYSICS SIMULATION, THE YELLOW BOX FALLS UNDER THE FORCE OF GRAVITY! WHY REMOVING THE FLOOR WILL MAKE THE BOX FALL DOWN!

this is how the floor is added: THERE IS SOMETHING I'M MISSING HERE!!

ModelBuilder mBuilder = new ModelBuilder();
    mBuilder.begin();

    // Start a new node with a specific name
    Node node = mBuilder.node();
    node.id = "floory"; // Set the node's id

    Material mat = new Material();
    mat.set(PBRColorAttribute.createBaseColorFactor(Color.BLACK));
    MeshPartBuilder mpartbuilder = mBuilder.part("floory", GL20.GL_TRIANGLES, VertexAttributes.Usage.Position|VertexAttributes.Usage.Normal,mat);
    BoxShapeBuilder.build(mpartbuilder,0,-0.5f,0,300f,1f,400f);
    ModelInstance mInstance = new ModelInstance(mBuilder.end());

    sManager.addScene(new Scene(mInstance));

    //create the physics id and body/shape properties
   

    btCollisionShape shape = Bullet.obtainStaticNodeShape(mInstance.nodes);


    btBoxShape/*btCollisionShape*/ btBox = new btBoxShape(new Vector3(150,0.5f,200)); //notice we take halves!
    btRigidBody.btRigidBodyConstructionInfo info = new btRigidBody.btRigidBodyConstructionInfo(0,null,btBox,Vector3.Zero);
    btRigidBody btBody = new btRigidBody(info);
    btBody.setWorldTransform(mInstance.transform);
  

    dynamicsWorld.addCollisionObject(btBody);
  • ✇Recent Questions - Game Development Stack Exchange
  • Use Stage's draw() method to invoke Actor's draw method in Libgdxuser2582651
    Question : In the following snippet, I wish to draw different shapes such as rectangles, circles, triangles etc. I will be creating different class files for each of such objects, as I did for Rectangle class here. I've been trying to invoke the draw method of Rectangle object from Stage object, but I am unable to do so. If I make a plain call to the draw method of the Rectangle object, I can draw the object. Can some one suggest me how is this possible ? Also, I had many other queries which
     

Use Stage's draw() method to invoke Actor's draw method in Libgdx

Question : In the following snippet, I wish to draw different shapes such as rectangles, circles, triangles etc. I will be creating different class files for each of such objects, as I did for Rectangle class here.

I've been trying to invoke the draw method of Rectangle object from Stage object, but I am unable to do so. If I make a plain call to the draw method of the Rectangle object, I can draw the object.

Can some one suggest me how is this possible ? Also, I had many other queries which I'd tried to put in comments. Please have a look at them and kindly help me in figuring out the concept beneath it.

Disclaimer : I am new to game programming, started with Libgdx.

Following is the Scan class :

package com.mygdx.scan.game;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.scenes.scene2d.Stage;

public class Scan extends ApplicationAdapter {
private Stage stage;
public static ShapeRenderer shapeRenderer;

@Override
public void create () {
    stage = new Stage();
    shapeRenderer = new ShapeRenderer();
    Rectangle rect1 = new Rectangle(50, 50, 100, 100);
    stage.addActor(rect1);

}

@Override
public void render () {
    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    shapeRenderer.setProjectionMatrix(stage.getCamera().combined);
    shapeRenderer.begin(ShapeType.Filled);
    shapeRenderer.setColor(Color.BLACK);
    //new Rectangle(50, 50, 100, 100).draw();
    shapeRenderer.end();
    // This should call Rectangles draw method. I want a Shapetype.Filled Rectangle. 
    // But I'm unable to invoke this method if I add the actor in stage object and invoke it's draw method. 
    stage.draw(); 
}

public void dispose() {
    stage.dispose();
}
}

Following is the Rectangle Actor class :

package com.mygdx.scan.game;

import com.badlogic.gdx.scenes.scene2d.Actor;

public class Rectangle extends Actor {

float xcord, ycord, width, height;
public Rectangle(float x , float y , float width, float height) {
    this.xcord = x;
    this.ycord = y;
    this.width = width;
    this.height = height;
}

// This needs to be called in the Scan class. I just want the draw       method to be invoked. 
// Also I wish to draw many such rectangles. What is the best practice to get hold of ShapeRenderer object from Scan class ?
// Should I use one instance of  ShapeRenderer object in Scan class or should I create ShapeRenderer object for each of the Rectangle object ??
// I also plan to repeat the activity for another object such as circles. So I would like to know the best practice here.
public void draw() {
    Scan.shapeRenderer.rect(this.xcord, this.ycord, this.width, this.height);
}

}

Differences between rotations and translations of different camera properties in LiBGDX

I am trying to understand the camera API (applicable to perspective camera ONLY) of LiBGDX.

It really does not make sense that you can call rotate and translate on many different properties of the camera. I would like to know what is the difference between them?

Here is the list of rotate and translate methods that act on the LibGDX camera:

  1. camera.translate() , camera.rotate()
  2. camera.view.translate() , camera.view.rotate()
  3. camera.position.traMul(Matrix4 m) , camera.position.rotate()
  4. camera.direction.traMul(Matrix4 m) , camera.direction.rotate()

To my understanding, the camera.view is the actual Frustrum of the camera what can be seen on the screen! What is the difference of rotating(translating) the camera's direction, as compared to rotation(translation) of the camera's view?

What about I just translate or rotate the camera and NOT the view of the camera OR the direction OR the position of the camera? What effect will that have?

I have read the documentation and its really lacking in helping us understand! Please someone to help demystified these camera concepts!

LiBGDX camera drifts far away from modelinstance after translation and rotation

My camera starts in the position I expect. However, after some time it drifts far away from the red modelinstance! How to keep it position right behind the red modelinstance without drifting far away!

Here is how I initially set up my camera:

    //initial set up of my camera:

 Gdx.input.setCursorCatched(true);
    Gdx.input.setCursorPosition(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2);

    camera = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());

 camera.position.set(10f,12f,17.5f);
   
    camera.lookAt(10f,0,10f);        

    camera.up.set(new Vector3(10f,0,10f).Y);
    camera.near = 0.1f;
    camera.far = 300f;     

    camera.update();

Here is how I translate my red model instance: AFTER PRESSING W KEY

BoundingBox bbox0091 = new BoundingBox();
                    ThreeDWithMultipleScreensGame.gameMainPlayerReference.calculateBoundingBox(bbox0091);
                    bbox0091.mul(ThreeDWithMultipleScreensGame.gameMainPlayerReference.transform);
                    Vector3 centerV= new Vector3();
                    bbox0091.getCenter(centerV);

 vecyr.set(0,0,0); //clearing vecyr... important
                    mat4_.set(ThreeDWithMultipleScreensGame.gameMainPlayerReference.transform);
                    vecyr.z-=deltatime*LevelOneScreen.playerSpeed;

                    if(Float.compare(Math.abs(centerV.x-10f),0.001f)>0)
                    vecyr.x-=deltatime*centerV.x;
                   
                    mat4_.translate(vecyr);
                    ThreeDWithMultipleScreensGame.gameMainPlayerReference.transform.set(mat4_);
                    ThreeDWithMultipleScreensGame.gameMainPlayerReference.calculateTransforms();
                    ThreeDWithMultipleScreensGame.gameMainPlayerReference.transform.getTranslation(ThreeDWithMultipleScreensGame.playerCurrentPosition);

Here is how I update my camera hoping that it will follow right behind my red model instance:

camera.up.set(0,1,0);
                 
                    Vector3 tmpVector=new Vector3();
                    camera.position.add(tmpVector.set(camera.direction).scl(deltatime*LevelOneScreen.playerSpeed).x,0,
                            tmpVector.set(camera.direction).scl(deltatime*LevelOneScreen.playerSpeed).z);  
                    camera.lookAt(centerV.x,0,centerV.z-7.5f);
                    camera.update();

Here is the picture that show the drifting effect I am talking about:

picture

Notice how the black line gets longer after some time of rotating and translating the red modelinstance How to fix this problem so camera stays always right behind the red model instance?

Modelinstance rotation breaks apart after translating modelinstance foward in LiBGDX project

The following code rotates my modelinstance about its centerpoint y-axis. HOWEVER, when I move the modelinstance foward the rotation gets all wrong! I am not sure what is happening. I need for the rotation to work the same always NOT just before I start moving the modelinstance foward!

Here how I apply my rotation after pressing the D key:

BoundingBox bbox = new BoundingBox();
                    ThreeDWithMultipleScreensGame.gameMainPlayerReference.calculateBoundingBox(bbox);
                    bbox.mul(/*node_.globalTransform*/ThreeDWithMultipleScreensGame.gameMainPlayerReference.transform);
                    Vector3 centerVector_ = new Vector3();
                    bbox.getCenter(centerVector_);

                    Gdx.app.log("okcenter","here: " + centerVector_.toString());


                    if(true){

                        Matrix4 m4 = new Matrix4();
                        m4.set(ThreeDWithMultipleScreensGame.gameMainPlayerReference.transform);
                        //m4.translate(10,0,10).rotate(0,1,0,-20f*LevelOneScreen.playerRotationSpeed*deltatime).translate(-10,0,-10);
                        m4.translate(centerVector_).rotate(0,1,0,-20f*LevelOneScreen.playerRotationSpeed*deltatime).translate(-1f*centerVector_.x,-1f*centerVector_.y,-1f*centerVector_.z);
                        Gdx.app.log("multiply","we have: " + centerVector_.cpy().scl(-1f).toString());
                        ThreeDWithMultipleScreensGame.gameMainPlayerReference.transform.set(m4);
                        ThreeDWithMultipleScreensGame.gameMainPlayerReference.calculateTransforms();

                    }

And, here is how I translate my modelinstance foward:

vecyr.set(0,0,0); //clearing vecyr... important
                    mat4_.set(ThreeDWithMultipleScreensGame.gameMainPlayerReference.transform);
                    vecyr.z-=deltatime*LevelOneScreen.playerSpeed;
                    mat4_.translate(vecyr);
                    ThreeDWithMultipleScreensGame.gameMainPlayerReference.transform.set(mat4_);
                    ThreeDWithMultipleScreensGame.gameMainPlayerReference.calculateTransforms();
                    ThreeDWithMultipleScreensGame.gameMainPlayerReference.transform.getTranslation(ThreeDWithMultipleScreensGame.playerCurrentPosition);


camera.position.add(vecyr);
                    
camera.lookAt(10f,0,ThreeDWithMultipleScreensGame.playerCurrentPosition.z-7.5f);
                    camera.update();

Why does the rotation only work before I start moving my modelinstance foward?

Rotate modelinstance node about its own centerpoint y axis in LiBGDX

I am trying to rotate the node of a modelinstance as follows:

Note: the node and modelinstance are rotating BUT not about their own center Y axis!

 Node node_ = myModelInstance.getNode("boxy", true);

                    BoundingBox bbox = new BoundingBox();
                    myModelInstance.calculateBoundingBox(bbox);
                    bbox.mul(node_.globalTransform/*myModelInstance.transform*/);
                    Vector3 centerVector_ = new Vector3();
                    bbox.getCenter(centerVector_);

                    if (true) {
                        try {
                           
                            if (node_ != null) {
                                
                                Gdx.app.log("information", "Before rotation: " + node_.localTransform.toString());

                                // Extract the local Y-axis and create a rotation matrix
                                //Vector3 yAxis = new Vector3(0, centerVector_.Y, 0);

                                float rotationAngle = MathUtils.degreesToRadians * 45;
                                       
                                Gdx.app.log("information", "Rotation angle: " + rotationAngle);


                                // Set rotation matrix based on the Y-axis and angle
                                rotationMatrix.setToRotation(centerVector_.Y/*yAxis*/, rotationAngle);

                                // Log the rotation matrix
                                Gdx.app.log("information", "Rotation matrix: " + rotationMatrix.toString());

                                // Apply the rotation to the node's local transform
                                node_.globalTransform/*localTransform*/.mulLeft(rotationMatrix);
                               // node_.globalTransform.getRotation(new Quaternion(),true);
                                node_.calculateLocalTransform();

                                //myModelInstance.transform.set(node.localTransform);

                               // myModelInstance.transform.set(node.localTransform.mulLeft(rotationMatrix));


                                // Log the local transform after applying rotation
                                Gdx.app.log("information", "After rotation: " + node_.localTransform.toString());

                                // Recalculate the transforms to update the hierarchy
                                //myModelInstance.calculateTransforms();

                                Gdx.app.log("error44", "Rotation applied successfully.");
                            } else {
                                Gdx.app.log("error44", "Node 'boxy' not found.");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Gdx.app.log("error44", "Exception: " + e.toString());
                        }
                    }

I need the modelinstance and its node to rotate about the Y axis of the centerpoint of the modelinstance! How to do this??

Here is a picture of the redbox modelinstance that is supposed to rotate in place about its own y axis.. we can say the normal to the top face!

enter image description here

Libgdx modelinstance rotates about some imaginary circle circumference. NOT its own center y axis! [duplicate]

So confused about how rotation works based on local y axis of modelinstance:

This how I create the modelinstance:

 //create a red box:
            ModelBuilder mBuilder = new ModelBuilder();
            mBuilder.begin();
            Material mat = new Material();
            mat.set(PBRColorAttribute.createBaseColorFactor(Color.RED));
            MeshPartBuilder mpartbuilder = mBuilder.part("boxy", GL20.GL_TRIANGLES, VertexAttributes.Usage.Position|VertexAttributes.Usage.Normal,mat);
            BoxShapeBuilder.build(mpartbuilder,10f,0,10f,2f,2f,5f);
            ModelInstance mInstance = new ModelInstance(mBuilder.end());

From code above I can see that modelinstance center is at 10f, 0, 10f.

I create the camera as such: viewing down on the modelinstance:

camera = new PerspectiveCamera(67, Gdx.graphics.getWidth(), 
Gdx.graphics.getHeight());
camera.position.set(10f,10f,17.5f);
camera.lookAt(10f,0,10f);  //so its looking at the center of 
modelinstance

//so, the up is the Y value of the center point of the modelinstance!
// I did also try:  Vector3.Y 
camera.up.set(new Vector3(10f,0,10f).Y); 
    camera.near = 0.1f;
    camera.far = 300f;

camera.update();

I also try to rotate the modelinstance as such:

if(Gdx.input.isKeyPressed(Input.Keys.B)){

        if(true) {
            camera.lookAt(10f,0f,10f);
            Gdx.app.log("rotating", "see");
            Matrix4 mat41 = new Matrix4();
            mat41.set(ThreeDWithMultipleScreensGame.gameMainPlayerReference.transform);
            //mat41.rotate(new Vector3(10f,0,10f),new Vector3(0,1f,0));
            mat41.rotate(camera.up.Y, 10f * delta);
            //mat41.setToRotation()
            ThreeDWithMultipleScreensGame.gameMainPlayerReference.transform.set(mat41);
            ThreeDWithMultipleScreensGame.gameMainPlayerReference.transform.getTranslation(ThreeDWithMultipleScreensGame.playerCurrentPosition);

            camera.update();
           
        }

        if(false)
        try{
            ThreeDWithMultipleScreensGame.gameMainPlayerReference.transform.rotate(new Vector3(10f,0,10f).Y,20f);
            camera.lookAt(10f,0,10f);
            camera.update();
        } catch (Exception e) {
            e.printStackTrace();
            Gdx.app.log("the_error","see: " + e.toString());
        }
    }

Both ways of rotating make the modelinstance rotate NOT about its center! It follows the path of an imaginary circle that is centered who knows where!

libGDX using Stage and Actor produces different camera angles on desktop and Android Phone

libGDX using Stage and Actor produces different camera angles on desktop and Android Phone.

Here are pictures demonstrating the problem: http://brandonyuh.minus.com/mFpdTSgN17VUq

On the desktop version, the image takes up most all the screen. On the Android phone it only takes up a bit of the screen.

Here's the code (not my actual project but I isolated the problem):

package com.me.mygdxgame2;
import com.badlogic.gdx.*;
import com.badlogic.gdx.graphics.*;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.*;
import com.badlogic.gdx.scenes.scene2d.*;
public class MyGdxGame2 implements ApplicationListener {
    private Stage stage;
    public void create() {
        stage = new Stage();
        stage.addActor(new ActorHi());
    }
    public void render() {
        Gdx.gl.glClearColor(0, 1, 0, 1);
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
        stage.draw();
    }
    public void dispose() {}
    public void resize(int width, int height) {}
    public void pause() {}
    public void resume() {}
    public class ActorHi extends Actor {
        private Sprite sprite;
        public ActorHi() {
            Texture texture = new Texture(Gdx.files.internal("data/hi.png"));
            texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
            sprite = new Sprite(new TextureRegion(texture, 0, 0, 128, 128));
            sprite.setBounds(0, 0, 300.0f, 300.0f);
        }
        public void draw(SpriteBatch batch, float parentAlpha) {
            sprite.draw(batch);
        }
    }
}

Why does this happen?

  • ✇Recent Questions - Game Development Stack Exchange
  • Scene2d Stage Actor setup issuesrrd
    I am creating a game using libgdx. In the same each level has a class. I have stage as a member variable of the class. To this stage, I add actors. Inside the levels class, I have attaced the input processor to the stage like below. stage = new Stage(); sviewPort = new StretchViewport(OSR_Constants.VIEWPORT_WIDTH, OSR_Constants.VIEWPORT_HEIGHT); OrthographicCamera camera = new OrthographicCamera(OSR_Constants.VIEWPORT_WIDTH, OSR_Constants.VIEWPORT_HEIGHT); camera.position.set(0, 0, 0); camer
     

Scene2d Stage Actor setup issues

I am creating a game using libgdx.

In the same each level has a class. I have stage as a member variable of the class. To this stage, I add actors.

Inside the levels class, I have attaced the input processor to the stage like below.

stage = new Stage();
sviewPort = new StretchViewport(OSR_Constants.VIEWPORT_WIDTH, OSR_Constants.VIEWPORT_HEIGHT);
OrthographicCamera camera = new OrthographicCamera(OSR_Constants.VIEWPORT_WIDTH, OSR_Constants.VIEWPORT_HEIGHT);
camera.position.set(0, 0, 0);
camera.update();
sviewPort.setCamera(camera);
stage.setViewport(sviewPort);

Gdx.input.setInputProcessor(stage); 

The level object is instantiated in another class known as GameScreen. GameScreen implements the Screen interface.

I am unable to detect touch events on my actors in the stage. Each actor has also been given bounds as per the world coordinates. I have added the following code on each actor to detect touch

this.addListener(new InputListener(){
     public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
          System.out.println("touchdown at " + x + " " + y);
          return true;
      }
  });
  • ✇Recent Questions - Game Development Stack Exchange
  • Resize font when screen resizes desktop LibgdxAndy
    I create my font using the following code: public BitmapFont createFont(FreeTypeFontGenerator ftfg, float dp) { FreeTypeFontParameter f = new FreeTypeFontParameter(); f.size = (int)(dp * Gdx.graphics.getDensity()); f.color = Color.BLACK; f.minFilter = Texture.TextureFilter.Nearest; f.magFilter = Texture.TextureFilter.MipMapLinearNearest; ftfg.scaleForPixelHeight((int)(dp * Gdx.graphics.getDensity())); return ftfg.generateFont(f); } myFont = createFont(new FreeTypeFo
     

Resize font when screen resizes desktop Libgdx

I create my font using the following code:

public BitmapFont createFont(FreeTypeFontGenerator ftfg, float dp)
{
    FreeTypeFontParameter f = new FreeTypeFontParameter();
    f.size = (int)(dp * Gdx.graphics.getDensity());
    f.color = Color.BLACK;
    f.minFilter = Texture.TextureFilter.Nearest;
    f.magFilter = Texture.TextureFilter.MipMapLinearNearest;
    ftfg.scaleForPixelHeight((int)(dp * Gdx.graphics.getDensity()));
    return ftfg.generateFont(f);
}

myFont = createFont(new FreeTypeFontGenerator(Gdx.files.internal("Fonts/Roboto-Black.ttf")), 16);

I have some labels to which I set the font using:

Label myLabel= new Label("Text", uiSkin);
        myLabel.setWrap(true);
        myLabel.getStyle().font = myFont;

How I create the stage:

Stage collectionStage = new Stage(new StretchViewport(Gdx.graphics.getWidth(), Gdx.graphics.getWidth()));

I also tried with no viewport or with other viewports.

In my resize method:

public void resize(int width, int height) {
    Viewport viewport = collectionStage.getViewport();
    viewport.update(width, height, false);
    viewport.apply();
}

The problem is that when I resize the window on Desktop the font gets distorted. Do I have to create another font in the resize method, and then for each label that I have, reassign the new font? Or should I do something else?

  • ✇Recent Questions - Game Development Stack Exchange
  • Libgdx clicklistener of Image Actor not recognising clickCameron
    So I am attempting to make a an image of a closed door for a ship. On clicking this door, it would then change to an open door. However, I am struggling to get the click listener to work for the Image. Weirdly, if i use a textbutton instead it works, with pretty much the same code. Below is the class in which a stage is created and the Image actor added to it. public class battleScreenActorOverlay implements Disposable { public battleScreenActorOverlay(World world, SpriteBatch sb, battleSh
     

Libgdx clicklistener of Image Actor not recognising click

So I am attempting to make a an image of a closed door for a ship. On clicking this door, it would then change to an open door. However, I am struggling to get the click listener to work for the Image. Weirdly, if i use a textbutton instead it works, with pretty much the same code. Below is the class in which a stage is created and the Image actor added to it.

    public class battleScreenActorOverlay implements Disposable {

public battleScreenActorOverlay(World world, SpriteBatch sb, battleShipScreen syst, float bottomButsH, float viewportWidth, float viewportHeight, List<Float> testDoor) {

    viewport = new ExtendViewport(viewportWidth,viewportHeight, new OrthographicCamera());
    stage = new Stage(viewport, sb);
    Gdx.input.setInputProcessor(stage);
    shipObjsAt = new TextureAtlas("batScreen/objects/shipObjects.atlas");
    Skin skin2 = new Skin(shipObjsAt);

    Image img = new Image(skin2.getDrawable("doorV"));
    img.setTouchable(Touchable.enabled);
    img.addListener(new ClickListener() {
        @Override
        public void clicked(InputEvent event, float x, float y) {
            System.out.println("clicked");
        }
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            System.out.println("touch down");
            return true;
        }
        @Override
        public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
            System.out.println("touch up");
        }
    });

    // set Image position and dimensions, then boundaries
    img.setPosition(testDoor.get(2),testDoor.get(3));
    img.setSize(testDoor.get(1)*6, testDoor.get(0)*6);
    System.out.println("gabriel "+img.getX()+" "+img.getY()+" "+img.getWidth()+" "+img.getHeight());
    img.setBounds(img.getX(),img.getY(),img.getWidth(),img.getHeight());

    // add to stage which is then rendered in main class
    stage.addActor(img);
    stage.act();
}

Then the main class basically does some stuff like this:

public class battleShipScreen implements Screen {

// a load of variable declarations here

public battleShipScreen(MyGdxGame game){

    // create viewport etc

    genShip();

}

public void genShip(){
    // basically method for setting door positions
    batScreenActs = new battleScreenActorOverlay(world,game.batch,this,margin,gameport.getWorldWidth(),gameport.getWorldHeight(),testDoor); // calls class which creates stage and adds door

}

@Override
public void show() {

}

public void update(float dt){
    world.step(1/60f,6,2);
    handleInput(dt);
    gamecam.update();
    renderer.setView(gamecam);

}

public void handleInput(float dt) {
 // classic handle input
}

@Override
public void render(float delta) {

    update(delta);
    Gdx.gl.glClearColor((float) 60/255, (float) 181/255, (float) 0/255, (float) 0);    // clears screen
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);                       // clears screen
    // render game map
    renderer.render();
    game.batch.setProjectionMatrix(gamecam.combined);

    game.batch.setProjectionMatrix(batScreenHUD.stage.getCamera().combined);


   game.batch.setProjectionMatrix(batScreenActs.stage.getCamera().combined);
    batScreenActs.stage.act(Gdx.graphics.getDeltaTime());
    batScreenActs.stage.draw();
}


@Override
public void resize(int width, int height) {
    System.out.println("resizing "+height+" by "+width);
    gameport.update(width,height);
    gamecam.update();
}

@Override
public void pause() {

}

@Override
public void resume() {

}

@Override
public void hide() {

}

@Override
public void dispose() {

}

Sorry for the long post, but I have been trying to sort this out for a few days now and have literally no idea what i am doing wrong. Any help working out how to make an Image actor click listener work would be much appreciated!

❌
❌