Java LibGDX Multi Touch Movement - java

What is the problem? I am using this code to movement for two players. But it is not working. Player1 is more quick than player2. How can I fix?
for (byte i = 0; i < 20; i++) {maxDistance = 10 * Gdx.graphics.getDeltaTi
me();
if (Gdx.input.isTouched(i) && Gdx.input.getY()<= 400) {
player1TouchPosition.set(Gdx.input.getX(i), Gdx.input.getY(i), 0);
camera.unproject(player1TouchPosition);
}
player1Tmp.set(player1TouchPosition.x, player1TouchPosition.y).sub(player1Rectangle.x, player1Rectangle.y);
if (player1Tmp.len() <= maxDistance) {
player1Rectangle.x = player1TouchPosition.x;
player1Rectangle.y = player1TouchPosition.y;
} else {
player1Tmp.nor().scl(maxDistance);
player1Rectangle.x += player1Tmp.x;
player1Rectangle.y += player1Tmp.y;
}
if (Gdx.input.isTouched(i) && Gdx.input.getY() >= 401) {
player2TouchPosition.set(Gdx.input.getX(i), Gdx.input.getY(i), 0);
camera.unproject(player2TouchPosition);
}
player2Tmp.set(player2TouchPosition.x, player2TouchPosition.y).sub(player2Rectangle.x, player2Rectangle.y);
if (player2Tmp.len() <= maxDistance) {
player2Rectangle.x = player2TouchPosition.x;
player2Rectangle.y = player2TouchPosition.y;
} else {
player2Tmp.nor().scl(maxDistance);
player2Rectangle.x += player2Tmp.x;
player2Rectangle.y += player2Tmp.y;
}
}

Two errors jump out at me:
You used getY() instead of getY(i) in a couple of places, so the criteria are mixed up for any pointer besides the most recent one.
You wrapped it all in a loop that runs 20 times, so you are moving each player 20 times a frame instead of one time each, at most. The movement should be applied outside the loop.
This problem is more complicated than it initially looks, because you have to deal with rejecting extra fingers on either side of the screen. Suppose pointer 1 is a finger on the top half of the screen. If pointer 2 is a finger on the top half, you want to reject it, but if it's on the bottom half, you want to use it to move player 2. If pointers 1 and 2 are both on the top, you want to accept pointer 3 only if it's on the bottom but you want to always reject it if pointers 1 and 2 are on opposite sides.
Furthermore, if only one finger is down, but it slides across the boundary to the other side, you want to be sure you don't let it start controlling the opposite player.
Here's one possible strategy. Track the first pointer down on each side and reset it whenever the tracked pointer is released. Only update target positions for the two currently tracked pointers.
private int player1Pointer = -1, player2Pointer = -1;
// render():
//stop tracking released fingers
if (player1Pointer >=0 && !Gdx.input.isTouched(player1Pointer))
player1Pointer = -1;
if (player2Pointer >=0 && !Gdx.input.isTouched(player2Pointer))
player2Pointer = -1;
//check for new pointers and update target positions
for (int i = 0; i<20; i++){
if (!Gdx.input.isTouched(i))
continue;
if (Gdx.input.getY(i) <= 400){ //bottom, player 1
if (player2Pointer == i)
continue; //player 2 slid finger across boundary, ignore it
if (player1Pointer < 0)
player1Pointer = i; //first finger down on this side of screen, track it
if (player1Pointer == i){ //this is the tracked finger, update target
player1TouchPosition.set(Gdx.input.getX(i), Gdx.input.getY(i), 0);
camera.unproject(player1TouchPosition);
}
} else { //top, player 2
if (player1Pointer == i)
continue;
if (player2Pointer < 0)
player2Pointer = i;
if (player2Pointer == i){
player2TouchPosition.set(Gdx.input.getX(i), Gdx.input.getY(i), 0);
camera.unproject(player2TouchPosition);
}
}
}
//update movement toward targets
maxDistance = 10 * Gdx.graphics.getDeltaTime();
temp.set(player1TouchPosition.x, player1TouchPosition.y).sub(player1Rectangle.x, player1Rectangle.y);
if (temp.len() <= maxDistance) {
player1Rectangle.x = player1TouchPosition.x;
player1Rectangle.y = player1TouchPosition.y;
} else {
temp.nor().scl(maxDistance);
player1Rectangle.x += temp.x;
player1Rectangle.y += temp.y;
}
temp.set(player2TouchPosition.x, player2TouchPosition.y).sub(player2Rectangle.x, player2Rectangle.y);
if (temp.len() <= maxDistance) {
player2Rectangle.x = player2TouchPosition.x;
player2Rectangle.y = player2TouchPosition.y;
} else {
temp.nor().scl(maxDistance);
player2Rectangle.x += temp.x;
player2Rectangle.y += temp.y;
}

