When called setPosition, how does a sprite move slowly - java

I am new to LibGDX library,
I am building the Snakes and ladders game with it.
I have a player class, it extends itself from Sprite class.
I want it to move when a dice is thrown.
But it becomes suddenly, I cannot see the movement.
public void updatePlayer(){
//this.setPosition(body.getPosition().x, body.getPosition().y);
game.getBatch().begin();
draw(game.getBatch());
game.getBatch().end();
}
public void updatePlayer(int dice){
if (dice > 0 && dice <= 6){
for (int i = 0; i < dice; i++){
float laterX = getX() + 48;
if (laterX > GameInfo.WIDTH - 20){
//setPosition(3, getY() + 5f);
translateY(5);
updatePlayer();
}else {
translateX(5);
//setPosition(getX() + 5, getY());
updatePlayer();
}
}
}
}

You cannot see movement 'cause you set the position. Use translate to move it.
doc
Sprite#setPosition() //Sets the position where the sprite will be drawn
Sprite#translate() //Sets the position relative to the current position where the sprite will be drawn.
My loop class:
public class Game extends ScreenAdapter {
private static String worldName;
private EntityPlayer player;
private FlatWorld flatWorld;
public static World world;
// private Box2DDebugRenderer debugRenderer;
private static boolean pauseGame;
public Game(String worldName){
world = new World(new Vector2(0, 0), false);
//this.debugRenderer = new Box2DDebugRenderer();
this.worldName = worldName;
this.player = PlayerDiskUtils.readPlayerFromDisk(this.worldName);
this.flatWorld = FlatWorldUtils.loadFlatWorld(this.worldName);
this.player.setCamera(this.flatWorld.getWorldSize());
this.flatWorld.setBlocksCourt(FlatWorldUtils.readBlocksCourt(this.flatWorld.getWorldSize().getWidth(), this.flatWorld.getWorldSize().getHeight(), this.worldName));
Gdx.input.setInputProcessor(new GameInputAdapter());
}
#Override
public void render(float delta) {
world.step(1/60f, 6, 2);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
Gdx.gl.glClearColor(0f, 0f, 0f, 1f);
this.flatWorld.getBlocksCourt().renderWorld(player.getCamera());
this.player.update(this.flatWorld, this.flatWorld.getWorldSize().getWidth(), this.flatWorld.getWorldSize().getHeight());
this.flatWorld.blocks.renderBlocks(this.player.getCamera());
this.player.renderInventory();
this.player.playerHud.render(this.player.states.getHealth(), this.player.states.getHungry(), this.player.states.getThirsty());
}
#Override
public void dispose() {
this.pause();
world = null;
worldName = null;
this.flatWorld.blocks.disposeBlocks();
}
#Override
public void pause() {
super.pause();
PlayerDiskUtils.writePlayerToDisk(this.worldName, this.player);
FlatWorldUtils.saveFlatWorld(this.worldName, this.flatWorld);
}
public static String getWorldName() { return worldName; }
public static boolean isPauseGame() { return pauseGame; }
public static void setPauseGame(boolean pauseGame) { Game.pauseGame = pauseGame; }
/**
* This is the input adapter of the player.
* Here keys and input event are set
*/
private class GameInputAdapter extends InputAdapter{
#Override //Mouse moving
public boolean mouseMoved(int screenX, int screenY) { return player.rotatePlayerToMouse(); }
#Override //Keys
public boolean keyDown(int keycode) {
if(keycode == Input.Keys.ESCAPE){ if(player.inventoryOpen) player.inventoryOpen = false;}
if(keycode == Input.Keys.E){ player.inventoryOpen = !player.inventoryOpen; }
return true;
}
#Override //Mouse buttons
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
Vector3 mouseCords3 = player.getCamera().unproject(new Vector3(screenX, screenY, 0));
return onBodyClick(new Vector2(mouseCords3.x, mouseCords3.y), button);
}
private boolean onBodyClick(Vector2 mouseCords, int button){
if(player.inventoryOpen) return false;
final Body[] body = new Body[1];
//Save inside body[0] the body which has been clicked
world.QueryAABB(fixture -> {
if(fixture.testPoint(mouseCords)){
body[0] = fixture.getBody();
}
return true;
}, mouseCords.x, mouseCords.y, mouseCords.x + 0.5f, mouseCords.y + 0.5f);
if(body[0] == null){
if(button == Input.Buttons.RIGHT){
player.onPlayerRightClick(flatWorld, mouseCords);
}
}else{
if(button == Input.Buttons.RIGHT){
((Block)body[0].getUserData()).onBlockClicked(player);
}else if(button == Input.Buttons.LEFT){
player.onPlayerBlockDestroying(flatWorld, (Block)body[0].getUserData(), mouseCords);
}
}
return true;
}
}
}
My code about player moving(it is 3d model, but it coult help you):
public void move(FlatWorld flatWorld, int worldWidth, int worldHeight) {
int x = 0, y = 0;
if (Gdx.input.isKeyPressed(Input.Keys.W))
y = 1;
if (Gdx.input.isKeyPressed(Input.Keys.S))
y = -1;
if (Gdx.input.isKeyPressed(Input.Keys.A))
x = -1;
if (Gdx.input.isKeyPressed(Input.Keys.D))
x = 1;
if(x != 0 || y != 0) {
if (this.canPlayerMove(flatWorld, new Vector3(x, y, 0), worldWidth, worldHeight)) {
this.modelInstance.transform.translate(x, y, 0);
this.moveCamera(worldWidth, worldHeight);
}
}
this.renderModel(null);
}
As you can see, I translate my model without call setPosition()

