Render a shape upon mouse click using Libgdx (Android) - android

Is it possible to render a sphere using Libgdx after the user clicks/taps on the screen, at the position chosen by the user? No matter what I try, it doesn't seem to work and either crashes the program or just does nothing.
I'd like a short demo code if possible - thanks!
Here's my entire class. I'm probably doing numerous things wrong :
package com.mygdx.game;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.graphics.FPSLogger;
/**
* See: http://blog.xoppa.com/basic-3d-using-libgdx-2/
* #author Xoppa
*/
public class Render implements ApplicationListener {
public Environment environment;
public PerspectiveCamera cam;
public CameraInputController camController;
public ModelBatch modelBatch;
private FPSLogger fps;
public Model model;
#Override
public void create() {
Gdx.graphics.setContinuousRendering(false);
DataBase.r = this;
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.Specular, 0.4f, 0.4f, 0.4f, 0.6f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, 0f, 0f, -1f));
modelBatch = new ModelBatch();
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(0f, 0f, 10f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
ModelBuilder modelBuilder = new ModelBuilder();
model = modelBuilder.createSphere(1f, 1f, 1f, 30, 30,
new Material(), Usage.Position | Usage.Normal);
ModelInstance instance = new ModelInstance(model);
instance.transform.setToTranslation(1, 1, 1);
ModelInstance instance2 = new ModelInstance(model);
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
DataBase.array.add(instance);
DataBase.array.add (instance2);
Gdx.input.setInputProcessor(new InputAdapter());
if (Gdx.input.justTouched()) {
System.out.println ("yes");
ModelInstance Instance = new ModelInstance (model);
Instance.transform.setToTranslation(Gdx.input.getX(),Gdx.input.getY(), 0);
DataBase.array.add(Instance);
Gdx.graphics.requestRendering();
}
fps = new FPSLogger();
}
#Override
public void render() {
camController.update();
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
modelBatch.begin(cam);
for (ModelInstance instance: DataBase.array) {
modelBatch.render(instance, environment);
}
modelBatch.end();
//fps.log();
}
#Override
public void dispose() {
modelBatch.dispose();
model.dispose();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
}
DataBase.array is just an ArrayList<ModelInstance>.

I don't understand what are you doing there , my style of writing maybe is different, but still I can provide a solution .
I dont suggest to use Touch events and Texture creating on render method.
But for the example :
//defined out of method
//OrthographicCamera cam , Boolean drawBoolean
//Texture texture ,SpriteBatch sb , Vector3 tmp
if (Gdx.input.justTouched()) {
tmp = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
//your camera obj
cam.unproject(tmp);
//Your sphere or rectangle object
texture = new Texture("yourTexture.png");
drawBoolean=true;
}
if(drawBoolean)
//sprite batch , use your render() thing
sb.draw(texture , tmp.x ,tmp.y);
}
I hope you can adapt it to your code.

Related

LibGdx `ShapeRenderer` on Android does not honor alpha channel