Related

Velocity never hitting 0 when key released in Java

I am trying to make it so if you are, lets say, moving right and you let go of your arrow key, you will slow down then stop, not just stop immediately. Here is how I am doing this:
//If you clicked right arrow key and you're not going
//Faster then the max speed
if(moveRight && !(vel.x >= 3)){
vel.x += movementSpeed;
//If you let go of arrow key, slow down at 3/2 the speed you were moving
}else if(vel.x >= 0 && !moveRight){
vel.x -= movementSpeed * 1.5f;
}
However, for some reason, this sometimes works. Other times, you will notice that the velocity is at about 0.00523329 or something very small like that. I don't understand why because the else if statement says to slow down until you are equal to 0 essentially. I need the velocity to reach 0. Any help in this regard is extremely appreciated!
else if statement says to subtrack movementSpeed * 1.5f, nothing more.
Code below always prints 0.0:
boolean moveRight = false;
Velocity vel = new Velocity();
vel.x = 4;
float movementSpeed = 3;
while (vel.x != 0) {
if(moveRight && !(vel.x >= 3)) {
vel.x += movementSpeed;
}
else if(vel.x >= 0 && !moveRight) {
vel.x -= movementSpeed * 1.5f;
}
if (vel.x <= 0) {
vel.x = 0;
}
}
System.out.println(vel.x);
Maybe you forgot about loop. Please, paste more code.

Java Monopoly Game

I made a Board and I set the board's layout to null. So I position my token's by moving them pixel by pixel. But when turning the corners I am having a trouble. After first 10 position token can make the turn and continue for the next 10 position. But it is impossible for my token to make the 2. turn.
Can anyone advice me a better code for this problem. I think I make things get more complicated than it is.
if(g.getPosx() <= 650 && g.getPosx() >= 50 && g.getPosy()==650) {
if(g.getPosx()-unitChange*d.getDice() <= 50) {
temp = unitChange*d.getDice() - (g.getPosx() - 50);
g.setPosx(50);
g.setPosy(g.getPosy()-temp);
}
else {
g.setPosx(g.getPosx()-unitChange*d.getDice());
temp = 0;
}
}
else if(g.getPosy() <= 650 && g.getPosy() >= 50 && g.getPosx()==650) {
if(g.getPosy()-unitChange*d.getDice() <= 50) {
temp = unitChange*d.getDice() - (g.getPosy() - 50);
g.setPosy(50);
g.setPosx(g.getPosx()-temp);
}
else {
g.setPosy(g.getPosy()-unitChange*d.getDice());
temp = 0;
}
}
else if(g.getPosx() <= 650 && g.getPosx() >= 50 && g.getPosy()==50) {
if(g.getPosx()-unitChange*d.getDice() <= 50) {
temp = unitChange*d.getDice() - (g.getPosx() - 50);
g.setPosx(50);
g.setPosy(g.getPosy()-temp);
}
else {
g.setPosx(g.getPosx()-unitChange*d.getDice());
temp = 0;
}
}
else if(g.getPosy() <= 650 && g.getPosy() >= 50 && g.getPosx()==50) {
if(g.getPosy()-unitChange*d.getDice() <= 50) {
temp = unitChange*d.getDice() - (g.getPosy() - 50);
g.setPosy(50);
g.setPosx(g.getPosx()-temp);
}
else {
g.setPosy(g.getPosy()-unitChange*d.getDice());
temp = 0;
}
}
Instead of using the current X and Y positions to track which location the piece is stopped on, try tracking which property the piece has landed on instead. so property 1 would be the first stop on the board after GO all the way up to boardwalk at position 39. Then you can have a function like
movePlayerToLocation(Player player, int location){
// calculate your x and y based on the property locatoin
if(locatoin < 11){
// on first edge
} else if (location < 21) {
// on second edge
} else if (location < 31)
// on third edge
} else {
// on fourth edge of the board
}
// do your g.setPos-ing
}