Related

Collision using Tiled and LibGDX not working

I have implemented a Player class which handles collision between the player and the objects in game. When I run it, he falls through the floor. I have followed a tutorial step by step but it is not working.
Below I have added the Player class and GameScreen class.
I have tried making rectangles around my Player to interact with, but it wasnt a fix.
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL30;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.maps.MapObjects;
import com.badlogic.gdx.maps.objects.RectangleMapObject;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.math.Intersector;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.utils.viewport.Viewport;
import inf112.skeleton.app.AGame;
import inf112.skeleton.app.entities.Player;
import inf112.skeleton.app.scenes.Hud;
public class GameScreen implements Screen {
public AGame game;
public TiledMap map;
private OrthogonalTiledMapRenderer mapRenderer;
private OrthographicCamera camera;
public Player player;
private BitmapFont font;
public Viewport gameport;
private Hud hud;
public GameScreen (AGame game) {
this.game = game;
hud = new Hud(game.batch);
}
#Override
public void show() {
font = new BitmapFont();
font.setColor(Color.RED);
font.setColor(Color.RED);
map = new TmxMapLoader().load("assets/data/GameBoard2.tmx");
camera = new OrthographicCamera();
camera.setToOrtho(false, 10, 10);
mapRenderer = new OrthogonalTiledMapRenderer(map, (float)0.015625);
mapRenderer.setView(camera);
player = new Player((TiledMapTileLayer) map.getLayers().get("Player"));
player.setPosition(11 * player.getCollisionLayer().getTileWidth(), (player.getCollisionLayer().getHeight() - 14) * player.getCollisionLayer().getTileHeight());
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);
mapRenderer.setView(camera);
mapRenderer.render();
mapRenderer.getBatch().begin();
player.draw((SpriteBatch) mapRenderer.getBatch());
mapRenderer.getBatch().end();
game.batch.setProjectionMatrix(hud.stage.getCamera().combined);
hud.stage.draw();
}
#Override
public void resize(int width, int height) {
camera.viewportHeight = height;
camera.viewportWidth = width;
}
#Override
public void pause() {
// TODO Auto-generated method stub
}
#Override
public void resume() {
// TODO Auto-generated method stub
}
#Override
public void hide() {
// TODO Auto-generated method stub
}
#Override
public void dispose() {
font.dispose();
mapRenderer.dispose();
map.dispose();
game.dispose();
}
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
public class Player extends Sprite implements InputProcessor {
private String blockedKey = "blocked";
private Vector2 velocity = new Vector2();
private float speed = 60 * 2, gravity = 60 * 1.8f, increment;
private boolean canJump;
private TiledMapTileLayer collisionLayer;
public Player(TiledMapTileLayer collisionLayer) {
this.collisionLayer = collisionLayer;
//setScale((float)0.1);
}
public void draw(SpriteBatch spriteBatch) {
update(Gdx.graphics.getDeltaTime());
super.draw(spriteBatch);
}
public void update(float delta) {
// apply gravity
velocity.y -= gravity * delta;
// clamp velocity
if(velocity.y > speed)
velocity.y = speed;
else if(velocity.y < -speed)
velocity.y = -speed;
// save old position
float oldX = getX(), oldY = getY();
boolean collisionX = false, collisionY = false;
// move on x
setX(getX() + velocity.x * delta);
// calculate the increment for step in #collidesLeft() and #collidesRight()
increment = collisionLayer.getTileWidth();
increment = getWidth() < increment ? getWidth() / 2 : increment / 2;
if(velocity.x < 0) // going left
collisionX = collidesLeft();
else if(velocity.x > 0) // going right
collisionX = collidesRight();
// react to x collision
if(collisionX) {
setX(oldX);
velocity.x = 0;
}
// move on y
setY(getY() + velocity.y * delta * 5f);
// calculate the increment for step in #collidesBottom() and #collidesTop()
increment = collisionLayer.getTileHeight();
increment = getHeight() < increment ? getHeight() / 2 : increment / 2;
if(velocity.y < 0) // going down
canJump = collisionY = collidesBottom();
else if(velocity.y > 0) // going up
collisionY = collidesTop();
// react to y collision
if(collisionY) {
setY(oldY);
velocity.y = 0;
}
// update animation
}
private boolean isCellBlocked(float x, float y) {
TiledMapTileLayer.Cell cell = collisionLayer.getCell((int) (x / collisionLayer.getTileWidth()), (int) (y / collisionLayer.getTileHeight()));
return cell != null && cell.getTile() != null && cell.getTile().getProperties().containsKey(blockedKey);
}
public boolean collidesRight() {
for(float step = 0; step <= getHeight(); step += increment)
if(isCellBlocked(getX() + getWidth(), getY() + step))
return true;
return false;
}
public boolean collidesLeft() {
for(float step = 0; step <= getHeight(); step += increment)
if(isCellBlocked(getX(), getY() + step))
return true;
return false;
}
public boolean collidesTop() {
for(float step = 0; step <= getWidth(); step += increment)
if(isCellBlocked(getX() + step, getY() + getHeight()))
return true;
return false;
}
public boolean collidesBottom() {
for(float step = 0; step <= getWidth(); step += increment)
if(isCellBlocked(getX() + step, getY()))
return true;
return false;
}
public Vector2 getVelocity() {
return velocity;
}
public void setVelocity(Vector2 velocity) {
this.velocity = velocity;
}
public float getSpeed() {
return speed;
}
public void setSpeed(float speed) {
this.speed = speed;
}
public float getGravity() {
return gravity;
}
public void setGravity(float gravity) {
this.gravity = gravity;
}
public TiledMapTileLayer getCollisionLayer() {
return collisionLayer;
}
public void setCollisionLayer(TiledMapTileLayer collisionLayer) {
this.collisionLayer = collisionLayer;
}
#Override
public boolean keyDown(int keycode) {
switch(keycode) {
case Input.Keys.W:
if(canJump) {
velocity.y = speed / 1.8f;
canJump = false;
}
break;
case Input.Keys.A:
velocity.x = -speed;
break;
case Input.Keys.D:
velocity.x = speed;
}
return true;
}
#Override
public boolean keyUp(int keycode) {
switch(keycode) {
case Input.Keys.A:
case Input.Keys.D:
velocity.x = 0;
}
return true;
}
#Override
public boolean keyTyped(char character) {
return false;
}
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
return false;
}
#Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
return false;
}
#Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
return false;
}
#Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
#Override
public boolean scrolled(float amountX, float amountY) {
return false;
}
The position of a libGDXSprite is bottom left so you need to make a distinction between position as far as your render is concerned, and as far as collision is concerned.
So if you add a half tile width to the x position when checking for the collision that would match what you see, being the base of the sprite.
Imagine a tilewidth of 4f and a position of 7f. As you look the sprite is rendered mainly on the third tile, but the collision is tested against the second one.

