Wrong Color DirectMediaPlayer VLCj and Libgdx - java

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;
}

Related

Box2d collision wont run on collision

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);
...
}

Manipulating pixels in BufferedImage

I wanted to manipulate pixels in a bufferedimage by doing this:
BufferedImage screen = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
int[] pixels = ((DataBufferInt)screen.getRaster().getDataBuffer()).getData();
The problem is: It displays the image but without the right color. There are no errors in the console.
Anyway, here's my main class:
package net.explorer.explorer;
import javax.swing.JFrame;
public class Explorer extends JFrame {
private static final long serialVersionUID = 1L;
public static int WIDTH = 1280;
public static int HEIGHT = 800;
public Explorer() {
super("Explorer");
add(new Game(WIDTH, HEIGHT));
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new Explorer();
}
}
Here's the the Game class:
package net.explorer.explorer;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.util.ArrayList;
import javax.swing.JPanel;
import javax.swing.Timer;
import net.explorer.entities.Entity;
import net.explorer.entities.Player;
import net.explorer.render.ScreenRenderer;
public class Game extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
public int width, height;
public BufferedImage screen;
public int[] pixels;
public ScreenRenderer screenRenderer;
private Timer timer;
public static ArrayList<Entity> entities;
public Player player;
public Game(int width, int height) {
this.width = width;
this.height = height;
setPreferredSize(new Dimension(width, height));
screen = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
pixels = ((DataBufferInt)screen.getRaster().getDataBuffer()).getData();
screenRenderer = new ScreenRenderer(width, height);
timer = new Timer(1, this);
timer.start();
entities = new ArrayList<Entity>();
player = new Player();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.render(g);
}
private void render(Graphics g) {
screenRenderer.renderScreen(screenRenderer);
for(int i = 0; i < width * height; i++) {
screenRenderer.pixels[i] = this.pixels[i];
}
g.drawImage(screen, 0, 0, this);
}
#Override
public void actionPerformed(ActionEvent e) {
repaint();
}
}
And, finally my ScreenRenderer class:
package net.explorer.render;
public class ScreenRenderer {
public int width, height;
public int[] pixels;
public ScreenRenderer(int width, int height) {
this.width = width;
this.height = height;
this.pixels = new int[width * height];
}
public void renderScreen(ScreenRenderer screen) {
for(int i = 0; i < screen.width*screen.height; i++) {
pixels[i] = 0x000000;
}
}
}
The other classes like Player don't matter. Only those 3 classes above do.
You are not writing to the actual BufferedImage raster.
Below is the code which handles that. I have made some other changes as well.
Explorer.java
package image;
import javax.swing.JFrame;
public class Explorer extends JFrame {
private static final long serialVersionUID = 1L;
public static int WIDTH = 400;
public static int HEIGHT = 400;
public Explorer() {
super("Explorer");
add(new Game(WIDTH, HEIGHT));
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new Explorer();
}
}
ScreenRenderer
package image;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.util.Random;
public class ScreenRenderer {
private int width, height;
/*public int[] pixels;*/
private WritableRaster raster;
private int[] pixels;
private Random rand = new Random();
public ScreenRenderer(BufferedImage image) {
/*this.width = width;
this.height = height;*/
//this.pixels = new int[width * height];
this.raster = image.getRaster();
this.width = raster.getWidth();
this.height = raster.getHeight();
pixels = new int[raster.getWidth() * raster.getHeight() * raster.getNumBands()];
System.out.printf("%d %d %d", width, height, pixels.length);
}
public void renderScreen() {
int seed = rand.nextInt();
for (int i = 0; i < pixels.length; i++) {
pixels[i] = i * seed;
}
raster.setPixels(0, 0, width, height, pixels);
}
}
Game.java
package image;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.util.ArrayList;
import javax.swing.JPanel;
import javax.swing.Timer;
/*import net.explorer.entities.Entity;
import net.explorer.entities.Player;
import net.explorer.render.ScreenRenderer;*/
public class Game extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
public int width, height;
public BufferedImage screen;
public int[] pixels;
public ScreenRenderer screenRenderer;
private Timer timer;
/*public static ArrayList<Entity> entities;
public Player player;*/
public Game(int width, int height) {
this.width = width;
this.height = height;
setPreferredSize(new Dimension(width, height));
screen = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
pixels = ((DataBufferInt) screen.getRaster().getDataBuffer()).getData();
screenRenderer = new ScreenRenderer(screen);
timer = new Timer(1, this);
timer.start();
/*entities = new ArrayList<Entity>();
player = new Player();*/
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.render(g);
}
private void render(Graphics g) {
screenRenderer.renderScreen();
/*for (int i = 0; i < width * height; i++) {
screenRenderer.pixels[i] = this.pixels[i];
}*/
g.drawImage(screen, 0, 0, this);
}
#Override
public void actionPerformed(ActionEvent e) {
repaint();
}
}

AutoParrallexBackGround not Working?

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.

Andengine Input Events

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);

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