Box2d collision wont run on collision - java

Contact Collision box2D wont run on collision i want the bullet to be able to run the WorldContactListener beginContact when it begins contact and when it ends contact runningendContact
iv'e looked through a lot of places and i cant get a system print
This is my contact listener class:
package com.mygdx.game;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.Manifold;
public class WorldContactListener implements ContactListener {
#Override
public void beginContact(Contact contact) {
//called when 2 fixtures collide
System.out.println("Begin Contact");
}
#Override
public void endContact(Contact contact) {
//called when the 2 fixtures connected gets split apart
System.out.println("end Contact");
}
#Override
public void preSolve(Contact contact, Manifold oldManifold) {
//gives power to change the characteristics of fixture
collision
}
#Override
public void postSolve(Contact contact, ContactImpulse impulse) {
//gives results of what happened because of collision like
angles ext
}
}
play screen class:
package com.mygdx.game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.maps.MapObject;
import com.badlogic.gdx.maps.objects.RectangleMapObject;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.badlogic.gdx.utils.viewport.ScreenViewport;
import com.badlogic.gdx.utils.viewport.StretchViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.mygdx.game.Sprites.Bullet;
import com.mygdx.game.Sprites.InversePlayer;
import com.mygdx.game.Sprites.Player;
#SuppressWarnings("unused")
public class PlayScreen implements Screen {
private main game;
private TextureAtlas atlas;
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 Player player;
private InversePlayer inversePlayer;
private Bullet bullet;
public PlayScreen(main game) {
atlas = new TextureAtlas("BurningShooterPlayer.pack");
this.game = game;
gamecam = new OrthographicCamera();
gamePort = new FitViewport(main.V_WIDTH / main.PPM, main.V_HEIGHT / main.PPM, gamecam);
hud = new Hud(game.batch);
maploader = new TmxMapLoader();
map = maploader.load("map1.tmx");
renderer = new OrthogonalTiledMapRenderer(map, 1 / main.PPM);
gamecam.position.set(gamePort.getWorldWidth()/2, gamePort.getWorldHeight()/2, 0);
world = new World(new Vector2(0,-10), true);
b2dr = new Box2DDebugRenderer();
new B2WorldCreator(this);
player = new Player(this);
inversePlayer = new InversePlayer(this, .32f, .32f);
bullet = new Bullet(this, .64f, .64f);
}
public TextureAtlas getAtlas() {
return atlas;
}
#Override
public void show() {
//world.setContactListener(ContactListener listener) .
}
public void handleInput(float dt) {
if(Gdx.input.isKeyJustPressed(Input.Keys.W))
player.b2body.applyLinearImpulse(new Vector2(0, 4f), player.b2body.getWorldCenter(), true);
if(Gdx.input.isKeyPressed(Input.Keys.D) && player.b2body.getLinearVelocity().x <= 2)
player.b2body.applyLinearImpulse(new Vector2(0.1f , 0), player.b2body.getWorldCenter(), true);
if(Gdx.input.isKeyPressed(Input.Keys.A) && player.b2body.getLinearVelocity().x >= -2)
player.b2body.applyLinearImpulse(new Vector2(-0.1f , 0), player.b2body.getWorldCenter(), true);
if(Gdx.input.isKeyJustPressed(Input.Keys.RIGHT)) {
bullet.b2body.setLinearVelocity(0, 0);
bullet.b2body.setTransform(new Vector2((float)(player.b2body.getPosition().x+player.getWidth()-(3/main.PPM)), (float)(player.b2body.getPosition().y)), 0);
bullet.b2body.applyLinearImpulse(new Vector2(Bullet.BULLET_SPEED, 0), bullet.b2body.getWorldCenter(), true);
Bullet.Right = true;
}
if(Gdx.input.isKeyJustPressed(Input.Keys.LEFT)) {
bullet.b2body.setLinearVelocity(0, 0);
bullet.b2body.setTransform(new Vector2((float)(player.b2body.getPosition().x-player.getWidth()+(3/main.PPM)), (float)(player.b2body.getPosition().y)), 0);
bullet.b2body.applyLinearImpulse(new Vector2(-Bullet.BULLET_SPEED, 0), bullet.b2body.getWorldCenter(), true);
Bullet.Right = false;
}
//if(Gdx.input.isKeyJustPressed(Input.Keys.SPACE)) {
//bullet.b2body.setBullet(true);
//world.destroyBody(bullet.b2body);
//}
}
public void update(float dt) {
handleInput(dt);
world.step(1/60f, 6, 2);
player.update(dt);
inversePlayer.update(dt);
bullet.update(dt);
gamecam.position.x = player.b2body.getPosition().x;
gamecam.update();
renderer.setView(gamecam);
}
#Override
public void render(float delta) {
update(delta);
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
renderer.render();
b2dr.render(world, gamecam.combined);
game.batch.setProjectionMatrix(gamecam.combined);
game.batch.begin();
player.draw(game.batch);
inversePlayer.draw(game.batch);
bullet.draw(game.batch);
game.batch.end();
game.batch.setProjectionMatrix(hud.stage.getCamera().combined);
hud.stage.draw();
}
#Override
public void resize(int width, int height) {
gamePort.update(width, width);
}
public TiledMap getMap() {
return map;
}
public World getWorld() {
return world;
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
map.dispose();
renderer.dispose();
world.dispose();
b2dr.dispose();
hud.dispose();
}
}
Bullet code (i want to detect if it collides with another body):
package com.mygdx.game.Sprites;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.utils.Array;
import com.mygdx.game.PlayScreen;
import com.mygdx.game.main;
public class Bullet extends projectile{
private float stateTime;
private Animation<TextureRegion> walkAnimation;
private Array<TextureRegion> frames;
public static float BULLET_SPEED = 1f;
public static boolean Right = true;
public Bullet(PlayScreen screen, float x, float y) {
super(screen, x, y);
frames = new Array<TextureRegion>();
frames.add(new TextureRegion(screen.getAtlas().findRegion("BurningShooterPlayer"),111, -1, 15, 8));
walkAnimation = new Animation<TextureRegion>(0.1f, frames);
stateTime = 0;
setBounds(getX(), getY(), (float) (7.5/ main.PPM), 4 / main.PPM);
}
public void update(float dt) {
stateTime += dt;
setPosition((b2body.getPosition().x - getWidth() / 2), b2body.getPosition().y - getHeight() / 2);
setRegion(walkAnimation.getKeyFrame(stateTime, true));
if((!Right) && !walkAnimation.getKeyFrame(dt).isFlipX()) {
walkAnimation.getKeyFrame(dt).flip(true, false);
}
else if((Right) && walkAnimation.getKeyFrame(dt).isFlipX()) {
walkAnimation.getKeyFrame(dt).flip(true, false);
}
}
#Override
protected void defineProjectile() {
BodyDef bdef = new BodyDef();
bdef.position.set(64 / main.PPM, 64 / main.PPM);
bdef.type = BodyDef.BodyType.DynamicBody;
b2body = world.createBody(bdef);
FixtureDef fdef = new FixtureDef();
PolygonShape shape = new PolygonShape();
shape.setAsBox((float) (7.5 / 2 / main.PPM), 4 / 2 / main.PPM);
fdef.filter.categoryBits = main.ENEMY_BIT;
fdef.filter.maskBits = main.GROUND_BIT |
main.ENEMY_BIT |
main.OBJECT_BIT;
fdef.shape = shape;
fdef.density = 100;
b2body.setBullet(true);
b2body.createFixture(fdef);
b2body.setUserData(this);
}
}