Libgdx: pause without triggering justtouch

I recently asked this question, it works perfectly, the only problem I'm having is that the whole game is based on touch events, when a user touches the screen, an object gets created.
What's happening now is that when a user touches the pause button (texture packer), an object gets created and the game is paused. I want to prevent objects from being created if the pause is touched. I used to be able to do something like this:
private Vector3 touchPos;
touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(touchPos);
if (Gdx.input.justTouched()) {
if (touchPos.x > pauseX && touchPos.x < pauseX + pauseX) {
if (touchPos.y > pauseY && touchPos.y < pauseX + pauseY) {
setGamePause(!getGamePause());
}}}
But doesn't seem to be working with texture packer, maybe my implementation is wrong, not sure, is there another approach?
private float pauseY = Gdx.graphics.getHeight() - 115;
private float pauseX = Gdx.graphics.getWidth() / 6;
button.setSize(150, 150)
It's on the top left of the screen
If pauseX and pauseY is left position and right position of a rectangle/button respectively then
you need width and height of button/rectangular area, like suppose that buttonWidth, buttonHeight.
if(Gdx.input.justTouched()) {
if (touchPos.x > pauseX && touchPos.x < pauseX + button.getWidth()) {
if (touchPos.y > pauseY && touchPos.y < pauseY + button.getHeight()) {
setGamePause(!getGamePause());
}
}
}
Please Check Test :
public class GdxTest extends Game implements InputProcessor{
private Stage stage;
Vector3 vector3;
TextButton button;
float pauseX,pauseY;
#Override
public void create() {
vector3=new Vector3();
ExtendViewport extendViewport=new ExtendViewport(700,1200,new OrthographicCamera());
stage=new Stage(extendViewport);
Skin skin=new Skin(Gdx.files.internal("skin/uiskin.json"));
skin.get("font-label", BitmapFont.class).getRegion().getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
pauseX=300;
pauseY=500;
button=new TextButton("Pause",skin);
button.setPosition(pauseX,pauseY);
stage.addActor(button);
Gdx.input.setInputProcessor(this);
}
#Override
public void render() {
super.render();
Gdx.gl.glClearColor(0,1,1,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.draw();
stage.act();
////Touch Detection without processor
vector3.set(Gdx.input.getX(),Gdx.input.getY(),0);
stage.getCamera().unproject(vector3);
if(Gdx.input.justTouched()){
if(vector3.x>pauseX && vector3.x<pauseX+button.getWidth() && vector3.y>pauseY && vector3.y<pauseY+button.getHeight())
System.out.println("TOuched");
}
///////
}
#Override
public void resize(int width, int height) {
super.resize(width,height);
stage.getViewport().update(width,height);
}
#Override
public void dispose() {
stage.dispose();
}
#Override
public boolean keyDown(int keycode) {
return false;
}
#Override
public boolean keyUp(int keycode) {
return false;
}
#Override
public boolean keyTyped(char character) {
return false;
}
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button1) {
vector3.set(screenX,screenY,0);
stage.getCamera().unproject(vector3);
if(vector3.x>pauseX && vector3.x<pauseX+button.getWidth() && vector3.y>pauseY && vector3.y<pauseY+button.getHeight())
System.out.println("TOuched");
return false;
}
#Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
return false;
}
#Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
return false;
}
#Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
#Override
public boolean scrolled(int amount) {
return false;
}
}

