Android Touch not working. Andengine - android

The scene is made pretty well but the touch is not working. I registered all sprites and made onTouchAreaBindingOnActionDownEnabled(true) too. I have tried using Andengine's made in MenuScene but it is not working touching part only too. Here's my present code.
I had same problem as this gentleman here, since I had no way out I changed my code to:
import org.andengine.engine.camera.Camera;
import org.andengine.entity.sprite.Sprite;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.util.GLState;
import org.andengine.opengl.vbo.VertexBufferObjectManager;
import com.***.RM; //I changed the directory name to ***
import com.***.SceneManager; //I changed the directory name to ***
import com.***.SceneType; //I changed the directory name to ***
public class MainMenuScene extends BaseScene {
private final int MENU_PLAY = 0;
private final int MENU_OPTIONS = 1;
private final int MENU_CREDITS = 2;
private final int MENU_EXIT = 3;
final int w = 256, h = 64;
public class MenuSprite extends Sprite {
private int ID;
public MenuSprite(int pID, int pX, int pY, ITextureRegion tex, VertexBufferObjectManager vbom) {
super(pX, pY, w, h, tex, vbom);
this.ID = pID;
}
#Override
public boolean onAreaTouched(TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) {
System.out.println("text");
if (pSceneTouchEvent.isActionDown() || pSceneTouchEvent.isActionMove()) {
onclick(this.ID);
this.setScale(1.5f);
return true;
} else {
this.setScale(1f);
}
return true;
}
}
#Override
public void createScene() {
attachChild(new Sprite(RM.MX, RM.MY, rM.menu_back, vbom) {
#Override
protected void preDraw(GLState pGLState, Camera pCamera) {
super.preDraw(pGLState, pCamera);
pGLState.enableDither();
}
});
final MenuSprite playMenuItem = new MenuSprite(MENU_PLAY, RM.MX, RM.CH * 4 / 6, rM.menu_play, vbom);
final MenuSprite optionsMenuItem = new MenuSprite(MENU_OPTIONS, RM.MX, RM.CH * 3 / 6, rM.menu_options, vbom);
final MenuSprite creditsMenuItem = new MenuSprite(MENU_CREDITS, RM.MX, RM.CH * 2 / 6, rM.menu_credit, vbom);
final MenuSprite exitMenuItem = new MenuSprite(MENU_EXIT, RM.MX, RM.CH * 1 / 6, rM.menu_exit, vbom);
attachChild(playMenuItem);
attachChild(optionsMenuItem);
attachChild(creditsMenuItem);
attachChild(exitMenuItem);
registerTouchArea(playMenuItem);
registerTouchArea(optionsMenuItem);
registerTouchArea(creditsMenuItem);
registerTouchArea(exitMenuItem);
setTouchAreaBindingOnActionDownEnabled(true);
}
#Override
public void disposeScene() {
}
#Override
public SceneType getSceneType() {
return SceneType.SCENE_MENU;
}
#Override
public void onBackKeyPressed() {
System.exit(0);
}
public void onclick(int ID) {
switch (ID) {
case MENU_PLAY:
SceneManager.getInstance().createLevelSelectionScene();
break;
case MENU_OPTIONS:
break;
case MENU_EXIT:
onBackKeyPressed();
break;
default:
break;
}
}
}
Here's a screenshot(I removed the title):
In Logcat I get the following on touching:
04-02 22:29:31.909: I/InputReader(159): dispatchTouch::touch event's action is 0
04-02 22:29:31.909: I/InputDispatcher(159): Delivering touch to current input target
but my application filtered messages have no touch log, not even the system.out that I added.

pOnCreateSceneCallback.onCreateSceneFinished(menuScene); is not present.
This does not give any warnings or errors but creates problems.

Related

Android memory leak Custom view