You create the World but you forget to set your ContactListener to your world:
private World world;
private WorldContactListener worldContactListener;
public PlayScreen(main game) {
...
world = new World(new Vector2(0,-10), true);
worldContactListener = new WorldContactListener();
world.setContactListener(worldContactListener);
...
}

Related

Why isn't my player falling (gravity) in Eclipse and LibGDX?

I am trying to make my player fall/go down, but he is not. He is just stuck on the map. He can't move. Can you please help?
Here is the code for the Screen. This is where I have all the methods like show, render, resize, pause, resume, hide, etc
package net.hasanbilal.prisonrevelations.screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import net.hasanbilal.prisonrevelations.entities.Player;
public class Play implements Screen {
private TiledMap map;
private OrthogonalTiledMapRenderer otmr;
private OrthographicCamera camera;
private Player porter;
#Override
public void show() {
map = new TmxMapLoader().load("maps/level1.tmx");
otmr = new OrthogonalTiledMapRenderer(map);
camera = new OrthographicCamera();
porter = new Player(new Sprite(new Texture("img/porter.png")));
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
otmr.setView(camera);
otmr.render();
otmr.getBatch().begin();
porter.draw(otmr.getBatch());
otmr.getBatch().end();
}
#Override
public void resize(int width, int height) {
camera.viewportWidth = width;
camera.viewportHeight = height;
camera.update();
}
#Override
public void pause() {
// TODO Auto-generated method stub
}
#Override
public void resume() {
// TODO Auto-generated method stub
}
#Override
public void hide() {
dispose();
}
#Override
public void dispose() {
map.dispose();
otmr.dispose();
}
}
Here is the code for the player
package net.hasanbilal.prisonrevelations.entities;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
public class Player extends Sprite {
/**
* x and y velocity
*/
private Vector2 velocity = new Vector2();
//change 120 to 60*2 if it doesn't work
private float speed = 60 * 2, gravity = 60 * 1.8f;
public Player(Sprite s) {
super(s);
}
public void draw(SpriteBatch sb) {
update(Gdx.graphics.getDeltaTime());
super.draw(sb);
}
private void update(float deltaTime) {
velocity.y -= gravity * deltaTime; //gravity to player
if(velocity.y>speed)
velocity.y = speed;
else if(velocity.y < speed)
velocity.y = -speed;
setX(getX() + velocity.x * deltaTime);
setY(getY() + velocity.y * deltaTime);
}
}
This assignment is due soon! Please help!
Nevermind guys, I fixed it. All I had to do is add porter.update(1);between porter.draw(otmr.getBatch()); and otmr.getBatch().end();