Collision Detection is Not Working

Basically I have been making a simple game in which I now want to create collision detection between the Player and the Enemy. I have made both a class of the player and the enemy and then also a separate GameView class. My issue is that there is simply no collision happening and I just don't understand why, I have changed the code various times but I still can't seem to crack it. I will leave my code below and if anyone sees where I have gone wrong it would be great help. Thank you.
GameView Class:
public class GameView extends SurfaceView implements Runnable {
Canvas canvas;
SurfaceHolder surfaceHolder;
Thread thread = null;
volatile boolean playing;
Paint paint;
Context context;
Player player;
int screenX, screenY, numberOfEnemies = 4, distanceBetweenEnemies;
int enemyX [] = new int[numberOfEnemies];
int enemyY [] = new int[numberOfEnemies];
private boolean paused = true;
Enemy enemy;
Enemy [] enemies;
Random random;
Rect [] enemyRectangle;
public GameView (Context context, int x, int y) {
super(context);
this.context = context;
surfaceHolder = getHolder();
paint = new Paint();
thread = new Thread();
screenX = x;
screenY = y;
player = new Player (context, screenX, screenY);
enemies = new Enemy[numberOfEnemies];
enemyRectangle = new Rect[numberOfEnemies];
enemy = new Enemy (context, screenX);
distanceBetweenEnemies = screenX * 3 / 4;
for (int i = 0; i < numberOfEnemies; i ++) {
enemies[i] = new Enemy(context, screenX);
enemyX[i] = screenX / 2 - enemy.getEnemyBitmap().getWidth() / 2 + i * distanceBetweenEnemies;
random = new Random();
enemyY[i] = random.nextInt(screenY - enemy.getEnemyBitmap().getHeight() / 2);
}
}
#Override
public void run() {
while (playing) {
draw();
if(!paused){
update();
}
}
}
private void draw () {
if (surfaceHolder.getSurface().isValid()) {
canvas = surfaceHolder.lockCanvas();
canvas.drawColor(Color.argb(255, 26, 128, 182));
canvas.drawBitmap(player.getPlayerBitmap(), player.getX(), player.getY(), null);
for (int i = 0; i < numberOfEnemies; i ++) {
canvas.drawBitmap(enemies[i].getEnemyBitmap(), enemyX[i], enemyY[i], null);
enemyRectangle [i] = new Rect(enemyX[i], enemyY[i], enemy.getEnemyBitmap().getWidth(),
enemy.getEnemyBitmap().getHeight());
enemyX[i] += enemy.getEnemySpeed();
}
update ();
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
private void update () {
player.updatePlayerPosition();
player.noLeaveScreen();
for (int i = 0; i < numberOfEnemies; i ++) {
if (enemyX[i] < 0 - enemy.getEnemyBitmap().getWidth()) {
enemyY[i] = random.nextInt(screenY);
enemyRectangle [i] = new Rect(enemyX[i], enemyY[i], enemy.getEnemyBitmap().getWidth(),
enemy.getEnemyBitmap().getHeight());
enemyX[i] += numberOfEnemies * distanceBetweenEnemies;
} else {
enemyX[i] += enemy.getEnemySpeed();
}
if (Rect.intersects(player.getPlayerRectangle(), enemyRectangle[i])) {
Log.e("COLLISION:", "Detected");
enemyX[i] = - 200;
}
}
}
public void pause () {
playing = false;
try {
thread.join();
} catch (InterruptedException e) {
Log.e("Error:", "joining thread");
}
}
public void resume () {
playing = true;
thread = new Thread(this);
thread.start();
}
#Override
public boolean onTouchEvent (MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
player.playerJump();
break;
}
return true;
}
}
Player Class:
public class Player {
Bitmap playerBitmap;
Rect playerRectangle;
int x, y, playerJumpSpeed, gravity, screenY;
boolean playerIsMoving;
public Player (Context context, int screenX, int screenY) {
this.screenY = screenY;
gravity = 2;
playerBitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);
x = screenX/2 - playerBitmap.getWidth()/2;
y = screenY/2 - playerBitmap.getHeight()/2;
playerRectangle = new Rect(x, y, playerBitmap.getWidth(), playerBitmap.getHeight());
playerJumpSpeed = - 1000;
playerIsMoving = true;
}
public void updatePlayerPosition () {
while (playerIsMoving) {
y += gravity;
break;
}
}
public void playerJump () {
while (playerIsMoving) {
y += playerJumpSpeed;
break;
}
}
public void noLeaveScreen () {
if (y < 0) {
playerJumpSpeed = 0;
} else {
playerJumpSpeed = - 40;
}
if (getY() > (screenY - playerBitmap.getHeight())) {
gravity = 0;
} else {
gravity = 2;
}
}
public int getX () {
return x;
}
public int getY () {
return y;
}
public Bitmap getPlayerBitmap () {
return playerBitmap;
}
public Rect getPlayerRectangle () {
return playerRectangle;
}
}
Enemy Class:
public class Enemy {
Bitmap enemyBitmap;
int enemySpeed, screenX;
boolean isEnemyMoving;
Random random;
public Enemy (Context context, int screenX) {
this.screenX = screenX;
enemyBitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);
random = new Random();
isEnemyMoving = true;
enemySpeed = - 3;
}
public int getEnemySpeed () {
return enemySpeed;
}
public Bitmap getEnemyBitmap () {
return enemyBitmap;
}
}
There are the classes, any help appreciated!

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

