Moving a Sprite using a Scene2d button - java

I am creating an Android Game using LibGdx. It is a platformer and the map is tiled based. To test the movements of the player I used Key inputs and the desktop version of the game works fine. I created some buttons in scene2d and added them as an actor to the scene so that the game has movement buttons when played on Android devices. The buttons work as "System.out.print" shows. Problem is: the buttons and the player are each created in a different class. I can't seem to modify the velocity (and so the movement) of the Player from the class that holds the buttons. For that I need to change the velocity and speed etc. to static, which gives me strange errors on an Android device (Player won't show, or disappears after a frame). I am not sure how to fix this and what is the actual cause of this error. Here is some of the code of the different Classes:
Main Class (MyGdxGame) only included one button as an example.
public class MyGdxGame extends Game implements ApplicationListener {
private Skin skin;
private Stage stage;
#Override
public void create() {
setScreen(new Play());
skin = new Skin(Gdx.files.internal("ui/defaultskin.json"));
stage = new Stage();
Gdx.input.setInputProcessor(stage);
//Button Right
TextButton buttonRight = new TextButton("Right", skin, "default");
buttonRight.setWidth(50f);
buttonRight.setHeight(50f);
buttonRight.setPosition(Gdx.graphics.getWidth() /2 - 250f, Gdx.graphics.getHeight()/2 - 200f);
buttonRight.addListener(new ClickListener(){
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
System.out.println("Hold");
return true;
}
public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
System.out.print("Released");
}
});
stage.addActor(buttonRight);
}
Play Class
public class Play implements Screen {
private TiledMap map;
private OrthogonalTiledMapRenderer renderer;
private OrthographicCamera camera;
private Player player;
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.position.set(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2, 0);
camera.update();
renderer.setView(camera);
renderer.render();
renderer.getSpriteBatch().begin();
player.draw(renderer.getSpriteBatch());
renderer.getSpriteBatch().end();
}
#Override
public void resize(int width, int height) {
camera.viewportWidth = width;
camera.viewportHeight = height;
}
#Override
public void show() {
map = new TmxMapLoader().load("maps/map.tmx");
renderer = new OrthogonalTiledMapRenderer(map);
camera = new OrthographicCamera();
player = new Player(new Sprite(new Texture("data/jack2.png")), (TiledMapTileLayer) map.getLayers().get(0));
player.setPosition(2 * player.getCollisionLayer().getTileWidth(), 10 * player.getCollisionLayer().getTileHeight());
}
Player Class
public class Player extends Sprite implements InputProcessor{
// the movement velocity //
public Vector2 velocity = new Vector2();
public float speed = 60 * 2, gravity = 60 * 1.8f;
private boolean canJump;
private TiledMapTileLayer collisionLayer;
private String blockedKey = "blocked";
public Player(Sprite sprite, TiledMapTileLayer collisionLayer){
super(sprite);
this.collisionLayer = collisionLayer;
}
#Override
public void draw(SpriteBatch spriteBatch) {
update(Gdx.graphics.getDeltaTime());
super.draw(spriteBatch);
}
So the button has a working ClickListener, but I don't know how it can modify the players velocity. Any help is welcome.

You just need to have some way to access that player instance from the class containing the button. In my games I make a static World class which can be accessed from anywhere in the program. Through the world class I can access the player instance. That's just how I do it, you may find another way. You say your program has errors on android device when making certain parameters static? Do you mean it compiles but it just doesn't work the way you expect? If that's the case, there is probably just a bug in how you're modifying the position or velocity of the player.

Related

Libgdx Software Design

I am building a libgdx game, and I am not sure what tools are available right now.I have a folder with actors and I do all the logic inside those actors, but I have to add them manually to the stage, is there any way I can load all those actors at once.
public class ConfigureUI extends Stage {
private RuvikEngine ruvikEngine;
private OrthographicCamera camera;
public ConfigureUI(ScreenViewport viewport, RuvikEngine engine, OrthographicCamera camera) {
super(viewport);
this.ruvikEngine = engine;
this.camera = camera;
configure();
}
private void configure() {
//TODO make a scalable UI class system,so we can load each UI component independently
TextureActor actor = new TextureActor("move.png");
TextureActor reset = new TextureActor("reset.jpg");
Image image = new Image(actor.texture);
Image resetimg = new Image(reset.texture);
image.setPosition(225, 0);
this.addActor(image);
this.addActor(resetimg);
image.addListener(new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
GameUIState.getInstance().setPAN_MODE(!GameUIState.getInstance().isPAN_MODE());
super.clicked(event, x, y);
}
});
resetimg.addListener(new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
ruvikEngine.clearBodyArray();
ruvikEngine.addBody(new Body(new Vector2(1920 / 2, 1080 / 2), new Vector2(0, 0), 1000));
camera.position.set(GameUIState.getInstance().width / 2, GameUIState.getInstance().height / 2, 0);
camera.zoom = 0.1f;
camera.update();
super.clicked(event, x, y);
}
});
}
}```
If you are looking for a Visual Editor like unity. Sorry but libgGdx doesn't have one.
But if you want some framework to make your game more easily.
You can take a look to Autumn Mvc a spring like framework you will permit you to make your game menu rapidly.
And who will add Ioc to your stack. Who can simplify your code greatly
I never use it myself because i don't need it but this can be a good solution.

How to manipulate characters and objects in LibGDX

I am new to programming in LibGDX and I'm currently working on a simple arcade game. And I would like to know how should I properly create a main character who just has to run and jump? Should I create a new class for him and implement some method? As for now, I have only two classes, MyGame where I handle the other game states and PlayState where I draw the background and objects.
Just create a Sprite, you can control it easily.
SpriteBatch batch;
Sprite sprite;//Main character
#Override
public void create(){
batch = new SpriteBatch();
sprite = new Sprite(new Texture(Gdx.files.internal("data/text.png")));
}
#Override
public void render(){
//Add logic to control the main character...
batch.begin();
sprite.draw(batch);
batch.end();
}
If you want to create more methods you could try extending the Actor class too, this way it can be reused.
public class MyActor extends Actor{
Texture texture = new Texture(Gdx.files.internal("data/tex.png"));
float actorX = 0, actorY = 0;
public MyActor(){
addListener(new InputListener(){//Receive events
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button){//Check your run and jump buttons
//...
}
}
#Override
public void draw(Batch batch, float alpha){//Draw it
batch.draw(texture,actorX,actorY);
}
#Override
public void act(float delta){//Update it
}
}

Libgdx reducing calls and optimize the game

Am trying to reduce number of calls being made everytime a Screen is called on my game in a bid to make my game faster and I noticed I do alot the same calculation on every screen..how can i avoid this?
I do this in practically every screen
public class ****Screen implements Screen {
#Override
public void show() {
float screenWidth = Gdx.graphics.getWidth();
float screenHeight = Gdx.graphics.getHeight();
float gameWidth = 360;
float gameHeight = screenHeight / (screenWidth / gameWidth);
midPointY = (int) (gameHeight / 2);
cam = new OrthographicCamera();
cam.setToOrtho(true, gameWidth, gameHeight);
viewport = new FitViewport(gameWidth, gameHeight, cam);
viewport.apply();
stage = new Stage(viewport);
Gdx.input.setInputProcessor(stage);
yet I have a GameClass..How can I implement the above in my gameclass(below) and only have to call it once?...
public class Start extends Game {
#Override
public void create() {
float screenWidth = Gdx.graphics.getWidth();
float screenHeight = Gdx.graphics.getHeight();
float gameWidth = 360;
float gameHeight = screenHeight / (screenWidth / gameWidth);
assets = new AssetLoader();
assetManager = new AssetManager();
camera = new OrthographicCamera();
camera.setToOrtho(true, gameWidth, gameHeight);
//initialize screens here
mainMenu = new MenuScreen(this);
loadingScreen = new LoadingScreen(this);
gameScreen = new GameScreen(this);
.......
//call assets
AssetLoader.load();
//start mainmenu...
this.setScreen(mainMenu);
}
First i have to tell you actualy this wont speed up your game.
If you change screen every 20 seconds then that means game does calculations 1 frame per 1200 frames.
However i am same like you and really looking for most optimize ways while doing game.
I found a solution for this case.
You can pass objects that you use in all screens, from game class to screen class.
Screen class
public class MainMenuScreen implements Screen {
public MainMenuScreen(OrthographicCamera camera) {
this.camera=camera;
}
//...Rest of class omitted for succinctness.
}
Game class
public class Starts extends Game {
OrthographicCamera camera;
public void create() {
camera=new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
this.setScreen(new MainMenuScreen(camera));// change screen and pass camera to new screen.
}
}
Or you can even pass the whole game class like this.
public class MainMenuScreen implements Screen {
final Starts game;
public MainMenuScreen(final Starts game) {
this.game = game;
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0.2f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
game.camera.update();
game.batch.setProjectionMatrix(game.camera.combined);
game.batch.begin();
game.font.draw(...);
game.font.draw(...);
game.batch.end();
if (Gdx.input.isTouched()) {
game.setScreen(new AnotherScreen(game));
dispose();
}
}
}
just need to call like this in game class. So you can use stage batches fonts etc. of game in all screens.
this.setScreen(new MainMenuScreen(this));
I assume you mean you want to shorten the little hiccup you get when switching screens. (Your game's frame rate is not affected by this.)
Easy way: move that code from show to the constructor of each screen class.
However, it is wasteful to be creating a new Stage for each Screen without passing it a SpriteBatch, because you are essentially instantiating three separate SpriteBatches, which are heavy objects (they have a big array for the mesh data, a big mesh on the GPU, and have to compile a shader).
You can instantiate shared objects in your Game class and pass them into the constructors of your Screens like this:
public class Start extends Game {
SpriteBatch spriteBatch;
#Override
public void create() {
//...
//initialize screens here
spriteBatch = new SpriteBatch(); //must be disposed in dispose()
mainMenu = new MenuScreen(this, spriteBatch);
loadingScreen = new LoadingScreen(this, spriteBatch);
gameScreen = new GameScreen(this, spriteBatch);
//...
}
}
Update your Screens' constructors accordingly and pass the sprite batch into the stage constructors. Viewports and cameras are lightweight, so I wouldn't bother with moving those up to the Game class unless it helps make your code more maintainable.
By the way, you're kind of abusing FitViewport by pre-calculating the aspect ratio. The point of Viewports is that you don't need to calculate anything when setting up. Use new ExtendViewport(360, 1, cam) to get the same thing you're doing without the calculations. And make sure you're updating it in resize().

How to extend Actor and draw it on stage? Libgdx

I am trying to make an object that extends the Actor class. but whenever I have call the Stage's draw() method, it only draws the button I added to it. Here is my code, maybe someone here can help me?
Code for my Screen class (Assume that I had overridden all necessary methods and that I imported all necessary classes):
public class PlayScreen implements Screen{
SpriteBatch batch;
Game game;
Table table;
Skin skin;
Stage stage;
BitmapFont font;
TextButton button;
TextDisplay display;
public PlayScreen(MyGdxGame game, SpriteBatch batch){
this.game = game;
this.batch = batch;
//instantiating Stage, Table, BitmapFont, and Skin objects.
font = new BitmapFont(Gdx.files.internal("MyTruefont.fnt"));
table = new Table();
stage = new Stage();
skin = new Skin(Gdx.files.internal("Test.json"));
button = new TextButton("Start!", skin, "default");
display = new TextDisplay(font, this);
//Setting table properties
table.setWidth(stage.getWidth());
table.align(Align.center|Align.top);
table.setPosition(0, Gdx.graphics.getHeight());
table.padTop(30);
//Adding actors to table
table.add(button).padBottom(50);
table.add(display);
//Adding table to stage and setting stage as the input processor
stage.addActor(table);
Gdx.input.setInputProcessor(stage);
}
#Override
public void show() {
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
stage.draw();
batch.end();
}
And here is My Textdisplay class that extends Actor (Again assume all other methods have been overriden, and all necessary classes have been imported):
public class TextDisplay extends Actor implements Drawable {
Texture texture;
BitmapFont font;
String str;
public TextDisplay(BitmapFont font, Screen screen){
this.font = font;
texture = new Texture(Gdx.files.internal("TextArea.png"));
str = "";
setLeftWidth(texture.getWidth());
setRightWidth(texture.getWidth());
setBottomHeight(texture.getHeight());
setTopHeight(texture.getHeight());
}
#Override
public void draw(Batch batch, float x, float y, float width, float height) {
batch.draw(texture, x, y);
}
You overrode the wrong draw method. Actor's draw method signature is:
public void draw (Batch batch, float parentAlpha)
You overrode the one from Drawable. Not sure why you're implementing Drawable. There's already an Actor available for drawing text anyway, called Label.
Also, if you want to put your Actor in a table, you need to set its width and height, or the width and height of its cell in the table.

Why doesn't my coordinate system reflect the standard coordinate axis that I requested for?(LibGdx)

Basically, I want my coordinate system to have (0,0) as the top left corner of the screen(used to this in Swing and Android Canvas drawing).
I saw a great thread for doing so Changing the Coordinate System in LibGDX (Java). I used the code that the creator provided but the rectangle I am drawing is still at the bottom of the screen.(screenshot)
Here is my code for drawing the rectangle(I use one class, GameWorld, to manage all the "game objects" and another class, GameRenderer to render all the game objects) Both classes have a method that will be called from the GameScreen's render method.
Relevant code in GameScreen.java
public class GameScreen implements Screen {
//manage game objects
private GameWorld world;
//render game objects
private GameRenderer renderer;
public GameScreen() {
world = new GameWorld();
renderer = new GameRenderer(world);
}
public void render(float delta) {
world.update(delta);
renderer.render();
}
.....
}
And in GameWorld.java
public class GameWorld {
private Rectangle rectangle;
public GameWorld() {
rectangle = new Rectangle(0, 0, 17, 12);
}
public void update(float delta) {
rectangle.setX(rectangle.getX() + 1);
if(rectangle.getX() > Gdx.graphics.getWidth()) {
rectangle.setX(0);
}
}
public Rectangle getRect() {
return rectangle;
}
}
And in GameRenderer.java
public class GameRenderer {
private ShapeRenderer shapeRenderer;
private OrthographicCamera cam;
private GameWorld myWorld;
public GameRenderer(GameWorld theWorld) {
myWorld = theWorld;
cam = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.setToOrtho(true, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
}
public void render() {
shapeRenderer = new ShapeRenderer();
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
shapeRenderer.setColor(87/255.0f, 109/255.0f, 120/255.0f, 1);
Rectangle toDraw = myWorld.getRect();
shapeRenderer.rect(toDraw.getX(), toDraw.getY(),
toDraw.getWidth(), toDraw.getHeight());
shapeRenderer.end();
}
}
And finally in Desktop.java where I am testing the game,
public class DesktopLauncher {
public static void main (String[] arg) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.title = "My test";
config.width = 272;
config.height = 408;
new LwjglApplication(new MyGdxGame(), config);
}
}
Does anyone see where i am doing wrong? Why is the rectangle still being drawn at the bottom of the screen. I used the provided code from the creator and specified the rectangle's top y coordinate as zero.
You didn't apply your camera's projection to the ShapeRenderer.
Add this line right before shapeRenderer.begin():
shapeRenderer.setProjectionMatrix(cam.combined);
Also, you should move ShapeRenderer's instantiation from render() to the class constructor so you aren't creating a new one on every frame.

Categories