Java LibGDX Moving to Touch Position on Android - java

I'm using this code but somethings aren't perfect. It's working but not smooth. First it goes touchX and then goes touchY. But I want this at the same time. I tried different codes but didn't work. How can I fix it? What's the problem?
package com.anil.game1;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector3;
public class Game1 extends ApplicationAdapter {
private SpriteBatch batch;
private OrthographicCamera camera;
private Texture player1Texture;
private Rectangle player1Rectangle;
private Vector3 touchPos;
#Override
public void create () {
batch = new SpriteBatch();
camera = new OrthographicCamera(480, 800);
player1Texture = new Texture("Player1.png");
player1Rectangle = new Rectangle();
player1Rectangle.set(240, 0, 64, 64);
touchPos = new Vector3();
}
#Override
public void render () {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined);
batch.begin();
if (Gdx.input.isTouched()) {
touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(touchPos);
//player1Rectangle.setPosition(new Vector2(touchPos.x, touchPos.y));
}
if (touchPos.x > player1Rectangle.x)
player1Rectangle.x += 5;
else
player1Rectangle.x -= 5;
if (touchPos.y > player1Rectangle.y)
player1Rectangle.y += 5;
else
player1Rectangle.y -= 5;
batch.draw(player1Texture, player1Rectangle.x - 32, player1Rectangle.y - 32);
batch.end();
}
#Override
public void dispose () {
batch.dispose();
player1Texture.dispose();
}
}

In this section:
if (touchPos.x > player1Rectangle.x)
player1Rectangle.x += 5;
else
player1Rectangle.x -= 5;
if (touchPos.y > player1Rectangle.y)
player1Rectangle.y += 5;
else
player1Rectangle.y -= 5;
You are forcing the rectangle to always move in the X and Y directions by a set amount. It's never allowed to just sit still or slow down. Also, you probably don't want to be handling X and Y separately, because then its speed will be slower in the cardinal directions and faster in the diagonal directions, which would look weird. And finally, you need to work with speed and time to keep a stable movement speed.
So first of all, define a speed for your object. Also, you're going to want a Vector2 handy for calculations.
private static final float SPEED = 300f; //world units per second
private final Vector2 tmp = new Vector2();
Now after you have calculated touch position, you want to figure out what direction to move in, and how far to move along that direction. So right after your isTouched block:
//how far the player can move this frame (distance = speed * time):
float maxDistance = SPEED * Gdx.graphics.getDeltaTime();
//a vector from the player to the touch point:
tmp.set(touchPos.x, touchPos.y).sub(player1Rectangle.x, player1Rectangle.y);
if (tmp.len() <= maxDistance) {// close enough to just set the player at the target
player1Rectangle.x = touchPos.x;
player1Rectangle.y = touchPos.y;
} else { // need to move along the vector toward the target
tmp.nor().scl(maxDistance); //reduce vector length to the distance traveled this frame
player1Rectangle.x += tmp.x; //move rectangle by the vector length
player1Rectangle.y += tmp.y;
}

Related

The size of the square is calculated incorrectly | Java libgdx

I am creating a game in which there is a 10x10 map and I need to calculate the size of these squares so that they all fit on the screen.
rect_x_end, rect_y_end The size of the square by x and y
screen_x, screen_y Screen Size
len_map_x, len_map_y Map width and length = 10
I calculated the size of the square like this:
rect_x_end = screen_x / len_map_x
rect_y_end = screen_y / len_map_y
example:
64 = 640 / 10
48 = 480 / 10
In this example, everything works correctly, but as soon as I start resizing the screen, this method gives an incorrect result.
I was doing something similar to python (pygame) and everything worked there.
kucer0043.java
package com.kucer0043.game;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.utils.ScreenUtils;
public class kucer0043 extends ApplicationAdapter {
private ShapeRenderer shapeRenderer;
private int map_size;
#Override
public void create () {
shapeRenderer = new ShapeRenderer();
map_size = 10; // square map size
}
#Override
public void render () {
ScreenUtils.clear(0.5f, 0.5f, 0.5f, 1);
int rect_x_end = Gdx.graphics.getWidth() / map_size;
int rect_y_end = Gdx.graphics.getHeight() / map_size;
int map_x = Gdx.input.getX() / rect_x_end;
int map_y = Gdx.input.getY() / rect_y_end;
int x = map_x * rect_x_end;
int y = Gdx.graphics.getHeight() - (map_y + 1) * rect_y_end;
shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
shapeRenderer.setColor(0f,1f,0f,0f);
shapeRenderer.rect(x,y, rect_x_end, rect_y_end);
shapeRenderer.end();
}
#Override
public void dispose () {
}
}
The projection matrix of your ShapeRenderer is calculated on initialization,you need to re-calculate it whenever the window changes size.
There are a few ways of achieving this, the simplest might be to just create a new ShapeRenderer when the window resizes:
#Override
public void resize(int width, int height) {
shapeRenderer = new ShapeRenderer();
}