Avoid out of bounds exception in 2D array

I'm trying to solve a problem which uses a 2D array, the problem of a rat in a maze.
While checking the conditions trying to compile, it finds an Array index out of bounds exception... how can I check the values so it doesn't go out of the array bounds?
static void solveMaze(){
int nSteps = 0; // Number of steps.
int x = 0; int y = 0; // Starting point.
boolean mazeCompleted = false;
while (!mazeCompleted){
if(x == maze.mazeMatrix.length && y == maze.mazeMatrix.length)
mazeCompleted = true;
else if(maze.mazeMatrix[x+1][y] == 0){ // Move right.
maze.mazeMatrix[x+1][y] = 2;
x++; nSteps++;
}
else if(maze.mazeMatrix[x-1][y] == 0){ // Move left.
maze.mazeMatrix[x-1][y] = 2;
x--; nSteps++;
}
else if(maze.mazeMatrix[x][y+1] == 0){ // Move down.
maze.mazeMatrix[x][y+1] = 2;
y++; nSteps++;
}
else if(maze.mazeMatrix[x][y-1] == 0){ // Move up.
maze.mazeMatrix[x][y-1] = 2;
y--; nSteps++;
}
}
maze.printMatrix();
System.out.println("Maze COMPLETE! - With a total of " + nSteps + " steps.");
}
Tried before with two "for" loops to prevent the out of bounds but I just can't go diagonal in this problem.
You have a pretty crucial bug in your program. You will never reach the end of the maze!
if(x == maze.mazeMatrix.length && y == maze.mazeMatrix.length)
references indices that are out of bounds! It should be
if(x == maze.mazeMatrix.length - 1 && y == maze.mazeMatrix.length - 1)
You also need to check to see whether you can & should move before you try to move there. I.E. :
while (!mazeCompleted){
boolean moveRight = (x + 1 < mazeMatrix.length && maze.mazeMatrix[x+1][y] == 0 ? true : false);
boolean moveLeft = (x - 1 >= 0 && maze.mazeMatrix[x-1][y] == 0 ? true : false);
boolean moveUp = (y + 1 < mazeMatrix[x].length && maze.mazeMatrix[x][y+1] == 0 ? true : false);
boolean moveDown = (y - 1 >= 0 && maze.mazeMatrix[x][y-1] == 0 ? true : false);
And:
else if(moveRight) { // Move right.
maze.mazeMatrix[x+1][y] = 2;
x++; nSteps++;
}
etc. Although it does seem like this is something that should be solved recursively, as if there are any loops in the maze you will end up getting stuck and infinite looping.

Moving a model between 3 points results in the model out of position

I have a cube and I am moving it between 3 points (float positions) only on the x axis. So the cube will start at 0.00 I press the right key and it moves right on the x axis to 2.0f. I then press the left key and it moves back to 0.0f. I then press the left key again and it moves to -2.0f. Pressing the right key should now return it to 0.0f but instead it goes beyond 0. and the size of the error depends on the speed I move at.
This also has the same result if i start with the left key.
if(MoveLeftFlag == true)
{
if(PositionFlag == 0)
{
if(Cube1.PositionX > MinCubeMovement)
{
Cube1.MoveLocalX(-CubeMoveSpeed * FrameTime );
}
else if(Cube1.PositionX < MinCubeMovement)
{
PositionFlag = -1;
MoveLeftFlag = false;
}
}
if(PositionFlag == 1)
{
if(Cube1.PositionX > Middle)
{
Cube1.MoveLocalX(-CubeMoveSpeed * FrameTime );
}
else if(Cube1.PositionX < Middle)
{
MoveLeftFlag = false;
PositionFlag = 0;
}
}
}
if(MoveRightFlag == true)
{
if(PositionFlag == 0)
{
if(Cube1.PositionX < MaxCubeMovement)
{
Cube1.MoveLocalX(CubeMoveSpeed * FrameTime );
}
else if(Cube1.PositionX > MaxCubeMovement)
{
MoveRightFlag = false;
PositionFlag = 1;
}
}
if(PositionFlag == -1)
{
if(Cube1.PositionX < Middle)
{
Cube1.MoveLocalX(CubeMoveSpeed * FrameTime );
}
else if(Cube1.PositionX > Middle)
{
MoveRightFlag = false;
PositionFlag = 0;
}
}
}
FrameTime is float frametime = getTimeInMillSeconds()/1000;
and the speed is set to `0.000001f; which moves it at a nice smooth speed for me.
As i said if i make the speed greater then when the cube is returning to 0.0f for the second time the offset error becomes greater.
Can anyone point me in the right direction.
Ok Well i have fixed the problem,surprised i didnt pick up on this but basically i was using < and > when i should have been using >= and <=.

2D Collision Detection between squares, simple but more specific than boolean + immune to large spacial jumps

Would like to know which direction player hits terrain tile from (just a simple up/down, left/right). Everything I find is either too simple, or is much more complex and seemingly way too much for what I need, like with AABB (granted it's hard to tell, my brain has trouble digesting what amounts to really long equations). What I've got so far is the result of spending better part of today reading and experimenting:
public int move(double toX, double toY) {
int col = COLLISION_NONE; //these are bit flags, in case I collide with a block to my right as well as below me
double nextX = mX+(toX*main.getDelta()); //delta regulates speed
double nextY = mY+(toY*main.getDelta());
if(mTerrainCollision){
int w = GameView.GameLoop.TILE_WIDTH;
int h = GameView.GameLoop.TILE_HEIGHT;
for(int i = -2; i <= 2; i++) //broad tile picking will be optimized later, better trace around players path
for(int j = -2; j <= 2; j++) {
GameTerrain.Block block = main.mTerrain.get(((int)Math.round(mX)/w)+i,((int)Math.round(mY)/h)+j);
if(block.type != GameTerrain.BLOCK_TYPE_NONE) {
if(nextX+w >= block.x() && mX+w <= block.x()){ //COLLISION ON THE RIGHT?
if(mY+h > block.y() && mY < block.y()+h) { //<THIS is a problem line, see below
nextX = block.x() - w;
xMomentum = 0;
col |= COLLISION_RIGHT;
}
}
else if(nextX < block.x()+w && mX >= block.x()+w){ //COLLISION ON THE LEFT?
if(mY+h > block.y() && mY < block.y()+h) { //same as above, make sure were on the same plane
nextX = block.x() + w;
xMomentum = 0;
col |= COLLISION_LEFT;
}
}
if(nextY+h >= block.y() && mY+h <= block.y()){ //COLLISION ON THE BOTTOM?
if(mX+w > block.x() && mX < block.x()+w) { //make sure were on the same plane
nextY = block.y() - h;
yMomentum = 0;
col |= COLLISION_DOWN;
}
}
else if(nextY < block.y()+h && mY >= block.y()+h){ //COLLISION ON THE TOP?
if(mX+w > block.x() && mX < block.x()+w) { //make sure were on the same plane
nextY = block.y() + h;
yMomentum = 0;
col |= COLLISION_UP;
}
}
}
}
}
mX = nextX;
mY = nextY;
return col;
}
It works... mostly. Player won't phase through blocks even after long sleeps making the delta skyrocket. The collision detection itself works unless the player's previous position (mX/mY) are not on the same plane as the block we're checking (see commented line with "THIS..."). Say we're perfectly diagonal to a block and moving straight for it, player will zip right through. I've been scratching my head for a while now trying to figure out how to go about solving this last issue, preferably without a major rehaul of everything, but if it had to come to that oh well! I'm only interested in simple collision data for things like "Did I touch a floor this frame? Ok I can jump", "Am I touching a wall right now? Ok I can wall jump, but not if I also touched a floor", etc.
Grow the wall's AABB by the size of the object's AABB (keeping the center of the wall's AABB fixed), construct a line segment from the object's before and after positions (use the center of the object's AABB), then do a segment-AABB intersection test.

Categories