I'm trying to make small App. This App have Activity, Custom View Class, and service.
1) Activity ask service for new Data and redraw Custom view
2) Service is listning to Bluetooth device and parse data.
Everything was fine, but I noticed that App is slowing down after 40 mins working.
I made another project remove service and find that it slowing too! So problem is my Customview class, maybe i have memory leaks in service to... but i have problem with drawings 100%.
I found that i have some objects that i'm creating on onDraw() method.. i try to move all thise staff to onSizeChanged() - but get more lags.
And now i need help. I need some example with simple drawings that depends on device width and height (I think my method is wrong - i use proportions of my 'Design' to calculate demetions in px)
By the way i'm using animator which make animations more smooth))
public class Dynamics {
/**
* Used to compare floats, if the difference is smaller than this, they are
* considered equal
*/
private static final float TOLERANCE = 0.01f;
/** The position the dynamics should to be at */
private float targetPosition;
/** The current position of the dynamics */
private float position;
/** The current velocity of the dynamics */
private float velocity;
/** The time the last update happened */
private long lastTime;
/** The amount of springiness that the dynamics has */
private float springiness;
/** The damping that the dynamics has */
private double damping;
public Dynamics(float springiness, float dampingRatio) {
this.springiness = springiness;
this.damping = dampingRatio * 2 * Math.sqrt(springiness);
}
public void setPosition(float position, long now) {
this.position = position;
lastTime = now;
}
public void setVelocity(float velocity, long now) {
this.velocity = velocity;
lastTime = now;
}
public void setTargetPosition(float targetPosition, long now) {
this.targetPosition = targetPosition;
lastTime = now;
}
public void update(long now) {
float dt = Math.min(now - lastTime, 50) / 1000f;
float x = position - targetPosition;
double acceleration = -springiness * x - damping * velocity;
velocity += acceleration * dt;
position += velocity * dt;
lastTime = now;
}
public boolean isAtRest() {
final boolean standingStill = Math.abs(velocity) < TOLERANCE;
final boolean isAtTarget = (targetPosition - position) < TOLERANCE;
return standingStill && isAtTarget;
}
public float getPosition() {
return position;
}
public float getTargetPos() {
return targetPosition;
}
public float getVelocity() {
return velocity;
}
}
In my Custom view i have this to set new data:
public void SetData(int[] NewData2,float[]newDatapoints)
{
this.NewData=NewData2;
long now = AnimationUtils.currentAnimationTimeMillis();
if (datapoints == null || datapoints.length != newDatapoints.length) {
datapoints = new Dynamics[newDatapoints.length];
for (int i = 0; i < newDatapoints.length; i++) {
datapoints[i] = new Dynamics(70f, 0.50f);
datapoints[i].setPosition(newDatapoints[i], now);
datapoints[i].setTargetPosition(newDatapoints[i], now);
}
invalidate();
} else {
for (int i = 0; i < newDatapoints.length; i++) {
datapoints[i].setTargetPosition(newDatapoints[i], now);
}
removeCallbacks(animator);
post(animator);
}
LastData=NewData;
//redraw();
}
Thise is "code" of my custom view, after all changes it's look terible, so i cut 90% of it. And i make some test code insted:
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ComposeShader;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.RadialGradient;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.animation.AnimationUtils;
import java.io.IOException;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Random;
public class CustomDisplayView extends View {
//paint for drawing custom view
private Paint RectPaint = new Paint();
//Динамические данные float
private Dynamics[] datapoints;
//Динамические статические Int
private int[] NewData = new int[500];
//созадем новый объект квадрат
private RectF rectf= new RectF();
//Задаем массив динамических цветов
int[] CurColors= new int[100];
int[] TargetColors= new int[100];
public CustomDisplayView(Context context, AttributeSet attrs){
super(context, attrs);
//Установка парметров красок
RectPaint.setAntiAlias(true);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
if (w != 0 && h != 0) {
//create Bitmap here
}
}
/**
* Override the onDraw method to specify custom view appearance using canvas
*/
#Override
protected void onDraw(Canvas canvas) {
//Get Screen size
//int viewWidth=this.getMeasuredWidth();
// int viewHeight = this.getMeasuredHeight();
//Выводим код цвета
RectPaint.setColor(0xff000000);
RectPaint.setTextSize(40);
canvas.restore();
canvas.drawText("V: " + datapoints[1].getPosition(), 20, 60, RectPaint);
//int saveCount = canvas.save();
for(int a=0;a<1000;a++)
{
rectf.set(datapoints[a].getPosition(), datapoints[a + 1].getPosition(), datapoints[a].getPosition() + datapoints[a + 1].getPosition() / 10, datapoints[a + 1].getPosition() + datapoints[a + 1].getPosition() / 10);
RectPaint.setColor(0x88005020);
//RectPaint.setColor(CurColor[a]);
//canvas.rotate(datapoints[1].getPosition(), viewWidth/2, viewHeight/2);
canvas.drawRoundRect(rectf, 0, 0, RectPaint);
//canvas.restore();
}
//canvas.restoreToCount(saveCount);
/*
for(int a=0;a<999;a++)
{
CurColors[a]=progressiveColor(CurColors[a], TargetColors[a], 2);
if(CurColors[a]==TargetColors[a])
{
TargetColors[a]=randomColor();
}
}
*/
canvas.restore();
}
//Рандом колор
public static int randomColor(){
Random random = new Random();
int[] ColorParams= new int[4];
ColorParams[0]=random.nextInt(235)+20;
ColorParams[1]=random.nextInt(255);
ColorParams[2]=random.nextInt(255);
ColorParams[3]=random.nextInt(255);
return Color.argb(ColorParams[0], ColorParams[1], ColorParams[2], ColorParams[3]);
}
//Интерполяция цвета
public static int progressiveColor(int CurColor,int TargetColor,int Step){
//Current color
int[] ColorParams= new int[4];
ColorParams[0]=(CurColor >> 24) & 0xFF;
ColorParams[1]=(CurColor >> 16) & 0xFF;
ColorParams[2]=(CurColor >> 8) & 0xFF;
ColorParams[3]=CurColor & 0xFF;
//TargetColor
int[] TargetColorParams= new int[4];
TargetColorParams[0]=(TargetColor >> 24) & 0xFF;
TargetColorParams[1]=(TargetColor >> 16) & 0xFF;
TargetColorParams[2]=(TargetColor >> 8) & 0xFF;
TargetColorParams[3]=TargetColor & 0xFF;
for(int i=0;i<4;i++)
{
if(ColorParams[i]<TargetColorParams[i])
{
ColorParams[i]+=Step;
if(ColorParams[i]>TargetColorParams[i])
{
ColorParams[i]=TargetColorParams[i];
}
}
else if(ColorParams[i]>TargetColorParams[i])
{
ColorParams[i]-=Step;
if(ColorParams[i]<TargetColorParams[i])
{
ColorParams[i]=TargetColorParams[i];
}
}
}
//int red = r - (int)((float)(r*255)/(float)all);
//int green = (int)((float)(g*255)/(float)all);
return Color.argb(ColorParams[0], ColorParams[1], ColorParams[2], ColorParams[3]);
//return String.format("#%06X", (0xFFFFFF & Color.argb(ColorParams[0], ColorParams[1], ColorParams[2], ColorParams[3])));
//return " "+opacity+" "+red+" "+green+" "+blue;
}
//each custom attribute should have a get and set method
//this allows updating these properties in Java
//we call these in the main Activity class
/**
* Get the current text label color
* #return color as an int
*/
public int getLabelColor(){
return 1;
}
/**
* Set the label color
* #param newColor new color as an int
*/
public void setLabelColor(int newColor){
//update the instance variable
//labelCol=newColor;
//redraw the view
invalidate();
requestLayout();
}
public void redraw(){
//redraw the view
invalidate();
requestLayout();
}
public void SetData(int[] NewData2,float[]newDatapoints)
{
this.NewData=NewData2;
long now = AnimationUtils.currentAnimationTimeMillis();
if (datapoints == null || datapoints.length != newDatapoints.length) {
datapoints = new Dynamics[newDatapoints.length];
for (int i = 0; i < newDatapoints.length; i++) {
datapoints[i] = new Dynamics(70f, 0.50f);
datapoints[i].setPosition(newDatapoints[i], now);
datapoints[i].setTargetPosition(newDatapoints[i], now);
}
invalidate();
} else {
for (int i = 0; i < newDatapoints.length; i++) {
datapoints[i].setTargetPosition(newDatapoints[i], now);
}
removeCallbacks(animator);
post(animator);
}
//redraw();
}
public int GetAction(float x,float y)
{
/*
if(x>(DicsCenterX-LineHalfSpeedZone) && x<(DicsCenterX+LineHalfSpeedZone) && y>(DicsCenterY-PowerOutRadius) && y<(DicsCenterY-SpeedZoneRadius2))
{
// private int SpeedZoneRadius2=0;
// private int PowerOutRadius=0;
//Смена режима
//начинаем смену размеру index / ms
ChangeVal(0,700);
return 1;
}
else if(x>(CofCantBGDrop*2) && x<(CofCantBGDrop*4) && y>(DicsCenterY-PowerOutRadius) && y<(DicsCenterY-SpeedZoneRadius2))
{
return 2;
}
else
{
return 0;
}
//return 0;
*/
return 1;
}
public static String fmt(double d)
{
double val = d/100;
String result;
if(val == (long) val)
result= String.format("%d",(long)d);
else
result= String.format("%s",d);
if(result.length()<2)
{
String result2=result;
result="0"+result2;
}
return result;
}
private Runnable animator = new Runnable() {
#Override
public void run() {
boolean needNewFrame = false;
long now = AnimationUtils.currentAnimationTimeMillis();
for (Dynamics dynamics : datapoints) {
dynamics.update(now);
if (!dynamics.isAtRest()) {
needNewFrame = true;
}
}
if (needNewFrame) {
postDelayed(this, 15);
}
invalidate();
}
};
}
I just want to understand where i need to declare scale values, where i need to calc real dimensions in px.. and et.c. to have no memory leaks..
If i remove color change and incrice number of Rects up to 1000 - i get lags.
All methods o any information how to debug memory leaks - you are wellcome!
You have to remove runnable for animation when view is detached.
if (needNewFrame) {
postDelayed(this, 15); <--- memory leak
}
Try like this.
#Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
removeCallback(your runnable);
}
Also refreshing every 15 milliseconds is very heavy.