I cannot figure out a way to move the balls

I am currently working on a 3 cushion billiards game project. I have added two balls on the table so far. I am trying to move one of the balls but I am having a hard time doing that. Should I use a timer? If so then could you tell me an effective way to use the timer on my code so I can move my balls?
Your help would be much appreciated.
Thanks in advance.
Farhan Hasan
I have tried to create a move function for the class balls. But I am not sure what I should put inside the function, I have added the xSpeed and ySpeed. The xLocation and the yLocation changes depending on the xSpeed and ySpeed.
public class Balls
{
private Color ballFillColor;
private Color ballBorderColor;
private int ballX = 0;
private int ballY = 0;
private int xSpeed = 5;
private int ySpeed = 0;
private int ballWidth = 0;
private int ballHeight = 0;
Timer t;
public boolean fillBall = false;
private static Balls ballArray[]; //Required for drawMultipleBalls
Balls(){ //Constructor
ballBorderColor = Color.black;
}
Balls(int ballX, int ballY, int ballWidth, int ballHeight, Color ballBorderColor, JFrame window){ //Constructor
// X , Y , Width, Height, Border Colour, container
this.setBallBorderColor(ballBorderColor);
this.setBallWidth(ballWidth);
this.setBallHeight(ballHeight);
this.setBallX(ballX);
this.setBallY(ballY);
this.drawBall(window);
}
//Here is the move function. I am not really sure what to do here.
public void move()
{
if(this.ballX < 1000 - this.ballWidth)
{
this.ballX += this.xSpeed;
}
try
{
Thread.sleep(1);
}
catch(Exception e)
{
}
}
//GET AND SET FUNCTIONS HERE
//HERE ARE THE FUNCTIONS WHICH ARE RESPONSIBLE FOR DRAWING MY BALLS IN JFRAME
public void drawBall(JFrame frame)
{
frame.getContentPane().add(new MyComponent());
}
public void drawMultipleBalls(JFrame frame, Balls[] balls)
{
ballArray = balls;
frame.getContentPane().add(new MyComponent2());
}
private class MyComponent extends JComponent{
public void paintComponent(Graphics g){
if (fillBall) //Fill first, and then draw outline.
{
g.setColor(ballFillColor);
g.fillOval(getBallX(),getBallY(), getBallHeight(),getBallWidth());
}
g.setColor(getBallBorderColor());
g.drawOval(getBallX(),getBallY(), getBallHeight(),getBallWidth());
}
}
private class MyComponent2 extends JComponent{
public void paintComponent(Graphics g){
for (int i = 0; i < ballArray.length; i++)
{
if (ballArray[i].fillBall) //Fill first, and then draw outline.
{
g.setColor(ballArray[i].ballFillColor);
g.fillOval(ballArray[i].getBallX(),ballArray[i].getBallY(), ballArray[i].getBallHeight(),ballArray[i].getBallWidth());
}
g.setColor(ballArray[i].getBallBorderColor());
g.drawOval(ballArray[i].getBallX(),ballArray[i].getBallY(), ballArray[i].getBallHeight(),ballArray[i].getBallWidth());
}
}
}
Hopefully, I can have two movable balls for the game, the should bounce back as the hit the edge of the screen and they should be able to slow down over time. For that, I am thinking to use a damper (I will multiply the xSpeed and ySpeed with a number less than 1, eventually it will slow down the ball)
Here is a simple example I came up with to show a ball moving and bouncing off the edges.
The direction changes based on the boundary. Left and top edges just check for 0. Bottom and right edges need to include the diameter of the ball.
The x and y increments are independent. And these amounts in conjunction with the timer can change the movement. Notice however, that to have objects bounce off of each other (as in a pool game) is more complicated due to angle of trajectories, etc. And the distances bounced will vary and slow with time based on frictional values. Everything else is documented in the Java API.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MovementDemo extends JPanel implements ActionListener {
JFrame frame = new JFrame("Movement Demo");
int size = 500;
int x = 50;
int y = 200;
int diameter = 50;
int yinc = 2;
int xinc = 2;
int xdirection = 1;
int ydirection = 1;
public MovementDemo() {
setPreferredSize(new Dimension(size, size));
frame.add(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MovementDemo().start());
}
public void start() {
Timer timer = new Timer(100, this);
timer.setDelay(5);
timer.start();
}
public void actionPerformed(ActionEvent ae) {
if (x < 0) {
xdirection = 1;
}
else if (x > size - diameter) {
xdirection = -1;
}
if (y < 0) {
ydirection = 1;
}
else if (y > size - diameter) {
ydirection = -1;
}
x = x + xdirection * xinc;
y = y + ydirection * yinc;
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.BLUE);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.fillOval(x, y, diameter, diameter);
}
}
It seems in general there are a few things you need to figure out:
has the ball collided with another ball
has the ball collided with a wall
otherwise just figure out what is the ball's new position based on its velocity
Below is some sample code that stubs some of this out. You can first compare the current ball's position to all others (not including the current ball of course). If there are any equal positions, process a collision with a ball. If the ball is at the window border i.e it hit a wall, process a collision with a wall. Otherwise just calculate its new position based on its current velocity.
The process collision part is just to apply physics mechanics to whatever degree of complexity you require. One general suggested change would be to update the velocity of the balls then apply it to the position after. The specific calculations for velocity changes you could apply as needed and as you can imagine it can get pretty involved which is why I suggest using a separate method and possibly a sub class for velocity instead of managing each part of the velocity vector in the ball itself. I used the wall as an object because of this. The composition, weights, velocities etc of the object's colliding can affect the resulting collision, but how complex you want that processing to be is up to you.
Sorry I'm no physics expert but I hope this sends you in the right direction in terms of code! Also this might help with the specific calculations you might want to use:
https://www.khanacademy.org/science/physics/one-dimensional-motion/displacement-velocity-time/v/calculating-average-velocity-or-speed
public void move()
{
// check if balls are on same position not including this ball
for(Ball b: ballArray){
if (this.position == b.position && this != b){
processCollision(this, b, null);
} else{
// if the ball hasn't collided with anything process its movement based on speed
// this assumes a 1000 x 1000 window for keeping objects inside it
if(this.ballX < 1000 - this.ballWidth && this.ballY < 1000 - this.ballHeight){
this.ballX += this.xSpeed;
this.ballY += this.ySpeed;
}else {
processCollision(this, null, new Wall());
}
}
}
try
{
Thread.sleep(1);
}
catch(Exception e)
{
}
}
public void processCollision(Ball b1, Ball b2, Wall w){
// if ball hasn't collided with a wall, process a ball - ball collision
if(w == null){
// apply physics mechanics according the complexity desired for ball collisions
b1.xSpeed -= b2.xSpeed;
b1.ySpeed -= b2.ySpeed;
// ball 2 would end up slowing down
b2.xSpeed -= b1.xSpeed;
b2.ySpeed -= b1.ySpeed;
}
// if ball hasn't collided with a ball, process a ball - wall collision
if(b2 == null){
// apply physics mechanics for hitting a wall
// e.g as below: just send ball in opposite direction
b1.xSpeed = b1.xSpeed * -1;
b1.ySpeed = b1.ySpeed * -1;
}
// either way, process ball's new position based on its new speed
b1.ballX += b1.xSpeed;
b1.ballY += b1.ySpeed;
b2.ballX += b2.xSpeed;
b2.ballY += b2.ySpeed;
}