I have a program where I am drawing some lines on each frame using ShapeRenderer. On each frame I want to draw on top the previous, faded by a amount, frame.
So what I am doing is first draw a black rectangle with an alpha less than 1 and then draw the current frame. On desktop it works well and the result is something like this
But on Android it does not work. It renders like this.
I tried enabling blending before drawing rectangle
Gdx.gl.glEnable(GL20.GL_BLEND);
Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
Also tried seting the alpha channel to 8 bits in AndroidApplicationConfiguration (config.a = 8)
Nothing of these worked. What else can I try?
Also is there a better way to achieve what I want?
Screen code
package com.waterpaw.trochoids.screen;
import java.util.ArrayList;
import java.util.List;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.utils.viewport.ScreenViewport;
import com.waterpaw.trochoids.Trochoid;
import com.waterpaw.trochoids.Trochoids;
public class GameScreen extends BaseScreen {
private ShapeRenderer sr;
private ScreenViewport viewport;
private List<Trochoid> trochoids = new ArrayList<Trochoid>();
public GameScreen(Trochoids game) {
super(game);
viewport = new ScreenViewport();
Gdx.input.setInputProcessor(this);
sr = new ShapeRenderer();
}
private int resized;
#Override
public void resize(int width, int height) {
viewport.update(width, height);
trochoids.clear();
trochoids.add(new Trochoid(viewport.getWorldWidth(), viewport.getWorldHeight()));
resized = 2;
}
#Override
public void render(float delta) {
if(resized-- > 0) {
Gdx.gl.glClearColor(0f, 0f, 0f, 0f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}
processInput();
if(!trochoids.get(0).isPaused()) {
updateTrochoids();
renderTrochoids();
}
}
private void processInput() {
if(Gdx.input.isKeyJustPressed(Keys.P)) {
if(trochoids.get(0).isPaused()) {
trochoids.get(0).unpause();
} else {
trochoids.get(0).pause();
}
} else if(Gdx.input.isKeyJustPressed(Keys.SPACE)) {
touchDown(0, 0, 0, 0);
}
}
#Override
public void dispose() {
sr.dispose();
}
#Override
public boolean touchDown(int x, int y, int pointer, int button) {
trochoids.get(0).initialize();
return true;
}
public void renderTrochoids() {
sr.setProjectionMatrix(viewport.getCamera().combined);
float w = viewport.getWorldWidth();
float h = viewport.getWorldHeight();
sr.setColor(0, 0, 0, 0.1f);
sr.begin(ShapeRenderer.ShapeType.Filled);
sr.rect(-w / 2, -h / 2, w, h);
sr.end();
sr.begin(ShapeRenderer.ShapeType.Line);
for(int i = 0; i < trochoids.size(); i++) {
trochoids.get(i).render(sr);
}
sr.end();
}
private void updateTrochoids() {
for(int i = 0; i < trochoids.size(); i++) {
trochoids.get(i).update();
}
}
}
LibGDX uses double buffering on Android, so your technique won't work. Draw to a FrameBuffer so you can ensure your previous drawing is not cleared every other frame. Then draw the FrameBuffer's color texture to the screen on every frame.

Camera does not follow player

I use libgdx have one player which moves in x direction from left to right. Now I want the camera to follow it (like in Flappy Bird for example).
What happen is that the player go out off screen when it reaches the right border of screen and the camera don't follow him.
I have tried following options but none of them worked:
camera.position.set(player.getX(), camera.position.y, 0);
camera.position.set(player.getX(), 0, 0);
Vector3 vector3= camera.unproject(new Vector3(player.getX(), 0f, 0f));
player.setX(vector3.x);
I know that this question already exists on SO but none answer works in this case. Maybe I miss something important that i don't know.
The code:
Game.java class
public class Game extends com.badlogic.gdx.Game implements ApplicationListener {
public static Vector2 VIEWPORT = new Vector2(320, 480);
public static int WIDTH;
public static int HEIGHT;
#Override
public void create() {
WIDTH = Gdx.graphics.getWidth();
HEIGHT = Gdx.graphics.getHeight();
// VIEWPORT = new Vector2(WIDTH/2, HEIGHT/2);
VIEWPORT = new Vector2(WIDTH, HEIGHT);
setScreen(new GameScreen(this));
}
#Override
public void resize(int width, int height) {
// TODO Auto-generated method stub
super.resize(width, height);
}
#Override
public void resume() {
}
#Override
public void pause() {
}
}
GameScreen.java class
import android.util.Log;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Color;
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.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.scenes.scene2d.Actor;
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.utils.ChangeListener;
import com.badlogic.gdx.utils.viewport.FitViewport;
import java.util.Collections;
public class GameScreen implements Screen {
private OrthographicCamera camera;
private Player player;
private PlayerInputHandler inputHandler1, inputHandler2;
private Sound sound;
FitViewport viewp;
public static int WIDTH;
public static int HEIGHT;
int width_spacing = 0;
int height_spacing = 0;
Stage stage;
Skin skin;
public GameScreen(Game game) {
stage = new Stage(new FitViewport(Game.WIDTH, Game.HEIGHT));
camera = (OrthographicCamera) stage.getCamera();
Gdx.input.setInputProcessor(stage);
}
#Override
public void show() {
resetGame();
}
public void resetGame() {
WIDTH = Gdx.graphics.getWidth();
HEIGHT = Gdx.graphics.getHeight();
width_spacing = Game.WIDTH / 24;
height_spacing = Game.HEIGHT / 14;
stage.clear();
skin = new Skin(Gdx.files.internal("data2/uiskin.json"));
prepareInputHandlers();
prepare_stage();
}
public void addPlayer() {
Texture texture = new Texture("player.png");
player = new Player(texture);
player.setPosition(Game.WIDTH / 2, Game.HEIGHT * 2 / 3);
stage.addActor(player);
}
#Override
public void resize(int width, int height) {
stage.getViewport().update(width, height, true);
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
if (delta > 1 / 60f) {
player.setX(player.getX() + (4 * delta));
camera.position.set(player.getX(), camera.position.y, 0);
}
update();
stage.act(delta);
stage.draw();
}
private void update() {
camera.update();
}
private void prepareInputHandlers() {
inputHandler2 = new PlayerInputHandler(player, Input.Keys.LEFT, Input.Keys.RIGHT, Input.Keys.UP, Input.Keys.DOWN);
}
#Override
public void dispose() {
sound.dispose();
player.getTexture().dispose();
}
public void prepare_stage() {
addPlayer();
player.setWidth(64);
player.setHeight(64);
}
#Override
public void resume() {
// TODO Auto-generated method stub
}
#Override
public void hide() {
// TODO Auto-generated method stub
}
#Override
public void pause() {
// TODO Auto-generated method stub
}
}
Player.java class
import com.badlogic.gdx.graphics.Texture;
public class Player extends com.badlogic.gdx.scenes.scene2d.ui.Image{
private Texture texture;
public Player(Texture texture) {
super(texture);
}
public Texture getTexture() {
return texture;
}
#Override
public void act(float delta) {
super.act(delta);
}
}
try to use stage's camera instead of creating your own. Change your GameScreen constructor like this:
public GameScreen(Game game)
{
stage = new Stage(new FitViewport(Game.WIDTH, Game.HEIGHT));
camera = (OrthographicCamera) stage.getCamera();
Gdx.input.setInputProcessor(stage);
}
then in the render method set the camera position just like
camera.position.set(player.getX(), camera.position.y, 0);
before camera.update() call
There is also something strange in your code - why you have camera.position.set() and setting player x in this condition:
if (delta > 1 / 60f) //??
{
player.setX(player.getX() + (4 * delta));
camera.position.set(player.getX(), camera.position.y, 0);
}
I'm pretty sure you don't need this - but even if you need the
camera.position.set(player.getX(), camera.position.y, 0);
should be out of if statement because what is happening now is that even if you are changing your player position (using keybord through PlayerInputHandler object) you **don't update camera position. Try to remove if statement or at least do something like
public void render(float delta)
{
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
if (delta > 1 / 60f)
{
player.setX(player.getX() + (100 * delta));
}
camera.position.set(player.getX(), camera.position.y, 0);
update();
stage.act(delta);
stage.draw();
}
last thing is that if your stage is empty (excluding player) when camera will start to follow player - you will see as player not moving at all :) Add someting more to stage