How can I get value from one class to another without extends it?

I am newbie in programming and may be this will be stupid question but here it is:
This is my class board:
public class Board {
public static final int COLOR_WHITE = 1;
public static final int COLOR_BLACK = 2;
PlayingPiece[][] board;
private boolean isFirstMove;
private int color;
public Board() {
this.setBoard(new PlayingPiece[8][8]);
this.isFirstMove = true;
this.initializePieces();
}
// Initialize the chess pieces
public void initializePieces() {
for (int i = 0; i < 8; i++) {
board[1][i] = new Pawn(1, i, COLOR_WHITE);
}
for (int i = 0; i < 8; i++) {
board[6][i] = new Pawn(6, i, COLOR_BLACK);
}
board[0][0] = new Rook(0, 0, COLOR_WHITE);
board[0][7] = new Rook(0, 7, COLOR_WHITE);
board[7][0] = new Rook(7, 0, COLOR_BLACK);
board[7][7] = new Rook(7, 7, COLOR_BLACK);
board[0][1] = new Knight(0, 1, COLOR_WHITE);
board[0][6] = new Knight(0, 6, COLOR_WHITE);
board[7][1] = new Knight(7, 1, COLOR_BLACK);
board[7][6] = new Knight(7, 6, COLOR_BLACK);
board[0][2] = new Officer(0, 2, COLOR_WHITE);
board[0][5] = new Officer(0, 5, COLOR_WHITE);
board[7][2] = new Officer(7, 2, COLOR_BLACK);
board[7][5] = new Officer(7, 5, COLOR_BLACK);
board[0][3] = new Queen(3, 0, COLOR_WHITE);
board[0][4] = new King(4, 0, COLOR_WHITE);
board[7][3] = new Queen(7, 3, COLOR_BLACK);
board[7][4] = new King(7, 4, COLOR_BLACK);
this.printBoard();
}
public boolean play(int color, int fromX, int fromY, int toX, int toY) {
boolean isTrue = false;
// Check if this is the first turn and only white can move
if (isFirstMove && color == COLOR_WHITE) {
isTrue = true;
} else if (isFirstMove && color == COLOR_BLACK) {
return false;
}
// check if player plays 2 times in a raw and if you move the piece from
// current possition
if (color == this.color || (toX == fromX && toY == fromY)) {
return false;
}
isTrue = true;
if (isTrue == true) {
this.isFirstMove = false;
// Check if player plays with his own color
if (((board[fromX][fromY]).getColor() != color)) {
return false;
}
// Check the isLegal movement of every chess piece
if ((board[fromX][fromY]).move(toX, toY)) {
board[toX][toY] = board[fromX][fromY];
board[fromX][fromY] = null;
}
this.printBoard();
}
return isTrue;
}
public PlayingPiece[][] getBoard() {
return board;
}
public void setBoard(PlayingPiece[][] board) {
this.board = board;
}
I want to get the value of this:
board[toX][toY];
OK after that here is the other my class for chess pieces:
public class PlayingPiece {
public static final int COLOR_WHITE = 1;
public static final int COLOR_BLACK = 2;
public static final char BLACK_PAWN = '\u265F';
public static final char BLACK_ROOK = '\u265C';
public static final char BLACK_KNIGHT = '\u265E';
public static final char BLACK_BISHOP = '\u265D';
public static final char BLACK_QUEEN = '\u265B';
public static final char BLACK_KING = '\u265A';
public static final char WHITE_PAWN = '\u2659';
public static final char WHITE_ROOK = '\u2656';
public static final char WHITE_KNIGHT = '\u2658';
public static final char WHITE_BISHOP = '\u2657';
public static final char WHITE_QUEEN = '\u2655';
public static final char WHITE_KING = '\u2654';
public static final char NO_PIECE = ' ';
private int x, y;
private boolean isAlive;
private int color;
private char symbol;
protected PlayingPiece (int newX, int newY, int newColor) {
this.setX(newX);
this.setY(newY);
this.color = newColor;
this.isAlive = true;
}
protected PlayingPiece(int newX, int newY) {
this.setX(newX);
this.setY(newY);
}
protected PlayingPiece() {
}
public int getX() {
return x;
}
public void setY(int y) {
this.y = y;
}
public int getY() {
return y;
}
public void setX(int x) {
this.x = x;
}
protected boolean moveIsLegal (int newX, int newY) {
boolean isLegal = false;
if ((0 <= newX && newX <= 7) && (0 <= newY && newY <= 7)){
isLegal = true;
}
return isLegal;
}
public boolean move (int newX, int newY) {
if (moveIsLegal(newX, newY)) {
setX(newX);
setY(newY);
return true;
}
return false;
}
public int getColor() {
return color;
}
public boolean isAlive() {
return isAlive;
}
public void setAlive(boolean isAlive) {
this.isAlive = isAlive;
}
public char getSymbol() {
return symbol;
}
public void setSymbol(char symbol) {
this.symbol = symbol;
}
}
And now this is Pawn class which extends PlayingPieces:
public class Pawn extends PlayingPiece {
private boolean hasBeenMoved;
protected Pawn(int newX, int newY, int color) {
super(newX, newY, color);
this.hasBeenMoved = false;
if (color == COLOR_BLACK) {
this.setSymbol(BLACK_PAWN);
} else {
this.setSymbol(WHITE_PAWN);
}
}
#Override
public boolean move(int newX, int newY) {
if (super.move(newX, newY)) {
this.hasBeenMoved = true;
return true;
}
return false;
}
#Override
protected boolean moveIsLegal(int newX, int newY) {
boolean isLegal = false;
int newPositionX = newX - this.getX();
if (super.moveIsLegal(newX, newY)) {
if ((hasBeenMoved == false)
&& (((Math.abs(newPositionX) <= 2) && getY() == newY))) {
isLegal = true;
} else if ((hasBeenMoved == true)
&& (((Math.abs(newPositionX) <= 1) && getY() == newY)) && isValidTrace(newX, newY)) {
isLegal = true;
}
}
return isLegal;
}
public boolean isValidTrace(int newX, int newY) {
PlayingPiece[][] array = new PlayingPiece[8][8];
if (array[newX][newY].equals(new PlayingPiece())) {
return false;
}
return true;
}
}
Now in this method isValidTrace() I want to get the value of board[toX][toY] from class Board and how can I do this without any extends here ?
Another solution (assuming you won't need multiple Board instances) is making board static.
public static PlayingPiece[][] board;
Then you can access it from your Pawn class using Board.board
I do not know if I understand your question but..
If you have got 2 classes A and B instead of using inheritance you can use aggregation. For example, you want to use some method from object B in class A you go with:
class A {
private B b;
}
and then inside methods of class A you go with b.nameOfTheMethod()
You can create a method to return the array and call it in the class you want the data.
public PlayingPiece getBoard()
{
return board;
}

Categories

Resources