Libgdx the correct way to make a game

Recently I started making my "first" real RPG (The other 'RPG's' were text based in batch or whatever). I am using Libgdx, since from what I read it's pretty simple to get the hang of.
But what I'm interested in is am I doing it right?
For example I make a TiledMap and draw the camera etc. everything 'semi works', but is it right? On one tutorial there was a person which created thread's and much more, so it's making me think I'm doing it wrong
For example this is my GameScreen
public class GameScreen implements Screen, Runnable{
private MenuScreen menuScreen;
SpriteBatch batch, infobatch;
BitmapFont font;
private int tileWidth, tileHeight,
mapWidthInTiles, mapHeightInTiles,
mapWidthInPixels, mapHeightInPixels;
private float delta;
private InputHandler inputHandler;
private TiledMap map;
private AssetManager manager;
private OrthogonalTiledMapRenderer renderer;
private OrthographicCamera camera;
private FitViewport playerViewport;
private Player player;
public GameScreen(MenuScreen mc)
{
menuScreen=mc;
}
#Override
public void show() {
batch = new SpriteBatch();
infobatch = new SpriteBatch();
font = new BitmapFont(Gdx.files.local("font/ornlan.fnt"));
font.setColor(Color.BLACK);
manager = new AssetManager();
manager.setLoader(TiledMap.class, new TmxMapLoader());
manager.load("world/test_1.tmx", TiledMap.class);
manager.finishLoading();
map = manager.get("world/test_1.tmx", TiledMap.class);
MapProperties properties = map.getProperties();
tileWidth = properties.get("tilewidth", Integer.class);
tileHeight = properties.get("tileheight", Integer.class);
mapWidthInTiles = properties.get("width", Integer.class);
mapHeightInTiles = properties.get("height", Integer.class);
mapWidthInPixels = mapWidthInTiles * tileWidth;
mapHeightInPixels = mapHeightInTiles * tileHeight;
camera = new OrthographicCamera(960.f, 720.f);
playerViewport = new FitViewport(mapWidthInTiles, mapHeightInTiles, camera);
camera.position.x = MathUtils.clamp(camera.position.x, camera.viewportWidth / 2, mapWidthInPixels - camera.viewportWidth /2);
camera.position.y = MathUtils.clamp(camera.position.y, camera.viewportHeight / 2, mapHeightInPixels - camera.viewportHeight / 2);
renderer = new OrthogonalTiledMapRenderer(map);
player = new Player();
inputHandler = new InputHandler();
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0.75f, 0.75f, 0.85f, 1);
Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);
camera.position.set(Player.x + Player.width / 2, Player.y + Player.height / 2, 0);
camera.update();
renderer.setView(camera);
renderer.render();
infobatch.begin();
font.draw(infobatch, "Test World, Dev. purposes", 10,25);
font.draw(infobatch, "FPS: " + Gdx.graphics.getFramesPerSecond(), 1180, 700);
infobatch.end();
batch.begin();
batch.setProjectionMatrix(camera.combined);
delta = Gdx.graphics.getDeltaTime();
inputHandler.update();
player.update(delta);
player.render(batch);
batch.end();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
batch.dispose();
infobatch.dispose();
font.dispose();
renderer.dispose();
manager.dispose();
}
#Override
public void run() {
// TODO Auto-generated method stub
}
}
And this is my "MainMenu"
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL30;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import com.badlogic.gdx.utils.viewport.ScreenViewport;
public class MenuScreen extends Game {
SpriteBatch batch;
BitmapFont font;
private Stage stage;
private GameScreen gameScreen;
private Texture btn_start;
private TextureRegion btn_startRegion;
private TextureRegionDrawable btn_startDrawable;
private ImageButton btn_startIB;
#Override
public void create() {
batch = new SpriteBatch();
font = new BitmapFont(Gdx.files.local("font/ornlan.fnt"));
font.setColor(Color.BLACK);
btn_start = new Texture(Gdx.files.internal("ui/start_btn.png"));
btn_startRegion = new TextureRegion(btn_start);
btn_startDrawable = new TextureRegionDrawable(btn_startRegion);
btn_startIB = new ImageButton(btn_startDrawable);
btn_startIB.setPosition(10, 250);
stage = new Stage(new ScreenViewport());
stage.addActor(btn_startIB);
Gdx.input.setInputProcessor(stage);
btn_startIB.addCaptureListener(new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
try {
System.out.println("Starting GameScreen...");
setGameScreen();
} catch (Exception e) {
System.out.println("Error starting GameScreen E:" + e);
}
};
});
}
#Override
public void render() {
Gdx.gl.glClearColor(0.67f, 0.75f, 0.98f, 1);
Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);
batch.begin();
font.getData().setScale(0.8f,0.8f);
font.draw(batch, "Ornlan DevBuild (pa) v0.0.0.1", 1000, 25);
batch.end();
stage.act(Gdx.graphics.getDeltaTime()); // Perform ui logic
stage.draw();
super.render();
}
#Override
public void dispose() {
batch.dispose();
font.dispose();
super.dispose();
}
void setGameScreen() {
gameScreen = new GameScreen(this);
setScreen(gameScreen);
}
}

