How to share data from Activity extended class to View extended class? - java

I wanted to create a game in which one could move a ball in a labyrinth using accelerometer sensor. In one of the classes extending from View I have the labyrinth, the ball, the goal and a method which draws them, a method which controls the movement of the ball.
package pl.wsiz.greatlabyrinth;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.Random;
import java.util.Stack;
public class GameView extends View {
private enum Direction{
up, down, left, right
}
private Cell[][] cells;
private Cell player, exit;
private static final int columns = 11, rows = 20;
private static final float wallThickness = 5;
private float cellSize, hMargin, vMargin;
private Paint wallPaint, playerPaint, exitPaint;
private Random random;
public GameView(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
wallPaint = new Paint();
wallPaint.setColor(Color.BLACK);
wallPaint.setStrokeWidth(wallThickness);
playerPaint = new Paint();
playerPaint.setColor(Color.RED);
exitPaint = new Paint();
exitPaint.setColor(Color.BLUE);
random = new Random();
createLabyrinth();
}
private Cell getNeighbour(Cell cell){
ArrayList<Cell> neighbours = new ArrayList<>();
//left neighbour
if(cell.column > 0) {
if (!cells[cell.column - 1][cell.row].visited) {
neighbours.add(cells[cell.column - 1][cell.row]);
}
}
//right neighbour
if(cell.column < columns-1) {
if (!cells[cell.column + 1][cell.row].visited) {
neighbours.add(cells[cell.column + 1][cell.row]);
}
}
//top neighbour
if(cell.row > 0) {
if (!cells[cell.column][cell.row - 1].visited) {
neighbours.add(cells[cell.column][cell.row - 1]);
}
}
//bottom neighbour
if(cell.row < rows-1) {
if (!cells[cell.column][cell.row + 1].visited) {
neighbours.add(cells[cell.column][cell.row + 1]);
}
}
if(neighbours.size() > 0) {
int index = random.nextInt(neighbours.size());
return neighbours.get(index);
}
return null;
}
private void removeWall(Cell current, Cell next){
if(current.column == next.column && current.row == next.row+1) {
current.topWall = false;
next.bottomWall = false;
}
if(current.column == next.column && current.row == next.row-1) {
current.bottomWall = false;
next.topWall = false;
}
if(current.column == next.column+1 && current.row == next.row) {
current.leftWall = false;
next.rightWall = false;
}
if(current.column == next.column-1 && current.row == next.row) {
current.rightWall = false;
next.leftWall = false;
}
}
private void createLabyrinth(){
Stack<Cell> stack = new Stack<>();
Cell current, next;
cells = new Cell[columns][rows];
for(int i=0; i<columns; i++){
for(int j=0; j<rows;j++){
cells[i][j] = new Cell(i, j);
}
}
player = cells[0][0];
exit = cells[columns-1][rows-1];
current = cells[0][0];
current.visited = true;
do {
next = getNeighbour(current);
if (next != null) {
removeWall(current, next);
stack.push(current);
current = next;
current.visited = true;
} else
current = stack.pop();
}while(!stack.empty());
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
int width = getWidth();
int height = getHeight();
if(width/height < columns/rows) {
cellSize = width/(columns+3);
}
else {
cellSize = height/(rows+3);
}
hMargin = (width-columns*cellSize)/2;
vMargin = (height-rows*cellSize)/2;
canvas.translate(hMargin, vMargin);
for(int i=0; i<columns; i++){
for(int j=0; j<rows;j++){
if(cells[i][j].topWall)
canvas.drawLine(i*cellSize, j*cellSize, (i+1)*cellSize,j*cellSize, wallPaint);
if(cells[i][j].leftWall)
canvas.drawLine(i*cellSize, j*cellSize, i*cellSize,(j+1)*cellSize, wallPaint);
if(cells[i][j].bottomWall)
canvas.drawLine(i*cellSize, (j+1)*cellSize, (i+1)*cellSize,(j+1)*cellSize, wallPaint);
if(cells[i][j].rightWall)
canvas.drawLine((i+1)*cellSize, j*cellSize, (i+1)*cellSize,(j+1)*cellSize, wallPaint);
}
}
float margin = cellSize/2;
canvas.drawCircle(player.column*cellSize+margin, player.row*cellSize+margin,(cellSize/2)-5, playerPaint);
canvas.drawCircle(exit.column*cellSize+margin, exit.row*cellSize+margin,(cellSize/2)-5, exitPaint);
}
private void movePlayer(Direction direction){
switch (direction){
case up:
if(!player.topWall)
player = cells[player.column][player.row-1];
break;
case down:
if(!player.bottomWall)
player = cells[player.column][player.row+1];
break;
case left:
if(!player.leftWall)
player = cells[player.column-1][player.row];
break;
case right:
if(!player.rightWall)
player = cells[player.column+1][player.row];
break;
}
checkExit();
invalidate();
}
private void checkExit(){
if(player == exit)
createLabyrinth();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
return true;
if(event.getAction() == MotionEvent.ACTION_MOVE){
float x = event.getX();
float y = event.getY();
float playerCenterX = hMargin + (player.column+0.5f)*cellSize;
float playerCenterY = vMargin + (player.row+0.5f)*cellSize;
float xDirection = x - playerCenterX;
float yDirection = y - playerCenterY;
float absXD = Math.abs(xDirection);
float absYD = Math.abs(yDirection);
if(absXD > cellSize || absYD > cellSize){
if(absXD>absYD){
//move in x-direction
if(xDirection>0){
movePlayer(Direction.right);
}
else{
movePlayer(Direction.left);
}
}
else {
//move in y-direction
if (yDirection > 0) {
movePlayer(Direction.down);
} else {
movePlayer(Direction.up);
}
}
}
return true;
}
return super.onTouchEvent(event);
}
private class Cell {
boolean leftWall = true;
boolean rightWall = true;
boolean topWall = true;
boolean bottomWall = true;
boolean visited = false;
int column, row;
public Cell(int column, int row) {
this.column = column;
this.row = row;
}
}
}
In the second class extending AppCompatActivity I have the code of accelerometer to be used in moving the ball.
package pl.wsiz.greatlabyrinth;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
public class GameActivity extends AppCompatActivity implements SensorEventListener {
private SensorManager sensorManager;
private Sensor accelerometr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
accelerometr = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}
#Override
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, accelerometr, SensorManager.SENSOR_DELAY_GAME);
}
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
}
I do not know how to join accelerometer with the first quoted code so that the ball moves using sensor and not onTouchEvent method. I would be grateful for some code with a little explanation.