Using touchdown in libGDX

I am trying to use touchdown() in my game. Motive is simple, I just want to move the player based on touch detection on screen, But it is giving the following error:
Exception in thread "LWJGL Application" java.lang.NullPointerException
at com.mygdx.game.sprites.Ron.touchDown(Ron.java:39)
at com.badlogic.gdx.backends.lwjgl.LwjglInput.processEvents(LwjglInput.java:329)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:215)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:124)
and the code is:
package com.mygdx.game.sprites;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.viewport.ExtendViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.mygdx.game.Constants;
/**
* Created by Vamsi Rao on 11/9/2016.
*/
public class Ron extends InputAdapter {
private Vector2 position;
private Vector2 velocity;
Vector2 worldClick;
boolean right;
boolean left;
private ExtendViewport viewport;
private Texture ron;
public Ron(int x, int y, ExtendViewport viewport) {
super();
position = new Vector2(x, y);
velocity = new Vector2(Constants.VELOCITY_X, 0);
this.viewport = viewport;
ron = new Texture("ron.png");
}
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
worldClick = viewport.unproject(new Vector2(screenX, screenY));
if (worldClick.x >= viewport.getWorldWidth() / 4) {
right = true;
}
if (worldClick.x < viewport.getWorldWidth() / 4) {
left = true;
}
return true;
}
public Vector2 getPosition() {
return position;
}
public Texture getTexture() {
return ron;
}
public void update(float delta) {
left=false;
right=false;
if (right) {
position.x += delta * velocity.x;
}
if (left) {
position.x -= delta * velocity.x;
}
}
}
and I had set Input processor in another class which is using the object ron of Ron class(the class shown above) like this:
Gdx.input.setInputProcessor(ron);
39 line is
worldClick = viewport.unproject(new Vector2(screenX, screenY));
so the NullPointerException is rather about viewport variable - you are passing this to the constructor
public Ron(int x, int y, ExtendViewport viewport) {
...
this.viewport = viewport;
...
so probably the viewport is being provided with null value.
Take a look at What is a NullPointerException, and how do I fix it?
The second thing is that maybe in this case using flags is not the best idea - your code is definitely less readable, also you have a redundant unnecessary code.
//these lines are almost the same
position.x += delta * velocity.x;
position.x -= delta * velocity.x;
better would be to set the direction vector of velocity then just multiply it by delta in update like you do
//in your touchdown
if (worldClick.x >= viewport.getWorldWidth() / 4) {
velocity.x *= (velocity.x >= 0) ? 1 : -1;
}
//also add else here - there is always one or another here
else if (worldClick.x < viewport.getWorldWidth() / 4) {
velocity.x *= (velocity.x < 0) ? 1 : -1;
}
//in update
position.x += delta * velocity.x;
you can also easily implement change-velocity logic this way (like when character changes direction he slow down then starting to move backward... etc)

Ball stops moving after a few bounces

Ok so I have been try to get this ball to bounce naturally for a few weeks now and can't seem to get it right. The program should allow the user to input a set amount of gravity and then have the ball bounce according to that amount. It works for the first few bounces but stopping the ball is the problem. I have to deliberately set its movement to 0 or else it will endlessly bounce in place but not move on the x-axis. This issue only happens when the gravity is set to 15, other amount and things really go bad. The ball will bounce naturally but then keep rolling on x-axis forever. I've never taken a physics class so the issue is probably in the physics code. Anyone know where the issue is?
Here is the code my code-
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.util.Random;
import javax.swing.JOptionPane;
//key stuff
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
public class StartingPoint extends Applet implements Runnable{
//key press
private static boolean wPressed = false;
public static boolean isWPressed() {
synchronized (StartingPoint.class) {
return wPressed;
}
}
//for position of circle
int x = 0;
int y= 0;
//for position change
double dx = 2;
double dy = 2;
//for circle size
int rad = 11;
//image for update()
private Image i;
private Graphics gTwo;
//Physics
double grav = 15;
double engloss= .65;
double tc = .2;
double friction = .9;
#Override
public void init() {
// sets window size
setSize(800,600);
}
#Override
public void start() {
//"this" refers to the implemented run method
Thread threadOne = new Thread(this);
//this goes to run()
threadOne.start();
}
#Override
public void run() {
String input = JOptionPane.showInputDialog( "How much gravity?" );
grav= Double.parseDouble(input);
// sets frame rate
while (true){
//makes sure it doesn't go off screen x wise
//right side
if (x + dx > this.getWidth() - rad -1){
x= this.getWidth() -rad -1; //blocks it from moving past boundary
dx = -dx; //Reveres it
}
//left side
else if (x + dx < 1 + rad){
x= 1+rad; //ball bounces from the center so it adjusts for this by adding one and rad to pad out the radius of the ball plus one pixel.
dx = -dx; //Inverters its movement so it will bounce
}
//makes the ball move
else{
x += dx; // if its not hitting anything it keeps adding dx to x so it will move.
}
//friction
if(y == this.getHeight()-rad -1){
dx *= friction; //every time the ball hits the bottom dx is decreased by 10% by multiplying by .9
//Keeps it from micro bouncing for ever
if (Math.abs(dy) < 4){ // if the speed of y (dy) is less than .4 it is set to 0
dy= 0;
}
/**if (Math.abs(dx) < .00000000000000000001){ // if the speed of x (dx) is less than .00000000000000000001 it is set to 0, this value doesn't seem to matter
dx = 0;
}**/
}
//makes sure it doesn't go off screen y wise
//down
if (y > this.getHeight() - rad -0){ // TODO Check how getHieght is measured.
y= this.getHeight() -rad -0;
//makes ball loose speed.
dy *= engloss;
dy = -dy;
}
else {
//velocity
// tc makes grav smaller. Total of which is added to dy. To increase velocity as the ball goes down.
dy += grav *tc;
//gravity
//new dy is decreased by tc + .5 multiplied by gravity and tc squared. This makes the ball bounce lower every time based on its speed
y += dy*tc + .5*grav*tc*tc;
}
//frame rate
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//end frame rate
}
#Override
public void stop() {
}
#Override
public void destroy() {
}
#Override
public void update(Graphics g) {
//keeps it from flickering... don't know how though
if(i == null){
i = createImage(this.getSize().width, this.getSize().height);
gTwo = i.getGraphics();
}
gTwo.setColor(getBackground());
gTwo.fillRect(0, 0, this.getSize().width, this.getSize().height);
gTwo.setColor(getForeground());
paint(gTwo);
g.drawImage(i, 0, 0, this);
//do some thing with setDoubleBuffered
}
#Override
public void paint(Graphics g) {
g.setColor(Color.BLUE);
g.fillOval(x-rad, y-rad, rad*2, rad*2);
}
}

LibGDX - Map Boundaries

Synopsis
Well, I'm making a little top-down JRPG and today I was like 'Yeah, I'm gonna bust out this whole map collision thing!'. I failed.
Problem
So I went on the internet and looked up 'LibGDX Tiled Map Collision Detection' and found a really neat post about Map Objects so I added in a map object layer and did all that biz and came out with this little method to ensure the player can move freely around the map but at the same time can't exit it but each time I've tried it ends up with a horrible result such as the player moving off the screen. The latest error is that the player gets stuck doing a walk animation and can't move anywhere else!
Code
package com.darkbyte.games.tfa.game.entity.entities;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.maps.objects.RectangleMapObject;
import com.badlogic.gdx.math.Rectangle;
import com.darkbyte.games.tfa.game.entity.Entity;
import com.darkbyte.games.tfa.game.entity.SpriteSheet;
import com.darkbyte.games.tfa.game.world.map.MapManager;
import com.darkbyte.games.tfa.render.Batch;
import com.darkbyte.games.tfa.render.Camera;
public class Player extends Entity {
// The constructor for the player class
public Player(String name, SpriteSheet spriteSheet) {
super(name, spriteSheet);
direction = Direction.DOWN;
collisionBox = new Rectangle(x, y, 64, 64);
}
// A flag to see if the player is moving
private boolean isMoving;
// The variable that holds the state time
private float stateTime;
// The player's walking animations
private Animation[] walkAnimations = {
spriteSheet.getAnimation(8, 8, 1 / 16f),
spriteSheet.getAnimation(9, 8, 1 / 16f),
spriteSheet.getAnimation(10, 8, 1 / 16f),
spriteSheet.getAnimation(11, 8, 1 / 16f) };
// The player's static frames
private TextureRegion[] staticFrames = {
spriteSheet.getTexture(8, 0),
spriteSheet.getTexture(9, 0),
spriteSheet.getTexture(10, 0),
spriteSheet.getTexture(11, 0) };
// The render code for the player
#Override
public void render() {
// Makes the camera follow the player
Camera.setCameraPosition(x, y);
Batch.getGameBatch().setProjectionMatrix(Camera.getCamera().combined);
// Updates the state time
stateTime += Gdx.graphics.getDeltaTime();
// Gets the player's direction, if the player's moving, it sets the
// current frame to the frame that would be played at the current moment
// based on the state time
// If the player isn't moving, it sets the current frame to the static
// frame associated to the direction
switch (direction) {
case UP:
if(isMoving) {
currentFrame = walkAnimations[0].getKeyFrame(stateTime, true);
} else
currentFrame = staticFrames[0];
break;
case LEFT:
if(isMoving) {
currentFrame = walkAnimations[1].getKeyFrame(stateTime, true);
} else
currentFrame = staticFrames[1];
break;
case DOWN:
if(isMoving) {
currentFrame = walkAnimations[2].getKeyFrame(stateTime, true);
} else
currentFrame = staticFrames[2];
break;
case RIGHT:
if(isMoving) {
currentFrame = walkAnimations[3].getKeyFrame(stateTime, true);
} else
currentFrame = staticFrames[3];
break;
}
}
// The tick code for the player
#Override
public void tick() {
// The object to represent the bounds of the land on the map
RectangleMapObject land = (RectangleMapObject) MapManager.getCurrentMap().getMap().getLayers().get("collision").getObjects().get("land");
// Checks if the player is within the bounds of the map
if(land.getRectangle().contains(collisionBox)) {
// If the player is moving but the arrow keys aren't pressed, sets isMoving to false
isMoving = (isMoving && (Gdx.input.isKeyPressed(Keys.W) || Gdx.input.isKeyPressed(Keys.UP)
|| Gdx.input.isKeyPressed(Keys.A) || Gdx.input.isKeyPressed(Keys.LEFT)
|| Gdx.input.isKeyPressed(Keys.S) || Gdx.input.isKeyPressed(Keys.DOWN)
|| Gdx.input.isKeyPressed(Keys.D) || Gdx.input.isKeyPressed(Keys.RIGHT)));
// Checks to see if the arrow / WASD keys are pressed and moves the
// player in the correct direction at the speed of 1.5 pixels/tick
// (45/second)
// It also sets the players state to moving and corresponds it's
// direction to the key pressed
// Doesn't move if opposing keys are pressed
if(Gdx.input.isKeyPressed(Keys.W) || Gdx.input.isKeyPressed(Keys.UP)) {
if(!(Gdx.input.isKeyPressed(Keys.S) || Gdx.input.isKeyPressed(Keys.DOWN))) {
direction = Direction.UP;
y += 1.5f;
isMoving = true;
}
}
if(Gdx.input.isKeyPressed(Keys.A) || Gdx.input.isKeyPressed(Keys.LEFT)) {
if(!(Gdx.input.isKeyPressed(Keys.D) || Gdx.input.isKeyPressed(Keys.RIGHT))) {
direction = Direction.LEFT;
isMoving = true;
x -= 1.5f;
}
}
if(Gdx.input.isKeyPressed(Keys.S) || Gdx.input.isKeyPressed(Keys.DOWN)) {
if(!(Gdx.input.isKeyPressed(Keys.W) || Gdx.input.isKeyPressed(Keys.UP))) {
direction = Direction.DOWN;
y -= 1.5f;
isMoving = true;
}
}
if(Gdx.input.isKeyPressed(Keys.D) || Gdx.input.isKeyPressed(Keys.RIGHT)) {
if(!(Gdx.input.isKeyPressed(Keys.A) || Gdx.input.isKeyPressed(Keys.LEFT))) {
direction = Direction.RIGHT;
x += 1.5f;
isMoving = true;
}
}
} else {
if(!isMoving) {
// If the player's just spawned puts the player to the map's spawn point
x = MapManager.getCurrentMap().getPlayerSpawnX();
y = MapManager.getCurrentMap().getPlayerSpawnY();
} else { // If not, it just moves them back till they're no longer out of the map
if(x > (land.getRectangle().getX() + land.getRectangle().getWidth())) x -= 1.5;
if(y > (land.getRectangle().getY() + land.getRectangle().getHeight())) y -= 1.5;
}
}
// Synchronises the collision box with the player's x and y position
collisionBox.x = x;
collisionBox.y = y;
}
// Returns if the player is moving
public boolean isMoving() {
return isMoving;
}
}
Can you guys make it so that when he reaches the border that he stops but he can still keep moving in other directions instead of staying static!
Thanks for reading!
At the moment it sounds you just copy/pasted it and you need to familiarize yourself with it first. If you don't know what it does then you should learn or stop the project imho.
Anyway, from what I can tell it's just a player class that handles the animation frames based on which direction it is moving. Nothing to do with collision detection at all. It does update some kind of collisionBox but functionality for this is handled elsewhere, perhaps in the parent class Entity?
My guess is that this is a tile map and units are restricted to the grid. It's pretty easy to detect if A tile exists or not.
private boolean tileExists(int tileX, int tileY, tile[][] map)
{
return tileX >= 0 && tileY >= 0 &&
tileX < map.length && tileY < map[0].length;
}
Now whenever a entity requests a move you should check if the destination is within the map bounds.
private void moveRequest(int destinationX, int destinationY, Tile[][] map)
{
//Just return if the tile is outside of the map
if (!tileExists(destinationX, destinationY, map) return;
//Same goes for your other checks...
//Return if the tile is not walkable
if (!tileIsWalkable(destinationX, destinationY, map) return;
//Return if the tile is already occupied
if (tileIsOccupied(destinationX, destinationY, otherEntities) return;
//etc..
//Now the move is valid and you can set it's state to moving in that direction.
}
Tile maps are not very hard to understand. I will make an attempt to give you some better insight into tile maps. You have a 2D array where you store your tiles in. Tiles have a width and a height and from that you can make your own tile engine:
//Find out which tiles to draw based on the camera position and viewport size.
int startX = (int)(camera.position.x - camera.viewportWidth / 2) / tileWidth;
int startY = (int)(camera.position.y - camera.viewportHeight / 2) / tileHeight;
int endX = (int)(startX + camera.viewportWidth / tileWidth) + 1;
int endY = (int)(startY + camera.viewportHeight / tileHeight) + 1;
//Loop using this data as boundaries
for (int y = startY; y < endY; y++)
{
for (int x = startX; x < endX; x++)
{
//If out of bounds continue to next tile.
if (!tileExists(x, y, map) continue;
//Now all we need to draw the on screen tiles properly:
//x == tile position x in array
//y == tile position y in array
//World position of this tile:
//worldX = x * tileWidth;
//worldY = y * tileHeight;
//Let's draw:
batch.draw(map[x][y].getTexture, worldX, worldY,
tileWidth, tileHeight)
}
}
There really is no magic involved here at all. Drawing only what is on screen like in the above example is very important for larger maps. Other then that you should draw thing in the back first. You have several options to do this, the easiest but least versatile is just a separate the ground from the objects that can obscure things and draw this later.
Characters, creatures or other entities can just use a world position and be easily converted back to tile position.
tileX = worldX / tileWidth;
tileY = worldY / tileHeight;
So if you want to move something with the world position calculate it's tile position first using the aforementioned method. Then lookup if this tile is valid to move to. Then block that tile for other and move to it.

Categories

Resources