I am new in libGDX and making a simple game like bomber-man.I want to move a sprite in accordance with my touch. for example , if i touch below the image it have to move downside,if i touch in right side of image or sprite it should move in right direction. this should be happened continuously i.e when i touch screen any where,sprite should move continuously and when i release the touch,it should stop there.
Thanks in advance..
here is my code
package com.kamal.bomberman;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.GL10;
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.badlogic.gdx.input.GestureDetector;
import com.badlogic.gdx.input.GestureDetector.GestureListener;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.sun.org.apache.bcel.internal.generic.RETURN;
public class Bomberman implements ApplicationListener {
private SpriteBatch batch;
private Texture textureBg,textureBman;
private TextureRegion regionBg , regionBman;
float x = 5 , y = 630 ;
#Override
public void create() {
textureBg = new Texture(Gdx.files.internal("data/bg.png"));
textureBman = new Texture(Gdx.files.internal("data/bm.png"));
regionBman = new TextureRegion(textureBman,0,0,256,512);
regionBg = new TextureRegion(textureBg,6,5,256,192);
batch = new SpriteBatch();
}
#Override
public void dispose() {
}
#Override
public void render() {
batch.begin();
batch.draw(regionBg,0,0,800,1280);
batch.draw(textureBman,x,y,300,300);
batch.end();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
}
Related
SurfaceView is never available for drawing after creation.
Other SO questions indicate that it can be managed with the callback functions handed to it, and it must be assigned to setContentView before the lifecycle starts.
Logcat indicates that the callbacks are assigned successfully, however they are never fired.
Full code here but I think relevant parts can be found in the main activity:
package com.example.gavin.pixelarraytest;
import android.app.Activity;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GameView theGame = new GameView(this, 0,0);
SurfaceHolder testt;
testt = theGame.getHolder();
setContentView(theGame);
while(true){
if(testt.getSurface().isValid()){ // this never becomes true. isCreating is also consistently false at this point
theGame.prepareCanvas();
break;
}
}
}
}
And in the SurfaceView object:
package com.example.gavin.pixelarraytest;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.util.Log;
import android.view.Display;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
public class GameView extends SurfaceView implements Runnable {
private Paint paint;
private Canvas canvas;
private Bitmap _buffer;
private SurfaceHolder ourHolder;
private boolean running;
private boolean paused = false;
private long fps;
public GameView(Context context, int screenX, int screenY){
ourHolder = getHolder();
ourHolder.addCallback(new MyCallback());
paint = new Paint();
}
public void prepareCanvas(){
running = true;
run();
}
#Override
public void run(){
while(running){
long startFrameTime = System.currentTimeMillis();
draw();
long endFrameTime = System.currentTimeMillis() - startFrameTime;
if(endFrameTime >= 1){
fps = 1000 / endFrameTime;
}
}
private void update(){
class MyCallback implements SurfaceHolder.Callback {
#Override
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
}
private void draw(){
this.setWillNotDraw(false);
if(ourHolder.getSurface().isValid()){
canvas = ourHolder.lockCanvas();
canvas.drawColor(Color.argb(255,100,40,40));
int width = 100;
int height = 100;
int colors[] = new int[width*height];
for (int i = 0; i < colors.length; i++){
int a = 255, r = 40, g = 100, b = 40;
colors[i] = (a << 24) | (r << 16) | (g << 8) | b;
_buffer = Bitmap.createBitmap(colors, width, height, Bitmap.Config.RGB_565);
canvas.drawBitmap(_buffer, 0,0,null);
}
}
}
Am I misunderstanding how SurfaceView is used or am I using it incorrectly in the above?
To inflate a canvas object you can try this:
First create a layout file in res>layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<GameView
android:id="+#id/mGameView"
android:layout_height="match_parent"
android:layout_width="match_parent"
/>
</LinearLayout>
Then you can inflate this by calling
setContentView(R.layout.your_file_name);
And finally access the gameview by using:
GameView gameView = findViewById(R.id.mGameView);
gameView.prepareCanvas();
Here my code:
package com.mygdx.game;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class MyGdxGame extends ApplicationAdapter {
SpriteBatch batch;
Texture img;
#Override
public void create () {
Gdx.input.setCatchBackKey(true);
batch = new SpriteBatch();
img = new Texture("badlogic.jpg");
}
#Override
public void render () {
if (Gdx.input.isKeyJustPressed(Input.Keys.BACK)) {
Gdx.app.log("Debug", "Back pressed!");
Gdx.app.exit();
}
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(img, 0, 0);
batch.end();
}
}
I have no idea why the code doesn't working as expected, when i replace "isKeyJustPressed" with "isKeyPressed" it works perfectly.
Or replace the Keys.Back with Keys.ESCAPE (run on desktop module) its work.
Any ideas? Thanks
Keys.BACK isnt probably what you are looking for. Try Keys.BACKSPACE
I am trying out AndEngine and cannot work out why my splashscreen is not centered in the device - see the image below.
I have set a default size for the device (800, 480) and placed the splash at camera.getWidth() / 2. It seems like the corner of my splash hits the center pretty spot on but I want the center of the splash to be centered - makes sense?
MainActivity:
package com.example.caspe.getmeout;
import org.andengine.engine.Engine;
import org.andengine.engine.LimitedFPSEngine;
import org.andengine.engine.camera.Camera;
import org.andengine.engine.handler.timer.ITimerCallback;
import org.andengine.engine.handler.timer.TimerHandler;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.WakeLockOptions;
import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.andengine.engine.options.EngineOptions;
import org.andengine.entity.scene.Scene;
import java.io.IOException;
public class MainActivity extends BaseGameActivity {
private ResourcesManager resourcesManager;
private static final int CAMERA_WIDTH = 800;
private static final int CAMERA_HEIGHT = 480;
private Camera camera;
public EngineOptions onCreateEngineOptions() {
camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(800, 480), this.camera);
engineOptions.getAudioOptions().setNeedsMusic(true).setNeedsSound(true);
engineOptions.setWakeLockOptions(WakeLockOptions.SCREEN_ON);
return engineOptions;
}
#Override
public Engine onCreateEngine(EngineOptions pEngineOptions) {
return new LimitedFPSEngine(pEngineOptions, 60);
}
#Override
public void onCreateResources(OnCreateResourcesCallback pOnCreateResourcesCallback) throws Exception {
ResourcesManager.prepareManager(mEngine, this, camera, getVertexBufferObjectManager());
resourcesManager = ResourcesManager.getInstance();
pOnCreateResourcesCallback.onCreateResourcesFinished();
}
#Override
public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback) throws IOException {
SceneManager.getInstance().createSplashScene(pOnCreateSceneCallback);
}
#Override
public void onPopulateScene(Scene pScene, OnPopulateSceneCallback pOnPopulateSceneCallback) throws IOException {
mEngine.registerUpdateHandler(new TimerHandler(2f, new ITimerCallback() {
public void onTimePassed(final TimerHandler pTimerHandler) {
mEngine.unregisterUpdateHandler(pTimerHandler);
// load menu resources, create menu scene
// set menu scene using scene manager
// disposeSplashScene();
}
}));
pOnPopulateSceneCallback.onPopulateSceneFinished();
}
}
And the code for Splash:
package com.example.caspe.getmeout;
import org.andengine.engine.camera.Camera;
import org.andengine.entity.sprite.Sprite;
import org.andengine.opengl.util.GLState;
import com.example.caspe.getmeout.BaseScene;
import com.example.caspe.getmeout.SceneManager.SceneType
public class SplashScene extends BaseScene {
private Sprite splash;
#Override
public void createScene() {
splash = new Sprite(0,0, resourcesManager.splash_region, vbom) {
#Override
protected void preDraw(GLState pGLState, Camera pCamera) {
super.preDraw(pGLState, pCamera);
pGLState.enableDither();
}
};
splash.setScale(1.5f);
splash.setPosition(camera.getWidth() / 2, camera.getHeight() / 2);
attachChild(splash);
}
#Override
public void onBackKeyPressed() {
}
#Override
public SceneType getSceneType() {
return SceneType.SCENE_SPLASH;
}
#Override
public void disposeScene() {
splash.detachSelf();
splash.dispose();
this.detachSelf();
this.dispose();
}
}
Please let me know if you need more code than this.
I am not directly seeking a working piece of code but more where my error is so I can use my braincells and work it out - I have just stared myself blind here.
splash.setPosition(camera.getWidth() / 2, camera.getHeight() / 2);
That is not enough. Your splash is actually centered correctly: the top left corner is in the center.
What you need is to subtract the half width and height of the splash from the position, too.
// untested code
splash.setPosition(camera.getWidth() / 2 - splash.getWidth() / 2, camera.getHeight() / 2 - splash.getHeight() / 2);
i am new to android and stuck with getting screen size. Here is my code,
package com.piyush.droidz;
import android.app.Activity;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import com.piyush.droidz.model.boy;
public class MainGamePanel extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = MainGamePanel.class.getSimpleName();
private GameThread td;
private boy b1;
private int s_width;
private int s_height;
public MainGamePanel(Context context) {
super(context);
getHolder().addCallback(this);
Log.d(TAG, "Screen width=" + s_width);
b1 = new boy(BitmapFactory.decodeResource(getResources(), R.drawable.boy), 50, 50);
td = new GameThread(getHolder(), this);
setFocusable(true);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
s_width = getHolder().getSurfaceFrame().width();
Log.d(TAG, "Present Screen width=" + s_width);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
td.setRunning(true);
td.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
td.setRunning(false);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
b1.handleActionDown((int)event.getX(), (int)event.getY());
if (event.getY()>getHeight()-50) {
td.setRunning(false);
((Activity) getContext()).finish();
}
else {
Log.d(TAG, "Coordinates: X="+event.getX()+", Y="+event.getY());
}
}
if (event.getAction()==MotionEvent.ACTION_MOVE) {
if (b1.isTouched()) {
b1.setX((int)event.getX());
b1.setY((int)event.getY());
}
}
if (event.getAction()==MotionEvent.ACTION_UP) {
b1.setTouched(false);
}
return true;
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.parseColor("#ff0000"));
b1.draw(canvas);
}
}
in the first log-tag it shows 0 where as in the second log-tag it shows exact width of emulator. I have tried initializing the "s_width" with getHolder().getSurfaceFrame().width() even before the constructor but still "s_width" is 0. Also tried WindowManagerand getwindowManager() but it is not recognized by IDE in this class. Here is my Activity class,
package com.piyush.droidz;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
public class DroidzActivity extends Activity {
MainGamePanel mgp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mgp = new MainGamePanel(this);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(mgp);
}
}
please help!
Have you tried?
DisplayMetrics metrics = new DisplayMetrics();
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(metrics);
You need to use context for getting the WindowManager. please see the documentation
http://developer.android.com/reference/android/view/WindowManager.html
Preferably the above should be done inside the constructor
public MainGamePanel(Context context) {}
Hope it helps. :)
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.