Related

Draw Line in View using Vector (in Android Studio)

I'm trying to draw a line, I managed to do it before but the first point somehow was always 0, 0. Now my logic is, there are two Vectors, one to store each point that is clicked, and another to store the Line, which is made by two points clicked by the user. I do the verifications to see if the Vector is not empty and only then I draw the line. I don't really know what's going on, I've tried everything, hope some of you can help, I'm in real need. Thank you.
Here it goes the code from MyView.java:
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import java.util.Vector;
public class MyView extends View {
Paint paint = null;
int figure;
int lados_poly;
int cor;
int deletar;
int CursorX, CursorY;
int nrCliques;
Vector<Ponto2D> ptsReta = new Vector<Ponto2D>();
Vector<Reta> guardaRetas = new Vector<Reta>();
public MyView(Context context) {
super(context);
paint = new Paint();
figure = 0;
cor = 0;
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
paint.setStrokeWidth(10);
figure = 0;
cor = 0;
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
paint = new Paint();
figure = 0;
cor = 0;
}
public void clickEcra() {
setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
CursorX = (int)event.getX();
CursorY = (int)event.getY();
if (figure == 2){
Ponto2D ptReta = new Ponto2D();
ptReta.x = CursorX;
ptReta.y = CursorY;
ptsReta.add(ptReta);
if (ptsReta.size()> 0) {
for (int c = 0; c < ptsReta.size(); c++)
System.out.println("ptRetaX: " + ptsReta.get(c).x + " ptRetaY: " + ptsReta.get(c).y + " size " + ptsReta.size());
}
invalidate();
}
default:
return false;
}
}
});
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
clickEcra();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.parseColor("#F5F1E0"));
canvas.drawPaint(paint);
paint.setColor(Color.parseColor("#3F5866"));
//cores
if (cor == 1) {
paint.setColor(Color.parseColor("#393E46"));
} else if (cor == 2){
paint.setColor(Color.parseColor("#00ADB5"));
} else if (cor == 3) {
paint.setColor(Color.parseColor("#F8B500"));
} else if (cor == 4) {
paint.setColor(Color.parseColor("#FC3C3C"));
}
if (figure == 2) {
if (ptsReta.size() >= 2) {
for (int b = 0; b < ptsReta.size(); b = b + 2) {
Reta retinha = new Reta(ptsReta.get(b), ptsReta.get(b + 1));
guardaRetas.add(retinha);
System.out.println("pts: " + ptsReta.get(b) + ptsReta.get(b + 1));
}
}
if (guardaRetas.size() > 0) {
for (int r = 0; r < guardaRetas.size(); r++) {
canvas.drawLine(guardaRetas.get(r).pinicial.x, guardaRetas.get(r).pinicial.y, guardaRetas.get(r).pfinal.x, guardaRetas.get(r).pfinal.y, paint);
}
}
}
//clear canvas
if (deletar == 2){
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.parseColor("#F5F1E0"));
canvas.drawPaint(paint);
nrCliques = 0;
ptsCirc.removeAllElements();
ptsReta.removeAllElements();
}
}
public void setfigure(int a) {
this.figure = a;
}
public void Cor1_mudar(int text_cor) {
this.cor = text_cor;
}
public void Resetar(int delete){
this.deletar = delete;
}
}
And now the code from Line.java:
public class Reta {
Ponto2D pinicial;
Ponto2D pfinal;
public Reta(){
pinicial = new Ponto2D();
pfinal = new Ponto2D();
}
public Reta(Ponto2D a, Ponto2D b) {
pinicial = a;
pfinal = b;
}
}
Update: It draws one line, and when I try to do another one, on the third click, it closes and I need to draw multiple lines in my canvas.
This were my changes, the following inside onDraw() method:
if (figure == 2) {
if (ptsReta.size() %2 == 0) {
for (int b = 0; b < ptsReta.size(); b = b + 2) {
Reta retinha = new Reta(ptsReta.get(b), ptsReta.get(b + 1));
guardaRetas.add(retinha);
}
if (guardaRetas.size() > 0) {
for (int r = 0; r < guardaRetas.size(); r++) {
canvas.drawLine(guardaRetas.get(r).pinicial.x, guardaRetas.get(r).pinicial.y, guardaRetas.get(r).pfinal.x, guardaRetas.get(r).pfinal.y, paint);
}
}
}
}
And this ones inside the click method:
public void clickEcra() {
setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
CursorX = (int)event.getX();
CursorY = (int)event.getY();
if (figure == 2){
Ponto2D ptReta = new Ponto2D();
ptReta.x = CursorX;
ptReta.y = CursorY;
ptsReta.add(ptReta);
invalidate();
}
default:
return false;
}
}
});
}

Starting another activity on collision detection