Box2D body lags/jumps when a camera is centered on it

I'm trying to set the camera position to the position of a body, but when I do this, the body will jump very noticeably. You can see this with the debug renderer but I have a sprite attached in my code. The jump is always in the direction that the sprite is headed. I've got a fixed time step with interpolation, and I update the sprites position to an interpolated value of the current and last position of a box2d body every frame. Then set the camera to the interpolated position.
import java.util.Random;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.Input.Orientation;
import com.badlogic.gdx.InputMultiplexer;
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.BitmapFont;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.JointEdge;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.TimeUtils;
import com.badlogic.gdx.utils.viewport.FitViewport;
public class GameScreen implements Screen {
private static learnGame game;
private static OrthographicCamera camera;
private static FitViewport viewport;
private static Random rand;
private static BitmapFont font;
private static Vector3 touch;
private static double frameTime;
private static double accumulator;
private static float animTime = 0f;
private static float step = 1f / 60f;
private static boolean killBody;
private static Buttons buttons;
public static Player tom;
public static InputMultiplexer multiplexer;
public static Bodies world;
public static boolean paused;
private static Sprite tomSprite = new Sprite(new Texture(Gdx.files.internal("chars/bob.png")));
public GameScreen(learnGame learngame) {
GameScreen.game = learngame;
multiplexer = new InputMultiplexer();
Gdx.input.setInputProcessor(multiplexer);
camera = new OrthographicCamera();
viewport = new FitViewport(40, 22.5f, camera);
buttons = new Buttons(game, multiplexer, viewport); //HUD stuff
world = new Bodies(viewport, multiplexer); //creates a box2d world
tom = new Player(world.box2d, 10, 15, 1f, multiplexer); //creates a body with a CircleShape with a radius of 1. Catches user input to apply forces to the body
Assets.loadSprites();
world.box2d.getBodies(world.bodies);
font = new BitmapFont();
touch = new Vector3();
rand = new Random();
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
learnGame.batch.setProjectionMatrix(camera.combined);
frameTime = 0;
if (!paused) {
frameTime = Math.min(Gdx.graphics.getRawDeltaTime(), 0.25);
accumulator += frameTime;
tom.update(); //here I apply forces to the body that I attach a camera to
generalUpdate(delta, touch, camera);
updatePositions(); //get previous positions for interpolation
while (accumulator >= step) {
world.box2d.step(step, 6, 2);
accumulator -= step;
interpolate((float) (accumulator / step));
}
world.box2d.clearForces();
learnGame.batch.begin();
if (tom.getBody().isActive()) {
tomSprite.setSize(tom.getHeight(), tom.getHeight());
tomSprite.setOriginCenter();
tomSprite.setRotation(Assets.tom.angle);//this doesn't work right but not the point.
tomSprite.setPosition(Assets.tom.pos.x, Assets.tom.pos.y);
tomSprite.draw(learnGame.batch);
}
learnGame.batch.end();
cameraUpdate(); //update the camera to the same position as the sprite
} else { //else pause the game
learnGame.batch.begin();
learnGame.batch.draw(Assets.pauset, viewport.getCamera().position.x
- (viewport.getCamera().viewportWidth / 2), viewport.getCamera().position.y
- (viewport.getCamera().viewportHeight / 2), viewport.getWorldWidth(), viewport.getWorldHeight());
learnGame.batch.end();
if (Gdx.input.isKeyJustPressed(Keys.SPACE) || Gdx.input.justTouched()) {
paused = false;
}
}
//destroy fixtures and bodies outside of the world step
for (Fixture fixture : Bodies.fixturesToDestroy) {
if (Bodies.destroyJoint == true) {
world.box2d.destroyJoint(Bodies.joint);
Bodies.joint = null;
Bodies.destroyJoint = false;
}
fixture.getBody().destroyFixture(fixture);
Bodies.fixturesToDestroy.removeValue(fixture, true);
}
for (Body body : Bodies.bodiesToDestroy) {
world.box2d.destroyBody(body);
body.setActive(false);
Bodies.bodiesToDestroy.removeValue(body, true);
}
}
#Override
public void show() {
Assets.firstSound.play();
}
#Override
public void resize(int width, int height) {
viewport.update(width, height, true);
Assets.reloadFont();
}
#Override
public void pause() {
paused = true;
}
#Override
public void resume() {
}
#Override
public void hide() {
paused = true;
}
#Override
public void dispose() {
Bodies.box2d.dispose();
Bodies.debugRenderer.dispose();
Buttons.stage.dispose();
Assets.cFrame.getTexture().dispose();
Assets.firstSound.dispose();
System.out.println("disposed");
}
public void generalUpdate(float delta, Vector3 touch, OrthographicCamera camera) {
if (Gdx.input.isKeyPressed(Keys.PAGE_UP)) {
camera.zoom -= 2f * Gdx.graphics.getDeltaTime();
;
} else if (Gdx.input.isKeyPressed(Keys.PAGE_DOWN)) {
camera.zoom += 2f * Gdx.graphics.getDeltaTime();
}
}
public static void cameraUpdate() {
camera.position.set(Assets.tom.pos, 0);
System.out.println("cam:" + Assets.tom.pos.x);
camera.update();
}
public static void kill() {
world.box2d.dispose();
world.debugRenderer.dispose();
Assets.cFrame.getTexture().dispose();
}
public void updatePositions() {
for (MySprite name : Assets.spriteList) {
name.prevPos = name.body.getTransform().getPosition();
name.prevAngle = name.body.getTransform().getRotation();
}
}
public void interpolate(float alpha) {
for (MySprite name : Assets.spriteList) {
name.pos.x = (name.body.getTransform().getPosition().x) * alpha + name.prevPos.x * (1.0f - alpha);
name.pos.y = (name.body.getTransform().getPosition().y) * alpha + name.prevPos.y * (1.0f - alpha);
name.angle = (name.body.getTransform().getRotation() * alpha + name.prevAngle * (1.0f - alpha));
}
}
}
I have tested my interpolation implementation without the camera moving and it appears to work fine. I've been able to test this on my desktop and on my android. The sprite "jumps" a lot more on my android but it happens on both devices. Not sure where I went wrong here, would really appreciate some input!
It's an old question, I know, but I just solved my Problem today.
I have implemented a fixed Timestep and interpolation, but my body lagged and jittered and jumped like there would be no tomorrow.
Please do following things to your camera Movement:
Use the interpolated Position from the body, NOT the original body position.
Use camera.position.slerp(x, y, z, alpha) to do a smooth movement. (You need to play a bit with the variables.
A really simple Example:
static Vector3 desiredPosition;
static {
desiredPosition = new Vector3(0, 0, 0);
}
public static moveCam(Player player, Camera camera){
desiredPosition.x = player.interpolatedPos.x;
desiredPosition.y = player.interpolatedPos.y;
camera.slerp(desiredPosition, Gdx.graphics.getDeltaTime * 5);
camera.update();
}
and in your render do the following
render(float delta){
moveCam(player, camera);
}
(Instant position setting caused jitter for my moving Object)
I wanted to give up my project, because of this bug. But I managed to do it. I hope it'll help people out there.
€dit: A guess why the jumping body is happening:
The interpolated position is not synchron with the camera (set Position then update world(now interpolated pos is offset with camera), then draw)
But I'm not sure with this.

How to use libgdx without having a core project?

I have been trying to implement libgdx without a core project in a new eclipse project, but I keep getting:
The method initialize(ApplicationListener,
AndroidApplicationConfiguration) in the type AndroidApplication is not
applicable for the arguments (AndroidApplication,
AndroidApplicationConfiguration)
The code I use is quite simple at the moment:
package com.debels.androidapplication;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import android.os.Bundle;
public class MainActivity extends AndroidApplication{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
cfg.useGL20 = false;
initialize(new AndroidApplication(), cfg);
}
}
and
package com.debels.androidapplication;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.FPSLogger;
import com.badlogic.gdx.graphics.OrthographicCamera;
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.debels.androidapplication.screens.MainMenuScreen;
public class AndroidApplication extends Game{
private OrthographicCamera camera;
private SpriteBatch batch;
private Texture texture;
private Sprite sprite;
private FPSLogger fps;
#Override
public void create(){
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
camera = new OrthographicCamera(1, h/w);
batch = new SpriteBatch();
//texture = new Texture(Gdx.files.internal("data/libgdx.png"));
//texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
//TextureRegion region = new TextureRegion(texture, 0, 0, 512, 275);
/*sprite = new Sprite(region);
sprite.setSize(0.9f, 0.9f * sprite.getHeight() / sprite.getWidth());
sprite.setOrigin(sprite.getWidth()/2, sprite.getHeight()/2);
sprite.setPosition(-sprite.getWidth()/2, -sprite.getHeight()/2);*/
setScreen(new MainMenuScreen(this));
fps = new FPSLogger();
}
#Override
public void dispose() {
super.dispose();
}
#Override
public void render() {
super.render();
/*fps.log();
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined);
batch.begin();
sprite.draw(batch);
batch.end();*/
}
#Override
public void resize(int width, int height) {
super.resize(width, height);
}
#Override
public void pause() {
super.pause();
}
#Override
public void resume() {
super.resume();
}
}
Thats because you are sending a (gdx)AndroidApplication instance to the ini instead of a (gdx)AndroidApplicationListener (which is any class that extends Game or implements ApplicationListener).
You get all confused because you named that class AndroidApplication...
Change this:
initialize(new AndroidApplication(), cfg);
to this:
initialize(new com.debels.androidapplication.AndroidApplication(), cfg);
Or better yet, change the name of that class.
Also dont forget to copy the gdx.jar to the android project libs folder.