Implementing The input as a separate thread

I am trying to implement an ACTION_MOVE input that moves a paddle as long as the screen is touched, in place of the ACTION_DOWN that is currently present. However Once I switch the ACTION_MOVE in place of ACTION_DOWN, the paddle moves but with stutters(some times too slow, then stopping then going too fast all of a sudden). How would I resolve this? Would Moving the Input to another thread be any good?
Here's the code
MainActivity.java
package com.nblsoft.ballpractise;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View myball = new BallDraw(this);
myball.setBackgroundColor(Color.BLACK);
setContentView(myball);
//setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
BallDraw.java
package com.nblsoft.ballpractise;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.View;
public class BallDraw extends View {
//Default System Variables
int screenHeight = getResources().getDisplayMetrics().heightPixels;
int screenWidth = getResources().getDisplayMetrics().widthPixels;
private int xMin = 0; // This view's bounds
private int xMax;
private int yMin = 0;
private int yMax;
//Game Variables
public int ball_pos_x = 0;
public int ball_pos_y = 800;
public int ball_vel_x = 5;
public int ball_vel_y = 5;
public int pad_1_pos = 10;
public int pad_2_pos = 10;
public int randi=1;
//Pads Implemented as Array of points
//public int[] pad_1 = {100,200,220,240};
//public int[] pad_2 = {100,200,1250,1270};
Rect pad_1 = new Rect(400 + pad_1_pos,220,500 + pad_1_pos,240);
Rect pad_2 = new Rect(400 + pad_2_pos,1250,500 + pad_1_pos,1270);
Rect pad_1_touch = new Rect(0, 0, 1080, 200);
Rect pad_2_touch = new Rect(0, 1300, 1080, 1500);
//calculations for screen sizes
private Paint paint;
public BallDraw(Context context) {
super(context);
paint = new Paint();
// To enable touch mode
this.setFocusableInTouchMode(true);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//case MotionEvent.ACTION_MOVE:
if(pad_1_touch.contains(x,y)){
//pad_1[0]+=10;
//pad_1[1]+=10;
pad_1.offset(pad_1_pos,0);
}
else if(pad_2_touch.contains(x,y)){
//pad_2[0]+=10;
//pad_2[1]+=10;
pad_2.offset(pad_2_pos,0);
}
}
return true; //Event Handled
}
#Override
protected void onDraw(Canvas canvas) {
paint.setColor(Color.WHITE);
//Touch Regions (Un-comment to see touch Regions)
//canvas.drawRect(pad_1_touch,paint);
//canvas.drawRect(pad_2_touch,paint);
//Draw Border
canvas.drawRect(0,800,1080,803,paint);
//Paddles Draw code
canvas.drawRect(pad_1,paint);
canvas.drawRect(pad_2,paint);
//canvas.drawRect(pad_1[0],pad_1[2], pad_1[1], pad_1[3], paint);
//canvas.drawRect(pad_2[0],pad_2[2],pad_2[1],pad_2[3],paint);
//Ball code
canvas.drawRect(ball_pos_x,ball_pos_y,ball_pos_x + 13, ball_pos_y+13,paint);
// Update the position of the ball, including collision detection and reaction.
update();
// Delay
try {
Thread.sleep(30);
} catch (InterruptedException e) { }
invalidate();
}
#Override
public void onSizeChanged(int w, int h, int oldW, int oldH) {
// Set the movement bounds for the ball
xMax = w-1;
yMax = h-1;
}
private void update(){
ball_pos_y += ball_vel_y;
ball_pos_x += ball_vel_x;
if(pad_1.contains(ball_pos_x,ball_pos_y)){
ball_vel_y = -ball_vel_y;
}
else if(pad_2.contains(ball_pos_x,ball_pos_y)){
ball_vel_y = -ball_vel_y;
}
else if(ball_pos_x >= xMax){
ball_vel_x = -ball_vel_x;
}
else if(ball_pos_y >= yMax){
ball_init();
}
else if(ball_pos_x <= 0){
ball_vel_x = -ball_vel_x;
}
else if(ball_pos_y <= 0){
ball_init();
}
}
private void ball_init(){
if (randi == 1){
randi = -1;
}
else{
randi= 1;
}
ball_pos_x=0;
ball_pos_y=800;
ball_vel_x=5;
ball_vel_y=5 * randi;
}
}