Okay, so I need to start another activity on collision detection, I am a beginner trying to make this simple game and I just cannot figure this out ... It is marked by //This is the place I am trying to start another activity, where I want to start it, the current code gives me error
GameView.java file where I need to start the activity
package fi.itsn.jetfighter;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.util.ArrayList;
import static android.support.v4.app.ActivityCompat.startActivity;
/**
* Created by h on 21.9.2016.
*/
public class GameView extends SurfaceView implements Runnable {
volatile boolean playing;
private Thread gameThread = null;
private Player player;
private Paint paint;
private Canvas canvas;
private SurfaceHolder surfaceHolder;
private Enemy[] enemies;
private Broccoli[] broccolis;
private int enemyCount = 3;
private int broccoliCount = 1;
private ArrayList<Star> stars = new
ArrayList<Star>();
//defining a boom object to display blast
private Boom boom;
public GameView(Context context, int screenX, int screenY) {
super(context);
player = new Player(context, screenX, screenY);
surfaceHolder = getHolder();
paint = new Paint();
int starNums = 100;
for (int i = 0; i < starNums; i++) {
Star s = new Star(screenX, screenY);
stars.add(s);
}
enemies = new Enemy[enemyCount];
for (int i = 0; i < enemyCount; i++) {
enemies[i] = new Enemy(context, screenX, screenY);
}
//initializing boom object
boom = new Boom(context);
broccolis = new Broccoli[broccoliCount];
for (int i = 0; i < broccoliCount; i++) {
broccolis[i] = new Broccoli(context, screenX, screenY);
}
}
#Override
public void run() {
while (playing) {
update();
draw();
control();
}
}
private void update() {
player.update();
//setting boom outside the screen
boom.setX(-250);
boom.setY(-250);
for (Star s : stars) {
s.update(player.getSpeed());
}
for (int i = 0; i < enemyCount; i++) {
enemies[i].update(player.getSpeed());
//if collision occurrs with player
if (Rect.intersects(player.getDetectCollision(), enemies[i].getDetectCollision())) {
//displaying boom at that location
boom.setX(enemies[i].getX());
boom.setY(enemies[i].getY());
enemies[i].setX(-200);
}
}
for (int i = 0; i < broccoliCount; i++) {
broccolis[i].update(player.getSpeed());
if (Rect.intersects(player.getDetectCollision(), broccolis[i].getDetectCollision())) {
startActivity(new Intent(this, end.class));
//This is the place I am trying to start another activity
}
}
}
private void draw() {
if (surfaceHolder.getSurface().isValid()) {
canvas = surfaceHolder.lockCanvas();
canvas.drawColor(Color.BLUE);
paint.setColor(Color.WHITE);
for (Star s : stars) {
paint.setStrokeWidth(s.getStarWidth());
canvas.drawPoint(s.getX(), s.getY(), paint);
}
canvas.drawBitmap(
player.getBitmap(),
player.getX(),
player.getY(),
paint);
for (int i = 0; i < enemyCount; i++) {
canvas.drawBitmap(
enemies[i].getBitmap(),
enemies[i].getX(),
enemies[i].getY(),
paint
);
}
for (int i = 0; i < broccoliCount; i++) {
canvas.drawBitmap(
broccolis[i].getBitmap(),
broccolis[i].getX(),
broccolis[i].getY(),
paint
);
}
//drawing boom image
canvas.drawBitmap(
boom.getBitmap(),
boom.getX(),
boom.getY(),
paint
);
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
private void control() {
try {
gameThread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void pause() {
playing = false;
try {
gameThread.join();
} catch (InterruptedException e) {
}
}
public void resume() {
playing = true;
gameThread = new Thread(this);
gameThread.start();
}
#Override
public boolean onTouchEvent(MotionEvent motionEvent) {
switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_UP:
player.stopBoosting();
break;
case MotionEvent.ACTION_DOWN:
player.setBoosting();
break;
}
return true;
}
}
And here is the Broccoli.java file
package fi.itsn.jetfighter;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import java.util.Random;
/**
* Created by h on 22.9.2016.
*/
public class Broccoli {
//bitmap for the enemy
//we have already pasted the bitmap in the drawable folder
private Bitmap bitmap;
private int x;
private int y;
private int speed = 1;
private int maxX;
private int minX;
private int maxY;
private int minY;
//creating a rect object
private Rect detectCollision;
public Broccoli(Context context, int screenX, int screenY) {
bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.broccoli);
maxX = screenX;
maxY = screenY;
minX = 0;
minY = 0;
Random generator = new Random();
speed = generator.nextInt(6) + 10;
x = screenX;
y = generator.nextInt(maxY) - bitmap.getHeight();
//initializing rect object
detectCollision = new Rect(x, y, bitmap.getWidth(), bitmap.getHeight());
}
public void update(int playerSpeed) {
x -= playerSpeed;
x -= speed;
if (x < minX - bitmap.getWidth()) {
Random generator = new Random();
speed = generator.nextInt(10) + 10;
x = maxX;
y = generator.nextInt(maxY) - bitmap.getHeight();
}
//Adding the top, left, bottom and right to the rect object
detectCollision.left = x;
detectCollision.top = y;
detectCollision.right = x + bitmap.getWidth();
detectCollision.bottom = y + bitmap.getHeight();
}
//adding a setter to x coordinate so that we can change it after collision
public void setX(int x){
this.x = x;
}
//one more getter for getting the rect object
public Rect getDetectCollision() {
return detectCollision;
}
//getters
public Bitmap getBitmap() {
return bitmap;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getSpeed() {
return speed;
}
}
Try with
startActivity(new Intent(getContext(), end.class));
You need to pass context not this. Here you are extending a class with SurfaceView not Activity so this won't give you context like it gives in Activity
OR
Because you are passing context in constructor so you can also do it like
public GameView(Context context, int screenX, int screenY) {{
super(context);
this.mContext = context;
}
and pass this mContext in Intent
startActivity(new Intent(mContext, end.class));

Path drawing. in android studio

I am trying to implement path drawing for a herding game.
Currently when I run the game on PC I use the mouse to draw a path for which the herder will move through, but I can not get it to draw a line.
package com.mygdx.herdergame.Sprites;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.utils.Array;
import com.mygdx.herdergame.HerderGame;
import com.mygdx.herdergame.Screens.PlayScreen;
import java.util.ArrayList;
public class Herder extends Sprite implements InputProcessor {
HerderGame game;
public World world;
public Body b2body;
private PlayScreen screen;
//States
private enum State {
RUNNINGRIGHT, RUNNINGLEFT, RUNNINGUP, RUNNINGDOWN, STANDINGRIGHT, STANDINGLEFT, STANDINGUP, STANDINGDOWN
}
private State currentState;
private State previousState;
private float stateTimer;
//Textures
private Animation runningRight;
private Animation runningLeft;
private Animation runningUp;
private Animation runningDown;
private TextureRegion standRight;
private TextureRegion standLeft;
private TextureRegion standUp;
private TextureRegion standDown;
private float destinationX;
private float destinationY;
//Velocity
private static final float MAX_SPEED = 500;
private float speedLimit = 1000;
private Vector2 velocity = new Vector2(0, 0);
private static float ACCURACY = 50;
//Touch Screen
private Vector3 touchpoint = new Vector3();
private Vector2 targetPosition;
private ArrayList<Vector2> herderPath = new ArrayList<Vector2>();
boolean dragging;
boolean followingPath = false;
// death variables
private boolean isInTimedDeathZone;
private float deathTimer;
//this is the constructor.
public Herder(World world, PlayScreen screen) {
super(screen.getAtlas().findRegion("herderRight"));
this.screen = screen;
game = screen.getGame();
this.world = world;
defBody();
setTextures();
currentState = State.STANDINGRIGHT;
previousState = State.STANDINGRIGHT;
stateTimer = 0;
isInTimedDeathZone = false;
deathTimer = 0;
}
public void defBody() {
BodyDef bdef = new BodyDef();
bdef.position.set(500, 500);
bdef.type = BodyDef.BodyType.DynamicBody;
b2body = world.createBody(bdef);
FixtureDef fdef = new FixtureDef();
CircleShape shape = new CircleShape();
shape.setRadius(10);
fdef.shape = shape;
b2body.createFixture(fdef).setUserData(this);
}
public void setTextures() {
int herderUpStartX = game.rm.getChapter(game.getCurrentChapter()).getHerderUp().getStartX();
int herderUpStartY = game.rm.getChapter(game.getCurrentChapter()).getHerderUp().getStartY();
int herderDownStartX = game.rm.getChapter(game.getCurrentChapter()).getHerderDown().getStartX();
int herderDownStartY = game.rm.getChapter(game.getCurrentChapter()).getHerderDown().getStartY();
int herderLeftStartX = game.rm.getChapter(game.getCurrentChapter()).getHerderLeft().getStartX();
int herderLeftStartY = game.rm.getChapter(game.getCurrentChapter()).getHerderLeft().getStartY();
int herderRightStartX = game.rm.getChapter(game.getCurrentChapter()).getHerderRight().getStartX();
int herderRightStartY = game.rm.getChapter(game.getCurrentChapter()).getHerderRight().getStartY();
int numberOfFrame = game.rm.getChapter(game.getCurrentChapter()).getHerderRight().getNumberOfFrame();
int width = game.rm.getChapter(game.getCurrentChapter()).getHerderRight().getWidth();
int height = game.rm.getChapter(game.getCurrentChapter()).getHerderRight().getHeight();
//this enables the sprite to be drawn.
Array<TextureRegion> frames = new Array<TextureRegion>();
for (int i = 0; i < numberOfFrame; i++) {
frames.add(new TextureRegion(getTexture(), herderRightStartX + width * i, herderRightStartY, width, height));
}
runningRight = new Animation(0.1f, frames);
frames.clear();
for (int i = 0; i < numberOfFrame; i++) {
frames.add(new TextureRegion(getTexture(), herderLeftStartX + width * i, herderLeftStartY, width, height));
}
runningLeft = new Animation(0.1f, frames);
frames.clear();
for (int i = 0; i < numberOfFrame; i++) {
frames.add(new TextureRegion(getTexture(), herderDownStartX + width * i, herderDownStartY, width, height));
}
runningDown = new Animation(0.1f, frames);
frames.clear();
for (int i = 0; i < numberOfFrame; i++) {
frames.add(new TextureRegion(getTexture(), herderUpStartX + width * i, herderUpStartY, width, height));
}
runningUp = new Animation(0.1f, frames);
standRight = new TextureRegion(getTexture(), herderRightStartX, herderRightStartY, width, height);
setBounds(0, 0, 32, 32);
setRegion(standRight);
standLeft = new TextureRegion(getTexture(), herderLeftStartX, herderLeftStartY, width, height);
setBounds(0, 0, 32, 32);
setRegion(standLeft);
standUp = new TextureRegion(getTexture(), herderUpStartX, herderUpStartY, width, height);
setBounds(0, 0, 32, 32);
setRegion(standUp);
standDown = new TextureRegion(getTexture(), herderDownStartX, herderDownStartY, width, height);
setBounds(0, 0, 32, 32);
setRegion(standDown);
setSize(32, 32);
}
public TextureRegion getFrame(float dt) {
currentState = getState();
TextureRegion region;
switch (currentState) {
case RUNNINGRIGHT:
region = runningRight.getKeyFrame(stateTimer, true);
break;
case RUNNINGLEFT:
region = runningLeft.getKeyFrame(stateTimer, true);
break;
case RUNNINGUP:
region = runningUp.getKeyFrame(stateTimer, true);
break;
case RUNNINGDOWN:
region = runningDown.getKeyFrame(stateTimer, true);
break;
case STANDINGLEFT:
region = standLeft;
break;
case STANDINGUP:
region = standUp;
break;
case STANDINGDOWN:
region = standDown;
break;
case STANDINGRIGHT:
default:
region = standRight;
break;
}
stateTimer = currentState == previousState ? stateTimer + dt : 0;
previousState = currentState;
return region;
}
public State getState() {
Vector2 direction = b2body.getLinearVelocity();
if (direction.isZero()) {
switch (previousState) {
case RUNNINGUP:
return State.STANDINGUP;
case RUNNINGLEFT:
return State.STANDINGLEFT;
case RUNNINGDOWN:
return State.STANDINGDOWN;
case RUNNINGRIGHT:
return State.STANDINGRIGHT;
default:
return previousState;
}
} else if (direction.x >= 0 && direction.y >= 0) {
if (direction.x > direction.y) {
return State.RUNNINGRIGHT;
} else return State.RUNNINGUP;
} else if (direction.x >= 0 && direction.y <= 0) {
if (direction.x > -direction.y) {
return State.RUNNINGRIGHT;
} else return State.RUNNINGDOWN;
} else if (direction.x <= 0 && direction.y >= 0) {
if (-direction.x > direction.y) {
return State.RUNNINGLEFT;
} else return State.RUNNINGUP;
} else if (direction.x <= 0 && direction.y <= 0) {
if (-direction.x > -direction.y) {
return State.RUNNINGLEFT;
} else return State.RUNNINGDOWN;
} else return currentState = previousState;
}
public void update(float dt) {
if (isXStapable() || isYStapable()) {
stop();
}
if (followingPath) {
if (!herderPath.iterator().hasNext()) {
followingPath = false;
herderPath.clear();
stop();
} else if (targetPosition.dst(b2body.getPosition()) < 1.5) {
targetPosition = herderPath.get(0);
herderPath.remove(0);
velocity = calculateVelocity(b2body.getPosition(), targetPosition);
} else {
velocity = calculateVelocity(b2body.getPosition(), targetPosition);
}
}
b2body.setLinearVelocity(velocity);
setPosition(b2body.getPosition().x - getWidth() / 2, b2body.getPosition().y - getHeight() / 2);
setRegion(getFrame(dt));
if (isInTimedDeathZone) {
deathTimer += dt;
} else {
deathTimer = 0;
}
if (deathTimer > 2f) {
screen.gameOver();
}
}
public void setInTimedDeathZone(boolean b) {
this.isInTimedDeathZone = b;
}
#Override
public boolean keyDown(int keycode) {
switch (keycode) {
case Input.Keys.UP:
velocity.y = speedLimit;
break;
case Input.Keys.DOWN:
velocity.y = -speedLimit;
break;
case Input.Keys.LEFT:
velocity.x = -speedLimit;
break;
case Input.Keys.RIGHT:
velocity.x = speedLimit;
break;
default:
return true;
}
followingPath = false;
return true;
}
#Override
public boolean keyUp(int keycode) {
switch (keycode) {
case Input.Keys.UP:
case Input.Keys.DOWN:
velocity.y = 0;
break;
case Input.Keys.LEFT:
case Input.Keys.RIGHT:
velocity.x = 0;
break;
}
return true;
}
#Override
public boolean keyTyped(char character) {
return false;
}
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
float diffX;
float diffY;
// ignore if its not left mouse button or first touch pointer
if (button != Input.Buttons.LEFT || pointer > 0) return false;
screen.getCamera().unproject(touchpoint.set(screenX, screenY, 0));
//ignore if the first point is not close to the herder
diffX = touchpoint.x - b2body.getPosition().x;
diffY = touchpoint.y - b2body.getPosition().y;
if (diffX > 25 || diffX < -25 || diffY > 25 || diffY < -25) return false;
dragging = true;
herderPath.clear();
targetPosition = b2body.getPosition();
herderPath.add(targetPosition);
return true;
}
#Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
Vector2 vec2 = new Vector2();
if (!dragging) return false;
screen.getCamera().unproject(touchpoint.set(screenX, screenY, 0));
vec2.set(touchpoint.x, touchpoint.y);
herderPath.add(vec2);
followingPath = true;
return true;
}
#Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
if (button != Input.Buttons.LEFT || pointer > 0) return false;
screen.getCamera().unproject(touchpoint.set(screenX, screenY, 0));
dragging = false;
return true;
}
private Vector2 calculateVelocity(Vector2 currentPosition, Vector2 targetPosition) {
Vector2 tempTP = new Vector2().set(targetPosition);
return tempTP.sub(currentPosition).nor().scl(speedLimit);
}
public boolean isXValid(int x) {
return b2body.getPosition().x <= x + ACCURACY && b2body.getPosition().x >= x - ACCURACY;
}
public boolean isYValid(int y) {
return b2body.getPosition().y <= y + ACCURACY && b2body.getPosition().y >= y - ACCURACY;
}
public boolean isXStapable() {
return isXValid((int) destinationX);
}
public boolean isYStapable() {
return isYValid((int) destinationY);
}
public void stop() {
velocity.set(0, 0);
}
#Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
#Override
public boolean scrolled(int amount) {
return false;
}
public void setSpeedLimit(float multiplier) {
if (speedLimit > MAX_SPEED) {
this.speedLimit = MAX_SPEED;
} else {
this.speedLimit = multiplier;
}
}
}

Background moves farther and faster than anything else

OK, So Im drawing a bitmap beneath everything else for my background. Whenever the player moves it moves the enemy array 1 px and its supposed to do the same for the background. But whenever I move the background goes way faster and farther than everything else in the game. Can anyone tell me whats causing this? Heres the code. The code that moves everything is at the bottom in the set direction method.
package com.gametest;
import java.util.concurrent.CopyOnWriteArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
public class GameSurfaceView extends Activity implements OnTouchListener {
double ran;
int touchX, touchY, screenWidth, screenHeight, objX, objY;
static int bgx, bgy, bgW, bgH, enemyCount, score, playerHealth;
static boolean canUpdate;
static MyView v;
static Bitmap orb, orb2, explosion, bg;
static CopyOnWriteArrayList<Sprite> copy = new CopyOnWriteArrayList<Sprite>();
static String hpString;
static Player player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
v = new MyView(this);
v.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent me) {
switch (me.getAction()) {
case MotionEvent.ACTION_DOWN:
return true;
case MotionEvent.ACTION_MOVE:
return true;
case MotionEvent.ACTION_UP:
touchX = (int) me.getX();
touchY = (int) me.getY();
for (Sprite sprite : copy) {
sprite.checkTouch(touchX, touchY);
return true;
}
}
return true;
}
});
canUpdate = true;
screenWidth = v.getWidth();
screenHeight = v.getHeight();
playerHealth = 250;
hpString = "Health " + playerHealth;
ran = 0;
score = 0;
orb = BitmapFactory.decodeResource(getResources(), R.drawable.blue_orb);
orb2 = BitmapFactory.decodeResource(getResources(), R.drawable.red_orb);
bg = BitmapFactory.decodeResource(getResources(), R.drawable.bg1);
bgx = bg.getHeight()/2;
bgy = bg.getHeight()/2;
bgH = bg.getHeight();
bgW = bg.getWidth();
explosion = BitmapFactory.decodeResource(getResources(), R.drawable.explosion);
player = new Player(v, orb2, explosion, screenWidth, screenHeight);
createEnemies();
setContentView(v);
}
private void createEnemies() {
if (enemyCount < 5) {
screenWidth = v.getWidth();
screenHeight = v.getHeight();
copy.add(new Sprite(v, orb, explosion, screenWidth, screenHeight, copy.size()));
enemyCount++;
}
}
public static void checkECount(int id) {
canUpdate = false;
copy.remove(id);
enemyCount--;
CopyOnWriteArrayList<Sprite> c = new CopyOnWriteArrayList<Sprite>();
int index = 0;
for (Sprite s : copy) {
s.ID = index;
c.add(s);
index++;
}
score = score + 10;
copy = c;
canUpdate = true;
}
#Override
protected void onPause() {
super.onPause();
v.pause();
}
#Override
protected void onResume() {
super.onResume();
v.resume();
}
public class MyView extends SurfaceView implements Runnable {
Thread t = null;
SurfaceHolder holder;
boolean isItOk = false;
public MyView(Context context) {
super(context);
holder = getHolder();
}
#Override
public void run() {
while (isItOk == true) {
if (!holder.getSurface().isValid()) {
continue;
}
Canvas c = holder.lockCanvas();
if (canUpdate) {
canvas_draw(c);
}
holder.unlockCanvasAndPost(c);
try {
t.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
protected void canvas_draw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
Rect bgRec = new Rect(bgx, bgy, bgx+bgW, bgy+bgH);
canvas.drawBitmap(bg, null, bgRec, null);
ran = Math.random() * 5;
if (ran > 4.5) {
createEnemies();
}
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setTextSize(15);
canvas.drawText(hpString, 10, 25, paint);
for (Sprite sprite : copy) {
sprite.sprite_draw(canvas);
}
Player.sprite_draw(canvas, copy);
}
public void pause() {
isItOk = false;
while (true) {
try {
t.join();
} catch (InterruptedException e) {
}
break;
}
t = null;
}
public void resume() {
isItOk = true;
t = new Thread(this);
t.start();
}
}
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
return false;
}
public static void damagePlayer() {
hpString = "Health " + playerHealth;
playerHealth = playerHealth - 5;
if (playerHealth < 0) {
hpString = "game over";
}
}
public static void setDirection(int i, int j) {
if (i == 0 && j == -1) {
for (Sprite s : copy) {
s.y++;
bgy++;
}
}
if (i == 0 && j == 1) {
for (Sprite s : copy) {
s.y--;
bgy--;
}
}
if (i == -1 && j == 0) {
for (Sprite s : copy) {
s.x++;
bgx++;
}
}
if (i == 1 && j == 0) {
for (Sprite s : copy) {
s.x--;
bgx--;
}
}
}
}
You are changing bgx based on the number of sprites you have in your copy Iterable. in your setDirection method, please move the bgy, bgx outside of the enhanced for loops, like in:
if (i == 0 && j == -1) {
for (Sprite s : copy) {
s.y++;
}
bgy++;
}