Moving bitmap with SurfaceView is slow

I am developing a game for android. Between stages, i want to show a part of a map with a route, and move it from a city to city (stage to stage).
First i want to do it on my phone, this a Samsung Galaxy Y, 240x320 Qvga ldpi.
So i have the map file in jpg format. This picture is 2463x602, this is a world map.
I did it, everything is done except one thing. This "animation" is slow for me.
When i start with this, i thought, it will be so fast, and i will handle the speed with a Thread.sleep(); but the matter is, it is not fast.
How can i make it more faster this?
Here is my code:
package hu.mycompany.myproject;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class MapActivity extends Activity {
DrawView drawView;
SoundPool soundPool;
int soundId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
soundId = soundPool.load(this, R.raw.airplane, 1);
drawView = new DrawView(this);
setContentView(drawView);
}
public void playSound() {
soundPool.play(soundId, 1f, 1f, 1, 0, 1f);
}
#Override
public void onResume() {
super.onResume();
playSound();
drawView.resume();
}
#Override
public void onPause() {
super.onPause();
drawView.pause();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_map, menu);
return true;
}
public class DrawView extends SurfaceView implements Runnable {
Bitmap gameMap = null;
Thread gameLoop = null;
SurfaceHolder surface;
Rect rect;
volatile boolean running;
volatile boolean moved;
public DrawView(Context context) {
super(context);
moved = false;
surface = getHolder();
gameMap = BitmapFactory.decodeResource(getResources(),
R.drawable.map);
}
public void resume() {
running = true;
gameLoop = new Thread(this);
gameLoop.start();
}
public void pause() {
running = false;
while (true) {
try {
gameLoop.join();
} catch (InterruptedException e) {
}
}
}
#Override
public void run() {
Rect canvasSize = new Rect(0, 0, 240, 320);
Paint paint = new Paint();
paint.setAntiAlias(true);
while (running) {
if (!surface.getSurface().isValid()) {
continue;
}
if (!moved) {
int i;
for (i = 80; i <= 830; i++) {
Canvas canvas = surface.lockCanvas();
rect = new Rect(i, 250, (i + 240), 570);
canvas.drawBitmap(gameMap, rect, canvasSize, paint);
surface.unlockCanvasAndPost(canvas);
}
moved = true;
}
}
}
}
}
1-try to reduce picture size by exporting it save for web in photoshop and select png as extension type
2- You should create two class one for handling thread and other for rendering and game logic. The thread will manage it by locking canvas when system is rendering. Take a look at this link
http://android-er.blogspot.com/2010/05/android-surfaceview.html

Categories

Resources