How to detect collision of player and ground in overlap2d and libgdx

I am following a video tutorial on Youtube called "Making Simple Sidescroller with Overlap2D and libGDX - Tutorial - 003".
I see on video he use raycast to detect collision. But when i try to follow, the player fall through the ground while in the video the player can stop on the ground.
Here is the link to download my libgdx project, and my overlap2d project for you to check.
Here is the code of Player.java
package com.test.superninja;
import com.badlogic.ashley.core.Entity;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.uwsoft.editor.renderer.scripts.IScript;
import com.uwsoft.editor.renderer.components.TransformComponent;
import com.uwsoft.editor.renderer.components.DimensionsComponent;
import com.uwsoft.editor.renderer.utils.ComponentRetriever;
import com.uwsoft.editor.renderer.physics.PhysicsBodyLoader;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.RayCastCallback;
import com.badlogic.gdx.physics.box2d.World;
public class Player implements IScript {
private Entity player;
private TransformComponent transformComponent;
private DimensionsComponent dimensionsComponent;
private Vector2 speed;
private float gravity = -500f;
private float jumpSpeed = 170f;
private World world;
public Player(World world) {
this.world = world;
}
#Override
public void init(Entity entity) {
player = entity;
transformComponent = ComponentRetriever.get(entity, TransformComponent.class);
dimensionsComponent = ComponentRetriever.get(entity, DimensionsComponent.class);
speed = new Vector2(50, 0);
}
#Override
public void act(float delta) {
//transformComponent.scaleY = 0.5;
if (Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
transformComponent.x -= speed.x * delta;
transformComponent.scaleX = -1f;
}
if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
transformComponent.x += speed.x * delta;
transformComponent.scaleX = 1f;
}
if (Gdx.input.isKeyJustPressed(Input.Keys.SPACE)) {
speed.y = jumpSpeed;
}
speed.y += gravity * delta;
transformComponent.y += speed.y * delta;
/*
if (transformComponent.y < 16f){
speed.y = 0;
transformComponent.y = 16f;
}
*/
}
private void rayCast() {
float rayGap = dimensionsComponent.height / 2;
// Ray size is the exact size of the deltaY change we plan for this frame
float raySize = -(speed.y) * Gdx.graphics.getDeltaTime();
//if(raySize < 5f) raySize = 5f;
// only check for collisions when moving down
if (speed.y > 0) return;
// Vectors of ray from middle middle
Vector2 rayFrom = new Vector2((transformComponent.x + dimensionsComponent.width / 2) * PhysicsBodyLoader.getScale(), (transformComponent.y + rayGap) * PhysicsBodyLoader.getScale());
Vector2 rayTo = new Vector2((transformComponent.x + dimensionsComponent.width / 2) * PhysicsBodyLoader.getScale(), (transformComponent.y - raySize) * PhysicsBodyLoader.getScale());
// Cast the ray
world.rayCast(new RayCastCallback() {
#Override
public float reportRayFixture(Fixture fixture, Vector2 point, Vector2 normal, float fraction) {
// Stop the player
speed.y = 0;
// reposition player slightly upper the collision point
transformComponent.y = point.y / PhysicsBodyLoader.getScale() + 0.1f;
return 0;
}
}, rayFrom, rayTo);
}
public float getX() {
return transformComponent.x;
}
public float getY() {
return transformComponent.y;
}
public float getWidth() {
return dimensionsComponent.width;
}
#Override
public void dispose() {
}
}
Here is SuperNinja.java
package com.test.superninja;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.uwsoft.editor.renderer.SceneLoader;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.uwsoft.editor.renderer.utils.ItemWrapper;
import com.uwsoft.editor.renderer.components.additional.ButtonComponent;
import com.badlogic.gdx.graphics.OrthographicCamera;
public class SuperNinja extends ApplicationAdapter {
private SceneLoader sceneLoader;
private Viewport viewport;
private ItemWrapper root;
private Player player;
private UIStage uiStage;
#Override
public void create () {
viewport = new FitViewport(266, 160);
sceneLoader = new SceneLoader();
sceneLoader.loadScene("MainScene", viewport);
root = new ItemWrapper(sceneLoader.getRoot());
player = new Player(sceneLoader.world);
root.getChild("player").addScript(player);
uiStage = new UIStage(sceneLoader.getRm());
}
#Override
public void render () {
Gdx.gl.glClearColor(0.5f, 0.5f, 0.5f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
sceneLoader.getEngine().update(Gdx.graphics.getDeltaTime());
uiStage.act();
uiStage.draw();
((OrthographicCamera)viewport.getCamera()).position.x=player.getX()+player.getWidth()/2f;
}
}
Here is UIStage.java
package com.uwsoft.platformer;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.uwsoft.editor.renderer.data.CompositeItemVO;
import com.uwsoft.editor.renderer.data.ProjectInfoVO;
import com.uwsoft.editor.renderer.resources.IResourceRetriever;
import com.uwsoft.editor.renderer.scene2d.CompositeActor;
/**
* Created by azakhary on 8/5/2015.
*/
public class UIStage extends Stage {
public UIStage(IResourceRetriever ir) {
Gdx.input.setInputProcessor(this);
ProjectInfoVO projectInfo = ir.getProjectVO();
CompositeItemVO menuButtonData = projectInfo.libraryItems.get("menuButton");
CompositeActor buttonActor = new CompositeActor(menuButtonData, ir);
addActor(buttonActor);
buttonActor.setX(getWidth() - buttonActor.getWidth());
buttonActor.setY(getHeight() - buttonActor.getHeight());
buttonActor.addListener(new ClickListener() {
#Override
public void clicked (InputEvent event, float x, float y) {
System.out.println("Hi");
}
});
}
}
With the help of Xeon, I solved my question. I just forgot to call rayCast() function.
I call raycast() function like this:
#Override
public void act(float delta) {
...
rayCast();
}
And it works. Thank you Xeon very much.

Stage and Box2d cameras are not aligned

In my first game I used Scened2d + Box2d rendering my bodies independently without extending Actor. It works, but it is messy and not recommended.
Now in my second game, I would like to do it properly and create a bridge between Scened2d and Box2d by using a physics stage Stage.
I found this code http://pastebin.com/rNpxvT80 what does pretty much what I need. However, the stage and box2d cameras are not aligned even if used mDebugRenderer.render(world, camera.combined) in the Draw() method of my Stage class called GameStage.
I have taken a look on this, but I had no luck libGdx How to use images or actor as body.
I know it may be something simple, but is wrecking my head...
Here is the result:
Here is the full "working" source code:
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
public class Box2D_Platformer extends Game {
public World mBoxWorld;
public Box2DDebugRenderer mDebugRenderer;
public OrthographicCamera mCam;
public AssetManager mManager;
public sprite_actor mBall;
public GameStage stage;
public SpriteBatch batch;
public static final float PIXEL_TO_METER_RATIO_DEFAULT = 32f;
static final float one_over_60 = 1f / 60f;
#Override
public void create() {
init();
batch = new SpriteBatch();
stage = new GameStage();
Gdx.input.setInputProcessor(stage);
stage.setupStage(mCam, mBoxWorld, mDebugRenderer);
stage.addActor(mBall);
}
#Override
public void render() {
stage.act(Math.min(Gdx.graphics.getDeltaTime(), 1 / 30f));
Gdx.gl.glClearColor(0.2f, 0.2f, 0.2f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
render_physics();
stage.draw();
}
#Override
public void dispose() {
stage.dispose();
mManager.dispose();
}
private void init() {
mManager = new AssetManager();
mCam = new OrthographicCamera(1024, 768);
mCam.update();
init_physics();
init_ball();
}
private void init_physics() {
mBoxWorld = new World(new Vector2(0, -200), true);
mDebugRenderer = new Box2DDebugRenderer();
create_static_object_floor();
}
private void init_ball() {
TextureAtlas atlasSprites;
mManager.load("data/atlas.txt",TextureAtlas.class);
mManager.finishLoading();
atlasSprites = mManager.get("data/atlas.txt");
TextureRegion t = atlasSprites.findRegion("bar");
//
mBall = new sprite_actor(mBoxWorld, new Sprite(t));
}
private Body create_dynamic_object_ball() {
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyType.DynamicBody;
bodyDef.position.set(100 / PIXEL_TO_METER_RATIO_DEFAULT,5000 / PIXEL_TO_METER_RATIO_DEFAULT );
Body body = mBoxWorld.createBody(bodyDef);
// Create a circle shape and set its radius to 6
CircleShape circle = new CircleShape();
circle.setRadius(1f*PIXEL_TO_METER_RATIO_DEFAULT);
// Create a fixture definition to apply our shape to
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = circle;
fixtureDef.density = 0.5f;
fixtureDef.friction = 0.4f;
fixtureDef.restitution = 1f; // Make it bounce a little bit
// Create our fixture and attach it to the body
Fixture fixture = body.createFixture(fixtureDef);
circle.dispose();
return body;
}
private Body create_static_object_floor() {
BodyDef groundBodyDef = new BodyDef();
groundBodyDef.position.set(new Vector2(0, 10));
Body groundBody = mBoxWorld.createBody(groundBodyDef);
PolygonShape groundBox = new PolygonShape();
groundBox.setAsBox(mCam.viewportWidth, 10.0f);
groundBody.createFixture(groundBox, 0.0f);
groundBox.dispose();
return groundBody;
}
private void render_physics() {mDebugRenderer.render(mBoxWorld, mCam.combined);}
private float to_world_x(float size) {return size /PIXEL_TO_METER_RATIO_DEFAULT;}
private float to_world_y(float size) {return size /PIXEL_TO_METER_RATIO_DEFAULT;}
private class sprite_actor extends Actor {
private Body mBody = null;
private Sprite mSprite;
public sprite_actor(World world, Sprite sprite) {
this.mSprite = sprite;
create_body();
}
#Override
public void act(float delta) {
super.act(delta);
}
#Override
public void draw(Batch batch, float parentAlpha) {
// TODO Auto-generated method stub
setRotation(MathUtils.radiansToDegrees * mBody.getAngle());
setPosition(to_world_x(mBody.getPosition().x),to_world_y(mBody.getPosition().y));
batch.draw(mSprite, getX(), getY());
System.out.println("("+to_world_x(mBody.getPosition().x)+","+to_world_y(mBody.getPosition().y)+")");
}
private void create_body() {
mBody = create_dynamic_object_ball();
}
}
private class GameStage extends Stage {
private World world;
private OrthographicCamera camera;
public void setupStage(OrthographicCamera cam, World box_world,Box2DDebugRenderer renderer) {
this.world = box_world;
this.camera = cam;
}
#Override
public void act(float step) {
world.step(one_over_60, 6, 2);
super.act(step);
}
#Override
public void draw() {
mDebugRenderer.render(world, camera.combined);
super.draw();
}
}
}

libgdx - How to draw some pixel

I am trying to alter a pixmap and render it, but modified pixels are not shown on screen. I'm not sure if a Pixmap is the best way to do it. Can anyone explain to me where my errors are in the code below ? thanks
package com.me.mygdxgame;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.utils.Array;
public class MyGdxGame implements ApplicationListener {
private OrthographicCamera camera;
private SpriteBatch batch;
private Pixmap _pixmap;
private int _width;
private int _height;
private Texture _pixmapTexture;
private Sprite _pixmapSprite;
private int _x = 0;
private int _y = 0;
#Override
public void create() {
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
camera = new OrthographicCamera(1, h/w);
batch = new SpriteBatch();
_width = (int)Math.round(w);
_height = (int)Math.round(h);
_pixmap = new Pixmap( _width, _height, Format.RGBA8888 );
_pixmap.setColor(Color.RED);
_pixmap.fillRectangle(0, 0, _width, _height);
_pixmapTexture = new Texture(_pixmap, Format.RGB888, false);
}
#Override
public void dispose() {
batch.dispose();
_pixmap.dispose();
_pixmapTexture.dispose();
}
#Override
public void render() {
updatePixMap();
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined);
batch.begin();
batch.draw(_pixmapTexture, -_width/2, -_height/2);
batch.end();
}
private void updatePixMap() {
_x += 1;
if (_x >= _width) {
_x = 0;
}
_y += 1;
if (_y >= _height / 2) {
return;
}
_pixmap = new Pixmap( _width, _height, Format.RGBA8888 );
_pixmap.setColor(Color.CYAN);
_pixmap.drawPixel(_x, _y);
_pixmapTexture = new Texture(_pixmap, Format.RGB888, false);
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
}
You are creating a new pixmap every loop and you don't draw the complete texture in your view.
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.MathUtils;
public class MyGdxGame implements ApplicationListener {
private OrthographicCamera camera;
private SpriteBatch batch;
private Pixmap _pixmap;
private Texture _pixmapTexture;
private int _x = 0;
private int _y = 0;
private float _w;
private float _h;
private int _width;
private int _height;
#Override
public void create() {
_w = Gdx.graphics.getWidth();
_h = Gdx.graphics.getHeight();
_width = MathUtils.round(_w);
_height = MathUtils.round(_h);
camera = new OrthographicCamera(1f, _h / _w);
camera.setToOrtho(false);
batch = new SpriteBatch();
_pixmap = new Pixmap(_width, _height, Format.RGBA8888);
_pixmap.setColor(Color.RED);
_pixmap.fillRectangle(0, 0, _width, _height);
_pixmapTexture = new Texture(_pixmap, Format.RGB888, false);
}
#Override
public void dispose() {
batch.dispose();
_pixmap.dispose();
_pixmapTexture.dispose();
}
#Override
public void pause() {
}
#Override
public void render() {
updatePixMap();
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined);
batch.begin();
batch.draw(_pixmapTexture, 1f / 2f, _h / _w / 2f);
batch.end();
}
#Override
public void resize(final int width, final int height) {
}
#Override
public void resume() {
}
private void updatePixMap() {
_x += 1;
if (_x >= _width) _x = 0;
_y += 1;
if (_y >= _height / 2) return;
_pixmap.setColor(Color.CYAN);
_pixmap.drawPixel(_x, _y);
_pixmapTexture = new Texture(_pixmap, Format.RGB888, false);
}
}
But this is very slow, so why do you want to do it?

Categories