SetTexture and Sprites not working as intended! (LibGDX)

I searched for and wide on the internet and I have yet to find an answer. I have an object called GameIcon which extends Sprite. Everything about it is okay except for the texture. Here is my code for the GameIcon class.
package com.xx4everPixelatedxx.gaterunner.sprites;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector3;
import com.xx4everPixelatedxx.gaterunner.GateRunner;
import javax.xml.soap.Text;
/**
* Created by Michael Jan on 8/17/2015.
*/
public class GameIcon extends Sprite {
private int vX = 3;
private int vY = 3;
private int r = 9;
private int rotation;
private Vector3 position;
private Texture texture;
public GameIcon(int x, int y) {
position = new Vector3(x, y, 0);
texture = new Texture(Gdx.files.internal("icon_players/icon1.png"));
setTexture(texture);
}
public void update() {
position.add(vX, vY, 0);
rotation = rotation + r;
rotation = rotation % 360;
setRotation(rotation);
setOriginCenter();
}
public void addPosition(int x, int y) {
position.add(x, y, 0);
setOriginCenter();
}
public void negateVelocityX() {
vX = -vX;
}
public void negateRotation() {
r = -r;
}
public Vector3 getPosition() {
return position;
}
public int getvY() {
return vY;
}
public void setvY(int vY) {
this.vY = vY;
}
public int getvX() {
return vX;
}
public void setvX(int vX) {
this.vX = vX;
}
}
Here is the icon1.png:
https://i.gyazo.com/1d52f5e58b227f08809f6c14ae4c94a4.png
Here is what I am getting:
https://i.gyazo.com/1881a9392955af34de5c55b9b8fac391.png
Note that the rotation of the image and the particles are intended. The problem is that the big square should be the texture (icon1.png), and I do not know how to fix this.
(Not enough reputation to post pictures)
I'm not familiar with LibGDX, but this may have something to do with the fact that you are maybe overwriting TextureRegion.texture. Could you try to user your parent class Sprite(Texture) constructor like this:
...
public class GameIcon extends Sprite {
private int vX = 3;
private int vY = 3;
private int r = 9;
private int rotation;
private Vector3 position;
//private Texture texture;
public GameIcon(int x, int y) {
super(new Texture(Gdx.files.internal("icon_players/icon1.png")))
position = new Vector3(x, y, 0);
}
...
As stated by Tenfour04 in comments, this method works because the parent's constructor applies the width and height of the texture, while setTexture() does not.

TMX file is not shown properly using AndEngine

I have written a position locator application for indoor positioning. I've used TMX files to render my floor maps and load them with AndEngine. The problem is that the program does not show the TMX file properly.
Here is the original file:
and here is what my application shows:
How can I fix this? Here is code:
public class TiledViewer extends SimpleBaseGameActivity implements
IOnSceneTouchListener, IScrollDetectorListener,
IPinchZoomDetectorListener {
private static final int CAMERA_WIDTH = 480;
private static final int CAMERA_HEIGHT = 320;
private SmoothCamera camera;
private TMXTiledMap mTMXTiledMap;
private SurfaceScrollDetector mScrollDetector;
private PinchZoomDetector mPinchZoomDetector;
private float mPinchZoomStartedCameraZoomFactor;
#Override
public EngineOptions onCreateEngineOptions() {
this.camera = new SmoothCamera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT, 400,
400, 10f);
final CroppedResolutionPolicy canvasSurface = new CroppedResolutionPolicy(
CAMERA_WIDTH, CAMERA_HEIGHT);
EngineOptions engineOptions = new EngineOptions(true,
ScreenOrientation.PORTRAIT_FIXED, canvasSurface, this.camera);
if (MultiTouch.isSupported(this)) {
if (MultiTouch.isSupportedDistinct(this)) {
Toast.makeText(
this,
"MultiTouch detected --> Both controls will work properly!",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(
this,
"MultiTouch detected, but your device has problems distinguishing between fingers.\n\nControls are placed at different vertical locations.",
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(
this,
"Sorry your device does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.",
Toast.LENGTH_LONG).show();
}
return engineOptions;
}
#Override
public void onCreateResources() {
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
}
#Override
public Scene onCreateScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene scene = new Scene();
scene.setOnAreaTouchTraversalFrontToBack();
this.mScrollDetector = new SurfaceScrollDetector(this);
this.mPinchZoomDetector = new PinchZoomDetector(this);
scene.setOnSceneTouchListener(this);
scene.setTouchAreaBindingOnActionDownEnabled(true);
try {
final TMXLoader tmxLoader = new TMXLoader(this.getAssets(),
this.mEngine.getTextureManager(), TextureOptions.DEFAULT,
this.getVertexBufferObjectManager(),
new ITMXTilePropertiesListener() {
#Override
public void onTMXTileWithPropertiesCreated(
final TMXTiledMap pTMXTiledMap,
final TMXLayer pTMXLayer,
final TMXTile pTMXTile,
final TMXProperties<TMXTileProperty> pTMXTileProperties) {
}
});
this.mTMXTiledMap = tmxLoader.loadFromAsset("tmx/m03.tmx");
} catch (final TMXLoadException e) {
Debug.e(e);
}
final TMXLayer tmxLayer = this.mTMXTiledMap.getTMXLayers().get(0);
scene.attachChild(tmxLayer);
this.camera.setBounds(0, 0, tmxLayer.getHeight(), tmxLayer.getWidth());
this.camera.setBoundsEnabled(true);
return scene;
}
#Override
public void onScrollStarted(final ScrollDetector pScollDetector,
final int pPointerID, final float pDistanceX, final float pDistanceY) {
final float zoomFactor = this.camera.getZoomFactor();
this.camera.offsetCenter(-pDistanceX / zoomFactor, -pDistanceY
/ zoomFactor);
}
#Override
public void onScroll(final ScrollDetector pScollDetector,
final int pPointerID, final float pDistanceX, final float pDistanceY) {
final float zoomFactor = this.camera.getZoomFactor();
this.camera.offsetCenter(-pDistanceX / zoomFactor, -pDistanceY
/ zoomFactor);
}
#Override
public void onScrollFinished(final ScrollDetector pScollDetector,
final int pPointerID, final float pDistanceX, final float pDistanceY) {
final float zoomFactor = this.camera.getZoomFactor();
this.camera.offsetCenter(-pDistanceX / zoomFactor, -pDistanceY
/ zoomFactor);
}
#Override
public void onPinchZoomStarted(final PinchZoomDetector pPinchZoomDetector,
final TouchEvent pTouchEvent) {
this.mPinchZoomStartedCameraZoomFactor = this.camera.getZoomFactor();
}
#Override
public void onPinchZoom(final PinchZoomDetector pPinchZoomDetector,
final TouchEvent pTouchEvent, final float pZoomFactor) {
this.camera.setZoomFactor(this.mPinchZoomStartedCameraZoomFactor
* pZoomFactor);
}
#Override
public void onPinchZoomFinished(final PinchZoomDetector pPinchZoomDetector,
final TouchEvent pTouchEvent, final float pZoomFactor) {
this.camera.setZoomFactor(this.mPinchZoomStartedCameraZoomFactor
* pZoomFactor);
}
#Override
public boolean onSceneTouchEvent(final Scene pScene,
final TouchEvent pSceneTouchEvent) {
this.mPinchZoomDetector.onTouchEvent(pSceneTouchEvent);
if (this.mPinchZoomDetector.isZooming()) {
this.mScrollDetector.setEnabled(false);
} else {
if (pSceneTouchEvent.isActionDown()) {
this.mScrollDetector.setEnabled(true);
}
this.mScrollDetector.onTouchEvent(pSceneTouchEvent);
}
return true;
}
}
I had the same problem for realize an indoor program.
I found a way to make better the display by editing directly the .tmx file.
In the tileset you should add those attributes spacing and margin.
For example:
tileset spacing="3" margin="2"
If you put the good value in the diferent field, you should have a better display.
My problem was resolved just by adding a margin=10 in this tileset.
I hope that help you,

how to open another class by clicking on a button on libgdx? (android development eclipse)

I am making my own game. I have already made a splash screen and a main menu. I have made a button "Play" in my menu but I can't link it to my main game, while I can link it to other classes.
Here is the code of the class I can't open:
package com.mygdx.Papermadness.screens;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureWrap;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.Vector2;
public class PaperMadness extends InputAdapter implements ApplicationListener, Screen {
float timer;
public static Preferences prefs;
public static int counter; // The variable you want to save
private BitmapFont font;
//public int counter = 0;
boolean touch = false;
SpriteBatch batch;
SpriteBatch spriteBatch;
Texture spriteTexture;
Sprite sprite;
float scrollTimer = 0.0f;
Player player;
Paper paper;
Huiz huiz;
Lijn lijn;
String money = String.valueOf(counter);
ShapeRenderer sr;
public boolean kukar = false;
public void create() {
font = new BitmapFont();
Gdx.input.setInputProcessor(this);
player = new Player(new Vector2(50, 100), new Vector2(100, 100));
huiz = new Huiz(new Vector2(200, 300), new Vector2(110, 110));
// huiz = new Huiz(new Vector2(200, 300), new Vector2(110, 110));
paper = new Paper(new Vector2(Gdx.input.getX(),
Gdx.graphics.getHeight() - Gdx.input.getY()), new Vector2(50,
50));
lijn = new Lijn(new Vector2(0, 200), new Vector2(600, 2));
// sr = new ShapeRenderer();
spriteBatch = new SpriteBatch();
spriteTexture = new Texture("b9.png");
spriteTexture.setWrap(TextureWrap.Repeat, TextureWrap.Repeat);
sprite = new Sprite(spriteTexture);
sprite.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch = new SpriteBatch();
}
#Override
public void render(float delta) {
// bounds.set(Gdx.input.getX(),
// Gdx.graphics.getHeight() - Gdx.input.getY(),
// secondTexture.getWidth(), secondTexture.getHeight());
scrollTimer += Gdx.graphics.getDeltaTime();
if (scrollTimer > 1.0f)
scrollTimer = 0.0f;
sprite.setV(scrollTimer + 2);
sprite.setV2(scrollTimer);
player.update();
paper.update();
lijn.update();
huiz.update();
/*
* if (tree.getBounds().overlaps(ball.getBounds())) {
* System.out.println("Swendley Programinateur"); }
*
* if (tree.getBounds().overlaps(paper.getBounds())) {
* System.out.println("Souk Programinateur"); }
*/
spriteBatch.begin();
sprite.draw(spriteBatch);
spriteBatch.end();
batch.begin();
player.draw(batch);
huiz.draw(batch);
// paper.draw(batch);
if (Gdx.graphics.getHeight() / 1.25 < Gdx.input.getY()
&& Gdx.graphics.getWidth() / 2.7 < Gdx.input.getX()
&& Gdx.graphics.getWidth() / 1.7 > Gdx.input.getX()
&& Gdx.input.isTouched() && kukar == false && touch == false) {
kukar = true;
touch = true;
} else if (Gdx.input.isTouched() && kukar == true && touch == true) {
paper.draw(batch);
if (paper.getBounds().overlaps(huiz.getBounds())
|| paper.getBounds().overlaps(huiz.getBounds1())) {
// System.out.println("Huis Geraakt!");
touch = false;
counter++;
checkSpeed();
money = Integer.toString(counter);
// System.out.println(counter);
}
}
if (huiz.getBounds().overlaps(lijn.getBounds())
|| huiz.getBounds1().overlaps(lijn.getBounds())){
//System.out.println("Game Over");
}
font.draw(batch, money, Gdx.graphics.getWidth() / 2.06f,
Gdx.graphics.getHeight() / 1.05f);
font.setColor(Color.BLACK);
font.setScale(2, 2);
// house.draw(batch);
// house1.draw(batch);
lijn.draw(batch);
batch.end();
// sr.begin(ShapeType.Filled);
// sr.setColor(Color.YELLOW);
// sr.rect(Gdx.input.getX(), Gdx.graphics.getHeight() -
// Gdx.input.getY(),
// paper.getSize().x, paper.getSize().y);
// sr.setColor(Color.BLACK);
// sr.rect(huiz.getPosition().x, huiz.getPosition().y,
// huiz.getSize().x, huiz.getSize().y);
// sr.rect(house1.getPosition().x, house1.getPosition().y,
// house1.getSize().x, house1.getSize().y);
// sr.end();
}
public static void savePrefs(){
prefs = Gdx.app.getPreferences("game-prefs"); // The name of your prefs files
prefs.putInteger("counter", counter);
prefs.flush();
System.out.println(prefs);
}
public static void loadPrefs(){
prefs = Gdx.app.getPreferences("game-prefs");
counter = prefs.getInteger("counter",0); //Load counter, default to zero if not found
}
public void checkSpeed() {
if (counter <= 7) {
huiz.huisVelocity = 500f;
}
if (counter > 7 && counter <= 17) {
huiz.huisVelocity = 550f;
}
if (counter > 17 && counter <= 30) {
huiz.huisVelocity = 650f;
}
if (counter > 30 && counter <= 50) {
huiz.huisVelocity = 750;
}
if (counter > 50 && counter <= 75) {
huiz.huisVelocity = 900;
}
if (counter > 75 && counter <= 100) {
huiz.huisVelocity = 1000;
}
}
#Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
kukar = false;
touch = false;
return true;
}
#Override
public void resize(int width, int height) {
}
#Override
public void show() {
}
#Override
public void hide() {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
}
#Override
public void render() {
}
}
Here is the menu class:
package com.mygdx.Papermadness.screens;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.mygdx.Papermadness.Papermadness;
public class MainMenu implements Screen {
private Stage stage;// done
private TextureAtlas atlas;// done
private Skin skin;// done
private Table table;// done
private TextButton buttonPlay, buttonExit;
private BitmapFont white, black;// done
private Label heading;
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
Table.drawDebug(stage);
stage.act(delta);
stage.draw();
}
#Override
public void resize(int width, int height) {
}
#Override
public void show() {
stage = new Stage();
Gdx.input.setInputProcessor(stage);
atlas = new TextureAtlas("ui/button.pack");
skin = new Skin(atlas);
table = new Table(skin);
table.setBounds(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
white = new BitmapFont(Gdx.files.internal("font/white.fnt"), false);
black = new BitmapFont(Gdx.files.internal("font/black.fnt"), false);
// maakt buttons
TextButtonStyle textButtonStyle = new TextButtonStyle();
textButtonStyle.up = skin.getDrawable("button.up");
textButtonStyle.down = skin.getDrawable("button.down");
textButtonStyle.pressedOffsetX = 1;
textButtonStyle.pressedOffsetY = -1;
textButtonStyle.font = black;
buttonExit = new TextButton("EXIT", textButtonStyle);
buttonExit.addListener(new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
Gdx.app.exit();
}
});
buttonExit.pad(15);
buttonPlay = new TextButton("PlAY", textButtonStyle);
buttonPlay.addListener(new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
((Game) Gdx.app.getApplicationListener())
.setScreen(new PaperMadness());
}
});
buttonPlay.pad(15);
// maakt header
heading = new Label(Papermadness.TITLE, new LabelStyle(white,
Color.WHITE));
heading.setFontScale(2);
table.add(heading);
table.getCell(heading).spaceBottom(100);
table.row();
table.add(buttonPlay);
table.getCell(buttonPlay).spaceBottom(15);
table.row();
table.add(buttonExit);
// table.debug();
stage.addActor(table);
}
#Override
public void hide() {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
stage.dispose();
atlas.dispose();
skin.dispose();
white.dispose();
black.dispose();
}
}
public class MyGdxGame extends Game{
public static MenuScreen menuScreen;
public static GameScreen gameScreen;
#Override
public void create(){
menuScreen = new MenuScreen(this);
gameScreen = new GameScreen (this);
setScreen(menuScreen);
}
}
Here is MenuScreen
public class MenuScreen implements Screen{
MyGdxGame game;
public MenuScreen(MyGdxGame game){
this.game = game;
}
////////////when you want to change screen type game.setScreen(game.gameScreen)
...........
...........
}
and this is GameScreen
public class GameScreen implements Screen{
...........
...........
...........
}
this is a simple example , try to do the same in your code.
Here is a good tutorial
https://github.com/libgdx/libgdx/wiki/Extending-the-simple-game
If it helped , let me know about it.

Categories

Resources