LibGDX scene2d stage does not show buttons

I have a scene2d stage which should display buttons and a touchpad however it doesn't. it just shows a black screen. This is what I'm doing:
skins.json
{
"com.badlogic.gdx.scenes.scene2d.ui.ImageButton$ImageButtonStyle": {
"buttonA": { "down": "buttonA", "up": "buttonA" },
"buttonB": { "down": "buttonB", "up": "buttonB" },
"buttonX": { "down": "buttonX", "up": "buttonX" },
"buttonY": { "down": "buttonY", "up": "buttonY" },
},
"com.badlogic.gdx.scenes.scene2d.ui.Touchpad$TouchpadStyle": {
"touchpad": {"background": "touchpadBG", "knob": "touchpadKnob"}
}
}
controller.java
package com.letigames.ananse.ui;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton.ImageButtonStyle;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Touchpad;
import com.badlogic.gdx.scenes.scene2d.ui.Touchpad.TouchpadStyle;
import com.letigames.ananse.entity.Player;
import com.letigames.ananse.entity.util.Position;
import com.letigames.ananse.entity.util.Size;
import com.letigames.ananse.entity.util.TouchpadDirectional;
import com.letigames.ananse.weaponsSystem.util.Direction;
public class Controller {
public Controller(Stage stage, Player player,Size size){
this.stage = stage;
this.playerDirectional = new TouchpadDirectional(false, false, false, false);
this.screenSize = size;
this.MapButtons();
this.GenerateAtlas();
this.StyleButtons();
this.PlaceButtons();
this.AddButtonsToStage();
this.AssignActions(player);
System.out.println("* controller setup *");
}
private void MapButtons(){
this.buttonBStagePosition = new Position(this.screenSize.GetWidth() - (Controller.separator + (Controller.separator/4)),
this.screenSize.GetHeight() - (this.screenSize.GetHeight() - (Controller.separator/4)));
this.buttonYStagePosition = new Position(this.screenSize.GetWidth() - ((Controller.separator/4) + Controller.separator),
this.screenSize.GetHeight() - (this.screenSize.GetHeight() - ((Controller.separator/4) + Controller.separator + (Controller.separator/2))));
this.buttonAStagePosition = new Position(this.screenSize.GetWidth() - (((Controller.separator * 2)+ (Controller.separator/4) + (Controller.separator/2))),
this.screenSize.GetHeight() - (this.screenSize.GetHeight() - (Controller.separator/4)));
this.buttonXStagePosition = new Position(this.screenSize.GetWidth() - (((Controller.separator * 2)+ (Controller.separator/4) + (Controller.separator/2))),
this.screenSize.GetHeight() - (this.screenSize.GetHeight() - ((Controller.separator/4) + Controller.separator + (Controller.separator/2))));
this.touchpadStagePosition = new Position((Controller.separator/4), (Controller.separator/4));
this.buttonXRegionPosition = new Position(90, 100);
this.buttonYRegionPosition = new Position(90, 100);
this.buttonARegionPosition= new Position(90, 100);
this.buttonBRegionPosition = new Position(90, 100);
this.touchpadRegionPosition = new Position(90, 50);
System.out.println("* mapped buttons to their positions *");
}
private void GenerateAtlas(){
this.controllerAtlas = new TextureAtlas();
this.controllerTexture = new Texture(Gdx.files.internal("data/fishes.jpeg"));
this.controllerAtlas.addRegion("buttonA", new TextureRegion(this.controllerTexture, this.buttonARegionPosition.GetX(),
this.buttonARegionPosition.GetY(), Controller.size.GetWidth(), Controller.size.GetHeight()));
this.controllerAtlas.addRegion("buttonB", new TextureRegion(this.controllerTexture, this.buttonBRegionPosition.GetX(),
this.buttonBRegionPosition.GetY(), Controller.size.GetWidth(), Controller.size.GetHeight()));
this.controllerAtlas.addRegion("buttonX", new TextureRegion(this.controllerTexture, this.buttonXRegionPosition.GetX(),
this.buttonXRegionPosition.GetY(), Controller.size.GetWidth(), Controller.size.GetHeight()));
this.controllerAtlas.addRegion("buttonY", new TextureRegion(this.controllerTexture, this.buttonYRegionPosition.GetX(),
this.buttonYRegionPosition.GetY(), Controller.size.GetWidth(), Controller.size.GetHeight()));
this.controllerAtlas.addRegion("touchpadBG", new TextureRegion(this.controllerTexture, this.touchpadRegionPosition.GetX(),
this.touchpadRegionPosition.GetY(), (Controller.size.GetWidth() * 2), (Controller.size.GetHeight() * 2)));
this.controllerAtlas.addRegion("touchpadKnob", new TextureRegion(this.controllerTexture, this.touchpadRegionPosition.GetX(),
this.touchpadRegionPosition.GetY(), (Controller.size.GetWidth()/2), (Controller.size.GetHeight()/2)));
System.out.println("* generated texture atlas*");
}
private void StyleButtons(){
this.skin = new Skin(Gdx.files.internal("data/skins.json"), this.controllerAtlas);
ImageButtonStyle buttonAStyle = this.skin.get("buttonA", ImageButtonStyle.class);
ImageButtonStyle buttonBStyle = this.skin.get("buttonB", ImageButtonStyle.class);
ImageButtonStyle buttonXStyle = this.skin.get("buttonX", ImageButtonStyle.class);
ImageButtonStyle buttonYStyle = this.skin.get("buttonY", ImageButtonStyle.class);
this.buttonA = new ImageButton(buttonAStyle);
this.buttonB = new ImageButton(buttonBStyle);
this.buttonX = new ImageButton(buttonXStyle);
this.buttonY = new ImageButton(buttonYStyle);
TouchpadStyle touchpadStyle = this.skin.get("touchpad", TouchpadStyle.class);
this.touchPad = new Touchpad(10f, touchpadStyle);
System.out.println("* styled buttons *");
}
private void PlaceButtons(){
this.buttonA.setX(this.buttonAStagePosition.GetX());
this.buttonB.setX(this.buttonBStagePosition.GetX());
this.buttonX.setX(this.buttonXStagePosition.GetX());
this.buttonY.setX(this.buttonYStagePosition.GetX());
this.touchPad.setX(this.touchpadStagePosition.GetX());
this.buttonA.setY(this.buttonAStagePosition.GetY());
this.buttonB.setY(this.buttonBStagePosition.GetY());
this.buttonX.setY(this.buttonXStagePosition.GetY());
this.buttonY.setY(this.buttonYStagePosition.GetY());
this.touchPad.setY(this.touchpadStagePosition.GetY());
System.out.println("* placed buttons on the stage *");
}
private void AddButtonsToStage(){
this.stage.addActor(this.buttonA);
this.stage.addActor(this.buttonB);
this.stage.addActor(this.buttonX);
this.stage.addActor(this.buttonY);
this.stage.addActor(this.touchPad);
System.out.println("* added buttons to the stage *");
}
private void AssignActions(final Player player){
this.buttonA.addListener(new InputListener(){
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) { return true;}});
this.buttonB.addListener(new InputListener(){
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) { return true; }});
this.buttonX.addListener(new InputListener(){
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) { return true; }});
this.buttonY.addListener(new InputListener(){
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) { return true; }});
System.out.println("* assigned actions *");
}
public void DetermineDirection(){
if(this.touchPad.isTouched()){
boolean moveLeft = false;
boolean moveRight = false;
boolean moveUp = false;
boolean moveDown = false;
float xPercent = this.touchPad.getKnobPercentX();
float yPercent = this.touchPad.getKnobPercentY();
if((xPercent > 0) && (yPercent > 0) && (xPercent > yPercent)){ moveRight = true; }
if((xPercent > 0) && (yPercent < 0) && (xPercent > Math.abs(yPercent))){ moveRight = true; }
if((yPercent > 0) && (xPercent > 0) && (yPercent > xPercent)){ moveUp = true; }
if((yPercent > 0) && (xPercent < 0) && (yPercent > Math.abs(xPercent))){ moveUp = true; }
if((xPercent < 0) && (yPercent > 0) && (Math.abs(xPercent) > yPercent)){ moveLeft = true; }
if((xPercent < 0) && (yPercent < 0) && (Math.abs(xPercent) > Math.abs(yPercent))){ moveLeft = true; }
if((yPercent < 0) && (xPercent > 0) && (Math.abs(yPercent) > xPercent)){ moveDown = true; }
if((yPercent < 0) && (xPercent < 0) && (Math.abs(yPercent) > Math.abs(xPercent))){ moveDown = true; }
this.playerDirectional.SetDirections(moveLeft, moveRight, moveUp, moveDown);
}
else{ this.playerDirectional.SetDirections(Controller.defaultDirectional.moveLeft, Controller.defaultDirectional.moveRight,
Controller.defaultDirectional.moveUp, Controller.defaultDirectional.moveDown); }
}
public void UpdateMove(Player player){
/* D-Pad */
//System.out.println("move left ->" + this.playerDirectional.moveLeft);
//System.out.println("move right ->" + this.playerDirectional.moveRight);
//System.out.println("move up ->" + this.playerDirectional.moveUp);
//System.out.println("move down ->" + this.playerDirectional.moveDown);
if(this.playerDirectional.moveLeft){
if(player.GetCanWalk()) {
if(!player.GetJumped()){ player.Walk(Direction.LEFT); }
if(player.GetJumped() && player.GetWebStringReady()){ player.MoveInAir(Direction.LEFT); }
player.SetIsFacingLeft(true);
}
if(!player.GetWebStringReady() && player.GetJumped()){ player.Swing(Direction.LEFT); player.SetIsFacingLeft(true); }
}
if(this.playerDirectional.moveRight){
if(player.GetCanWalk()) {
if(!player.GetJumped()) { player.Walk(Direction.RIGHT); }
if(player.GetJumped() && player.GetWebStringReady()){ player.MoveInAir(Direction.RIGHT); }
player.SetIsFacingLeft(false);
}
if(!player.GetWebStringReady() && player.GetJumped()){ player.Swing(Direction.RIGHT); player.SetIsFacingLeft(false); }
}
if(this.playerDirectional.moveUp){
if(player.GetStickToWallState()){
player.GetBody().applyLinearImpulse(player.GetCrawlImpulse(),
player.GetBody().getWorldCenter());
player.SetIsFacingDown(false);
}
if(this.buttonA.isPressed() && player.GetWebStringReady() && (!player.GetCanJump())){ player.TryAttachString(true); }
if(!player.GetWebStringReady()){ player.UpdateAttachedString(true); }
}
if(this.playerDirectional.moveDown){
if(player.GetStickToWallState()){
player.GetBody().applyLinearImpulse(player.GetCrawlImpulse().cpy().mul(-1), player.GetBody().getWorldCenter());
player.SetIsFacingDown(true);
}
if(!player.GetWebStringReady()){ player.UpdateAttachedString(false); }
}
/* four buttons */
if(this.buttonB.isPressed()){
if(this.playerDirectional.moveLeft || this.playerDirectional.moveRight){
if(this.playerDirectional.moveLeft){ player.Throw(Direction.LEFT); }
else if(this.playerDirectional.moveLeft){ player.Throw(Direction.RIGHT); }
}
else { player.Throw(Direction.NONE); }
}
if(this.buttonA.isPressed()){
if(player.GetCanJump()){
player.Jump();
player.SetCanJump(false);
}
}
if(this.buttonX.isPressed()){
if(!player.GetWebStringReady()){ player.TryDetachString(true); }
if(player.GetStickToWallState()){ player.DetachFromWall(); }
}
if(this.buttonY.isPressed()){ player.Punch(); }
}
private Touchpad touchPad;
public ImageButton buttonA;
public ImageButton buttonB;
public ImageButton buttonX;
public ImageButton buttonY;
public ImageButton dPadLeft;
public ImageButton dPadRight;
public ImageButton dPadUp;
public ImageButton dPadDown;
private TextureAtlas controllerAtlas;
private Texture controllerTexture;
private Skin skin;
private Size screenSize;
private Stage stage;
private Position buttonARegionPosition;
private Position buttonBRegionPosition;
private Position buttonXRegionPosition;
private Position buttonYRegionPosition;
private Position touchpadRegionPosition;
private Position touchpadStagePosition;
private Position buttonAStagePosition;
private Position buttonBStagePosition;
private Position buttonXStagePosition;
private Position buttonYStagePosition;
public TouchpadDirectional playerDirectional;
private static final int separator = 100;
private static final TouchpadDirectional defaultDirectional = new TouchpadDirectional(false, false, false, false);
private static final Size size = new Size(100, 100); /* set the default size here for all the buttons */
}
Application listener class
package com.letigames.ananse;
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.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.math.Vector2;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.letigames.ananse.entity.util.Size;
import com.letigames.ananse.ui.Controller;
public class Ananse implements ApplicationListener {
#Override
public void create() {
this.screenWidth = Gdx.graphics.getWidth();
this.screenHeight = Gdx.graphics.getHeight();
this.doSleep = true;
this.gravity = new Vector2(0f, -10f);
this.UIStage = new Stage();
//Gdx.input.setInputProcessor(this.UIStage);
this.world = new World(this.gravity, this.doSleep);
this.camera = new OrthographicCamera(this.screenWidth, this.screenHeight);
this.debugRenderer = new Box2DDebugRenderer();
this.level = new Level(this.world);
this.controller = new Controller(this.UIStage, this.level.GetPlayer(), new Size((int)this.screenWidth, (int)this.screenHeight));
this.world.setContactListener(level.GetEntityContactListener());
//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);
}
#Override
public void dispose() {
level.DestroyLevel(false);
this.UIStage.dispose();
//batch.dispose();
//texture.dispose();
}
#Override
public void render() {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
debugRenderer.render(world, camera.combined);
//batch.setProjectionMatrix(camera.combined);
//batch.begin();
//sprite.draw(batch);
//batch.end();
level.UpdateLevel();
world.step(1/20f, 6, 2);
this.controller.DetermineDirection();
this.controller.UpdateMove(this.level.player);
this.camera.position.set(level.GetPlayer().GetBody().getWorldCenter().x, level.GetPlayer().GetBody().getWorldCenter().y, 0);
this.camera.zoom = 0.1f;
this.camera.update();
this.UIStage.act(Gdx.graphics.getDeltaTime());
this.UIStage.draw();
}
#Override
public void resize(int width, int height) { this.UIStage.setViewport(width, height, true); }
#Override
public void pause() {
}
#Override
public void resume() {
}
private OrthographicCamera camera;
private World world;
private Stage UIStage;
private Controller controller;
private Vector2 gravity;
private boolean doSleep;
private float screenWidth;
private float screenHeight;
Box2DDebugRenderer debugRenderer;
//private SpriteBatch batch;
//private Texture texture;
//private Sprite sprite;
private Level level;
}
I'm using LibGDX v 0.9.7. This code worked just fine some days ago, it doesn't anymore for some reason and doesn't generate error messages. The files being referred to in the code are all present: in the data folder within the LibGDX assets folder. Thoughts?

Categories

Resources