I am trying to implement autoparrallexbackgrounf using andengine 2 for sample. But its not working for me. A still screen appears with player sprite still at centre. Here are my two classes.. can anybody help what i am doing wrong?
package com.example.movingbackground;
import org.andengine.engine.camera.Camera;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.WakeLockOptions;
import org.andengine.engine.options.resolutionpolicy.FillResolutionPolicy;
import org.andengine.entity.scene.Scene;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.ui.activity.SimpleBaseGameActivity;
public class MainActivity extends SimpleBaseGameActivity
{
public Camera mCamera = null;
private static final int width = 480;
private static final int height = 800;
private GamePlay mScene = null;
public EngineOptions onCreateEngineOptions()
{
mCamera = new Camera(0, 0, width, height);
EngineOptions eo = new EngineOptions(true, ScreenOrientation.PORTRAIT_FIXED, new FillResolutionPolicy(), mCamera);
eo.setWakeLockOptions(WakeLockOptions.SCREEN_ON);
return eo;
}
protected void onCreateResources()
{
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
loadRes();
}
private void loadRes()
{
mScene = new GamePlay(this);
}
protected Scene onCreateScene()
{
return mScene;
}
}
Scene Class goes like :
package com.example.movingbackground;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.scene.background.AutoParallaxBackground;
import org.andengine.entity.scene.background.ParallaxBackground.ParallaxEntity;
import org.andengine.entity.sprite.Sprite;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.region.TextureRegion;
public class GamePlay extends Scene
{
private MainActivity mCxt = null;
private Sprite background_1 = null;
private Sprite background_2 = null;
private Sprite background_3 = null;
private AutoParallaxBackground bg = null;
private Sprite player = null;
public GamePlay(MainActivity mCxt)
{
this.mCxt = mCxt;
bg = new AutoParallaxBackground(0.0f, 0.0f, 0.0f, 1f);
background_1 = new Sprite(0, 0, getSpriteRegion(640, 1136, "bg.png"), this.mCxt.getVertexBufferObjectManager());
background_2 = new Sprite(0, 0, getSpriteRegion(640, 1136, "bg.png"), this.mCxt.getVertexBufferObjectManager());
background_3 = new Sprite(0, 0, getSpriteRegion(640, 1136, "bg.png"), this.mCxt.getVertexBufferObjectManager());
player = new Sprite(100, 100, getSpriteRegion(512, 512, "icon.png"), this.mCxt.getVertexBufferObjectManager())
{
#Override
protected void onManagedUpdate(float pSecondsElapsed)
{
// TODO Auto-generated method stub
super.onManagedUpdate(pSecondsElapsed);
player.setX(player.getX()+10);
}
};
attachChilds();
setBackground(bg);
}
private void attachChilds()
{
bg.attachParallaxEntity(new ParallaxEntity(0.0f, background_1, 640, 1136));
bg.attachParallaxEntity(new ParallaxEntity(0.0f, background_2, 640, 1136));
bg.attachParallaxEntity(new ParallaxEntity(0.0f, background_3, 640, 1136));
attachChild(player);
this.mCxt.mCamera.setChaseEntity(player);
}
#Override
protected void onManagedUpdate(float pSecondsElapsed)
{
// TODO Auto-generated method stub
super.onManagedUpdate(pSecondsElapsed);
this.mCxt.mCamera.updateChaseEntity();
}
private TextureRegion getSpriteRegion(int width, int height, String name)
{
BitmapTextureAtlas atlas = new BitmapTextureAtlas(this.mCxt.getTextureManager(), width, height, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
atlas.load();
return BitmapTextureAtlasTextureRegionFactory.createFromAsset(atlas, this.mCxt.getAssets(), name , 0 , 0);
}
}
I only worked with a Parllax Background in andengine right now, but I think the problem is, that you create all your ParallaxEntitys with 0.0f as parallaxFactor. (The first parameter is the parallaxFactor, isn't it?)
I'm not sure, but I think something like
bg.attachParallaxEntity(new ParallaxEntity(5.0f, background_1, 640, 1136));
bg.attachParallaxEntity(new ParallaxEntity(10.0f, background_2, 640, 1136));
bg.attachParallaxEntity(new ParallaxEntity(15.0f, background_3, 640, 1136));
should work.
Related
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);
}
}
so I'm following a tutorial for how to make a 2D game and my button does not, want to go to the place i specify i am going to put the code i have on a separate site as its connected to other classes I've made. but this is the class I'm looking at: MenuState:
package game.dl.gamestates;
import java.awt.Graphics2D;
import game.dl.Managers.MouseManager;
import game.dl.gamestate.GameState;
import game.dl.gamestate.GameStateManager;
import game.dl.gamestate.gameStateButton;
import game.dl.main.Main;
public class MenuState extends GameState {
MouseManager mm;
gameStateButton startGame;
public MenuState(GameStateManager gsm) {
super(gsm);
}
#Override
public void init() {
startGame = new gameStateButton(Main.width / 2, 200, new DungeonLvlLoader(gsm), gsm, "start Game");
mm = new MouseManager();
}
#Override
public void tick(double deltaTime) {
mm.tick();
startGame.tick();
}
#Override
public void render(Graphics2D g) {
startGame.render(g);
mm.render(g);
// g.drawString("TESTING", Main.width, Main.height);
// g.drawString("Hello World!", 150, 200);
g.clipRect(0, 0, Main.width, Main.height);
}
}
this is the GameStateButton.java class:
package game.dl.gamestate;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import game.dl.Managers.MouseManager;
import game.dl.main.Assets;
import game.gos.main.VectorToF;
public class gameStateButton extends Rectangle{
private VectorToF pos = new VectorToF();
private GameState gameState;
private GameStateManager gsm;
// private boolean isClicked;
private boolean isHeldOver;
private int width = 32 *3;
private int height = 32;
private BufferedImage defaultImage;
private String buttonMsg;
public gameStateButton(float xpos, float ypos, GameState gameState, GameStateManager gsm, String buttonMsg) {
this.gameState = gameState;
this.gsm = gsm;
this.pos.xpos = pos.xpos;
this.pos.ypos = pos.ypos;
this.buttonMsg = buttonMsg;
setBounds((int)pos.xpos, (int)pos.ypos, width, height);
defaultImage = Assets.getButton_notHoveredOver();
}
public gameStateButton(float xpos, float ypos, String buttonMsg) {
this.pos.xpos = pos.xpos;
this.pos.ypos = pos.ypos;
this.buttonMsg = buttonMsg;
setBounds((int)pos.xpos, (int)pos.ypos, width, height);
defaultImage = Assets.getButton_notHoveredOver();
}
public void tick(){
setBounds((int)pos.xpos, (int)pos.ypos, width, height);
if(getBounds().contains(MouseManager.mouse)){
isHeldOver = true;
}else{
isHeldOver = false;
}
if(isHeldOver){
if(defaultImage != Assets.getButton_hoveredOver()){
defaultImage = Assets.getButton_hoveredOver();
}
}else{
if(defaultImage != Assets.getButton_notHoveredOver()){
defaultImage = Assets.getButton_notHoveredOver();
}
}
if(gameState != null){
if(isHeldOver){
if(isPressed()){
gsm.states.push(gameState);
isHeldOver = false;
MouseManager.pressed = false;
}
}
}
}
public void render(Graphics2D g){
g.drawImage(defaultImage, (int)pos.xpos, (int)pos.ypos, width, height, null);
g.drawString(buttonMsg, pos.xpos, pos.ypos);
}
// public boolean isClicked(){
// return isClicked;
// }
public boolean isHeldOver(){
return isHeldOver;
}
public boolean isPressed (){
return MouseManager.pressed;
}
}
this is the full code dump:
https://drive.google.com/file/d/0B7JJSxzNdpBrNmdFRTgyVXhRSVU/view?usp=sharing
Your gameStateButton class is initialized as:
startGame = new gameStateButton(Main.width / 2, 200, new DungeonLvlLoader(gsm), gsm, "start Game");
Looking inside your code zip (btw, next time add the gameStateButton.java code here), you have a fixed width of 32*3 pixel and 32 pixel height for the button.
You are setting it at x = Main.width/2, y=200.
You can change those values to be whatever you want.
Now you have not told us what is the actual result (i.e. where it shows now), nor what is the expected result (i.e. where you want it to be), but that line is what is defining its initial position: if it doesn't show there, then something is changing its place. If it doesn't show at all, then probably you are drawing it in the wrong order and it gets overwritten.
So after playing around and looking at my other classes for a while I found the problem. in gameStateButton.java the constructor was pulling the x and y pos from the class fields and not the constructor variable so it should look like this:
public gameStateButton(float xpos, float ypos, GameState gameState, GameStateManager gsm, String buttonMsg) {
this.gameState = gameState;
this.gsm = gsm;
this.pos.xpos = xpos;
this.pos.ypos = ypos;
this.buttonMsg = buttonMsg;
setBounds((int)pos.xpos, (int)pos.ypos, width, height);
defaultImage = Assets.getButton_notHoveredOver();
}
and NOT this:
public gameStateButton(float xpos, float ypos, GameState gameState, GameStateManager gsm, String buttonMsg) {
this.gameState = gameState;
this.gsm = gsm;
this.pos.xpos = pos.xpos;
this.pos.ypos = pos.ypos;
this.buttonMsg = buttonMsg;
setBounds((int)pos.xpos, (int)pos.ypos, width, height);
defaultImage = Assets.getButton_notHoveredOver();
}
I am currently working with libGDX and got to a strange problem.
The textures that I use with batch and rectangles are stretched. Here is a picture.
As you can see, the background looks completely normal, but the person in the middle is a lot taller than the person in the left corner, which it should look like.
Here is my code:
import java.util.Iterator;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
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.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.utils.Array;
import com.data.Manager;
public class GameScreen implements Screen{
private Texture backgroundTexture = Manager.manager.get(("Ressources/Hintergrund_Skizze.png"), Texture.class);
private Texture farmerBackTexture = Manager.manager.get(("Ressources/Farmer_Back_Skizze.png"), Texture.class);
private Texture farmerRightTexture = Manager.manager.get(("Ressources/Farmer_Right_Skizze.png"), Texture.class);
private Texture farmerLeftTexture = Manager.manager.get(("Ressources/Farmer_Left_Skizze.png"), Texture.class);
private Texture ufoTexture = Manager.manager.get(("Ressources/Ufo_Skizze.png"), Texture.class);
private Texture laserTexture = Manager.manager.get(("Ressources/Magic_Ball.png"), Texture.class);
private Image backgroundImage = new Image(backgroundTexture);
private Image farmerBackImage = new Image(farmerBackTexture);
private Stage levelStage = new Stage(), menuStage = new Stage();
private Table menuTable = new Table();
private Skin menuSkin = Manager.menuSkin;
private OrthographicCamera camera;
private SpriteBatch batch;
private Rectangle farmer, ufo;
private Array<Rectangle> lasers;
private boolean ufoMovementLeft = true;
private boolean leftArrow = false;
private boolean rightArrow = false;
private float laserMovement = 0;
private int ufoLife = 15;
#Override
public void show() {
levelStage.addActor(backgroundImage);
levelStage.addActor(farmerBackImage);
Gdx.input.setInputProcessor(levelStage);
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
batch = new SpriteBatch();
farmer = new Rectangle();
farmer.x = 800 / 2 - 80 / 2; farmer.y = 80;
farmer.width = 80; farmer.height = 270;
ufo = new Rectangle();
ufo.x = 800 / 2; ufo.y = 375;
ufo.width = 185; ufo.height = 94;
lasers = new Array<Rectangle>();
}
public void movement() {
if(Gdx.input.isKeyPressed(Keys.LEFT)) leftArrow = true;
if(!Gdx.input.isKeyPressed(Keys.LEFT)) leftArrow = false;
if(Gdx.input.isKeyPressed(Keys.RIGHT)) rightArrow = true;
if(!Gdx.input.isKeyPressed(Keys.RIGHT)) rightArrow = false;
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
levelStage.act();
levelStage.draw();
batch.setProjectionMatrix(camera.combined);
batch.begin();
movement();
if(leftArrow) {if(farmer.x >= 60) farmer.x -= 2; batch.draw(farmerLeftTexture, farmer.x, farmer.y);}
else if(rightArrow) {if(farmer.x <= 590) farmer.x += 2; batch.draw(farmerRightTexture, farmer.x, farmer.y);}
else batch.draw(farmerBackTexture, farmer.x, farmer.y);
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() {
levelStage.dispose(); menuStage.dispose();
menuSkin.dispose();
ufoTexture.dispose();
laserTexture.dispose();
farmerBackTexture.dispose();
farmerRightTexture.dispose();
farmerLeftTexture.dispose();
}}
I hope you are able to help me find the mistake.
Cheers,
Joshflux
EDIT: I am pretty sure, that it has to do something with the size of the window. If I resize the height of the window from 800 to 200, the person in the left corner looks the same, but the person in the middle is way smaller. Still can't figure out how to solve it though...
The problem is that your levelStage uses a different camera.
new Stage();
Creates a stage with its own camera and a scaling viewport. And here you create another camera:
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
Note that this does NOT set the window size!
With a static size, as you never update it when you resize the window.
Since you use a stage for your level you could do this:
batch.setProjectionMatrix(levelStage.getCamera().combined);
If you don't want a scaling viewport create your own (take a look a the different viewports) and add it as an parameter to new Stage(viewport).
To set the window size you need to go to the desktop project and change it in the config class.
That happens because you are adding an actor to a scene and just drawing an texture after. you could use some information about differences of actors and texture drawing here:
libgdx difference between sprite and actor
When to use actors in libgdx? What are cons and pros?
How do you add movement event to the sprite?
I really do not know how to use input events i have checked out tons of different links on this website and the others and none have really helped. I need someone to explain and help me out with this please.
package com.KDevs.test;
import java.util.Random;
import java.util.Vector;
import org.andengine.engine.camera.Camera;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.andengine.entity.modifier.IEntityModifier;
import org.andengine.entity.scene.IOnSceneTouchListener;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.scene.background.Background;
import org.andengine.entity.sprite.Sprite;
import org.andengine.extension.physics.box2d.PhysicsConnector;
import org.andengine.extension.physics.box2d.PhysicsFactory;
import org.andengine.extension.physics.box2d.PhysicsWorld;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.ui.activity.BaseGameActivity;
import android.hardware.SensorManager;
import android.util.Log;
import android.view.MotionEvent;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.FixtureDef;
public class Main extends BaseGameActivity {
Random rand;
Scene scene;
int x , y;
protected static final int CAMERA_WIDTH = 800;
protected static final int CAMERA_HEIGHT = 480;
BitmapTextureAtlas playerTexture;
ITextureRegion playerTexureRegion;
BitmapTextureAtlas blockTexture;
ITextureRegion blockTexureRegion;
BitmapTextureAtlas ZeusTexture;
ITextureRegion ZeusTexureRegion;
PhysicsWorld physicsWorld;
Sprite sPlayer;
Sprite block;
#Override
public EngineOptions onCreateEngineOptions() {
// TODO Auto-generated method stub
Camera mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
EngineOptions options = new EngineOptions(true,
ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(
CAMERA_WIDTH, CAMERA_HEIGHT), mCamera);
return options;
}
#Override
public void onCreateResources(
OnCreateResourcesCallback pOnCreateResourcesCallback)
throws Exception {
// TODO Auto-generated method stub
loadGfx();
// resource
pOnCreateResourcesCallback.onCreateResourcesFinished();
}
private void loadGfx() {
// TODO Auto-generated method stub
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
ZeusTexture = new BitmapTextureAtlas(getTextureManager(), 64, 64);
ZeusTexureRegion = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(ZeusTexture, this, "zeus.png", 0, 0);
ZeusTexture.load();
// width and height power of 2^x
playerTexture = new BitmapTextureAtlas(getTextureManager(), 64, 64);
playerTexureRegion = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(playerTexture, this, "player.png", 0, 0);
playerTexture.load();
blockTexture = new BitmapTextureAtlas(getTextureManager(), 64, 256);
blockTexureRegion = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(blockTexture, this, "block.png", 0, 0);
blockTexture.load();
}
#Override
public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback)
throws Exception {
// TODO Auto-generated method stub
this.scene = new Scene();
this.scene.setBackground(new Background(0, 0, 0));
physicsWorld = new PhysicsWorld(new Vector2(0,SensorManager.GRAVITY_MARS), false);
this.scene.registerUpdateHandler(physicsWorld);
pOnCreateSceneCallback.onCreateSceneFinished(this.scene);
}
#Override
public void onPopulateScene(Scene pScene,
OnPopulateSceneCallback pOnPopulateSceneCallback) throws Exception {
int counter = 0 , timer = 0;
int x2 , y2;
counter++;
x =CAMERA_WIDTH /2;
y = 416;
x2 = 300;
y2= -40;
//if(counter % 100 == 0){
//x++;
//timer++;
//}
rand = new Random();
int area = rand.nextInt(800);
//Player
sPlayer = new Sprite(x, y,
playerTexureRegion, this.mEngine.getVertexBufferObjectManager());
scene.registerTouchArea(sPlayer);
scene.setTouchAreaBindingOnActionDownEnabled(true);
scene.setTouchAreaBindingOnActionMoveEnabled(true);
//Block
block = new Sprite(x2 , y2,
blockTexureRegion, this.mEngine.getVertexBufferObjectManager());
//Zeus Sprite
Sprite zeus = new Sprite(CAMERA_WIDTH/2 , 11,
ZeusTexureRegion, this.mEngine.getVertexBufferObjectManager());
//sPlayer.setRotation(45.0f);
//I knew this shit would be helpful
block.setRotation(90.0f);
FixtureDef PLAYERBlock = PhysicsFactory.createFixtureDef(5.0f, 0.0f, 0.0f);
Body body = PhysicsFactory.createCircleBody(physicsWorld, block, BodyType.DynamicBody, PLAYERBlock);
this.scene.attachChild(sPlayer);
this.scene.attachChild(block);
this.scene.attachChild(zeus);
physicsWorld.registerPhysicsConnector(new PhysicsConnector(block, body,true,false));
pOnPopulateSceneCallback.onPopulateSceneFinished();
}
public boolean onTouchEvent(MotionEvent event) {
if(event.getAction==MotionEvent.ACTION_DOWN){
Log.e("Touching", "Touching the Screen");
}
else if(event.getAction==MotionEvent.ACTION_UP){
Log.e("Touching up", "Touching the Screen up");}
return true;
}
}
First of all I would extend from SimpleBaseGameActivity.
You need to override onAreaTouch method of a sprite object. This way:
Sprite sprite = new Sprite(x, y, texture, this.getVertexBufferObjectManager()) {
public boolean onAreaTouched(org.andengine.input.touch.TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY)
{
//<DO ANYTHING this.setPosition(x,y) method to move the sprite>
this.setPosition(this.getX() + 10 , this.getY() + 10);
return true;
};
};
scene.setTouchAreaBindingOnActionDownEnabled(true);
scene.registerTouchArea(sprite);
I use Libgdx and VLCj to play video, but the color is wrong (the left side on the image is ok).
I use DirectMediaPlayer to catch frame data from the memory, create texture and draw on the screen.
My code:
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.player.MediaPlayerFactory;
import uk.co.caprica.vlcj.player.direct.BufferFormat;
import uk.co.caprica.vlcj.player.direct.BufferFormatCallback;
import uk.co.caprica.vlcj.player.direct.DirectMediaPlayer;
import uk.co.caprica.vlcj.player.direct.RenderCallbackAdapter;
import uk.co.caprica.vlcj.player.direct.format.RV32BufferFormat;
import uk.co.caprica.vlcj.runtime.RuntimeUtil;
import uk.co.caprica.vlcj.runtime.x.LibXUtil;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.Gdx2DPixmap;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
public class MyGdxGame implements ApplicationListener {
private OrthographicCamera camera;
private Texture texture;
private BitmapFont font;
private SpriteBatch batch;
float w = 800;
float h = 600;
private BufferedImage image;
private MediaPlayerFactory factory;
private DirectMediaPlayer mediaPlayer;
private Pixmap pixmap;
#Override
public void create() {
w = Gdx.graphics.getWidth();
h = Gdx.graphics.getHeight();
camera = new OrthographicCamera();
camera.setToOrtho(false, w, h);
camera.update();
font = new BitmapFont();
batch = new SpriteBatch();
LibXUtil.initialise();
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), "C:\\Users\\Dima\\Desktop\\vlc-2.1.0_64\\");
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
image = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration().createCompatibleImage((int) w, (int) h);
image.setAccelerationPriority(1.0f);
String[] args = { "--no-video-title-show", "--verbose=3" };
String media = "C:\\video512.mp4";
factory = new MediaPlayerFactory(args);
mediaPlayer = factory.newDirectMediaPlayer(new TestBufferFormatCallback(), new TestRenderCallback());
mediaPlayer.playMedia(media);
System.out.println(LibVlc.INSTANCE.libvlc_get_version());
}
#Override
public void dispose() {
Gdx.app.exit();
}
#Override
public void render() {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
batch.begin();
if (pixmap != null) {
texture = new Texture(pixmap);
batch.draw(texture, 0, 0, 800, 600);
}
font.draw(batch, "FPS: " + Gdx.graphics.getFramesPerSecond(), 10, 20);
batch.end();
}
private final class TestRenderCallback extends RenderCallbackAdapter {
public TestRenderCallback() {
super(((DataBufferInt) image.getRaster().getDataBuffer()).getData());
}
#Override
public void onDisplay(DirectMediaPlayer mediaPlayer, int[] data) {
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(data.length * 4).order(ByteOrder.nativeOrder());
IntBuffer intBuffer = byteBuffer.asIntBuffer();
intBuffer.put(data);
try {
long[] nativeData = new long[] { 0, 800, 600, Gdx2DPixmap.GDX2D_FORMAT_RGBA8888 };
Gdx2DPixmap pixmapData = new Gdx2DPixmap(byteBuffer, nativeData);
pixmap = new Pixmap(pixmapData);
} catch (Exception e) {
pixmap = null;
throw new GdxRuntimeException("Couldn't load pixmap from image data", e);
}
}
}
private final class TestBufferFormatCallback implements BufferFormatCallback {
#Override
public BufferFormat getBufferFormat(int sourceWidth, int sourceHeight) {
return new RV32BufferFormat((int) w, (int) h);
}
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
}
If you know others ways to draw video in java, let me know.
Solved!
Method getBufferFormat in TestBufferFormatCallback class was not correct. Right variant:
#Override
public BufferFormat getBufferFormat(int sourceWidth, int sourceHeight) {
sourceWidth = 800;
sourceHeight = 600;
System.out.println("Got VideoFormat: " + sourceWidth + "x" + sourceHeight);
BufferFormat format = new BufferFormat("RGBA", sourceWidth, sourceHeight, new int[] { sourceWidth * 4 }, new int[] { sourceHeight });
return format;
}