Collision Detection Error - java

I am currently working on a relatively simple platform game that has an odd bug. You start the game by falling onto the ground (you spawn a few blocks above the ground), but when you land your feet get stuck INSIDE the world and you can't move until you jump. Here's what I mean:
http://i.imgur.com/IKLZY.png
The player's feet are a few pixels below the ground level. However, this problem only occurs in 3 places throughout the map and only in those 3 select places. I'm assuming that the problem lies within my collision detection code but I'm not entirely sure, as I don't get an error when it happens.
public boolean isCollidingWithBlock(Point pt1, Point pt2) {
//Checks x
for(int x = (int) (this.x / Tile.tileSize); x < (int) (this.x / Tile.tileSize + 4); x++) {
//Checks y
for(int y = (int) (this.y / Tile.tileSize); y < (int) (this.y / Tile.tileSize + 4); y++) {
if(x >= 0 && y >= 0 && x < Component.dungeon.block.length && y < Component.dungeon.block[0].length) {
//If the block is not air
if(Component.dungeon.block[x][y].id != Tile.air) {
//If the player is in contact with point one or two on the block
if(Component.dungeon.block[x][y].contains(pt1) || Component.dungeon.block[x][y].contains(pt2)) {
//Checks for specific blocks
if(Component.dungeon.block[x][y].id == Tile.portalBlock) {
Component.isLevelDone = true;
}
if(Component.dungeon.block[x][y].id == Tile.spike) {
Health.health -= 1;
Component.isJumping = true;
if(Health.health == 0) {
Component.isDead = true;
}
}
return true;
}
}
}
}
}
return false;
}
What I'm asking is how I would fix the problem. I've looked over my code for quite a while and I'm not sure what's wrong with it. Also, if there's a more efficient way to do my collision checking then please let me know!
I hope that is enough information, if it's not just tell me what you need and I'll be sure to add it.
Thank you!

The problem probably isn't your collision check, but your logic of what to do on collision. Your character is falling into the block which once in there is always colliding with the block. So it won't be able to jump (since you check for collision when jumping I guess). When you check for collision you have to make sure your character doesn't fall into the block by pre-checking and adjusting.
if (will collide) {
put beside block
}
You're probably doing something like
if (colliding) {
stop moving
}
When putting beside though, you have to check which way you're moving and that you don't move into blocks.

Related

Possible uneven distribution in Java's Random class or bad implementation?

I'm tinkering around with a cellular automaton and my movement detection function is acting really strangely. I'm 80% sure it's my implementation but I have no idea where the issue is. Could someone take a look and enlighten me since I've spent the better part of 7H trying to get it to work and it won't:
private int[] cellularSearch(short xPos, short yPos)
{
// the center position is our current position; the others are potentially free positions
byte[][] positions = new byte[][]{{0,0,0},{0,1,0},{0,0,0}};
int[] result = new int[2];
byte strike=0;
int dice0=0, dice1=0;
while(strike<9)
{
dice0 = r.nextInt(3)-1;
result[0] = xPos + dice0;
if((result[0] >= 0)
&& (result[0] < img.getWidth()))
{
dice1 = r.nextInt(3)-1;
result[1] = yPos + dice1;
if((result[1] >= 0)
&& (result[1] < img.getHeight()))
{
if((positions[dice1+1][dice0+1] != 1)) // if this isn't our own cell and wasn't tried before
{
if(img.getRGB(result[0], result[1]) == Color.white.getRGB()) // if the new cell is free
{
return result;
}
}
positions[dice1+1][dice0+1]=1; // we need to use +1 to create a correlation between the linkage in the matrix and the actual positions around our cell
strike++;
}
}
}
}
The code works and it correctly identifies when a pixel is white and returns the position for it. My problem is the distribution of the results. Given that I'm using Random both for the row and the column, I was expecting a near equal distribution over all possible locations, but what happens is that this code seems to prefer the cell right above the coordinates being fed in (it hits it ~3x as much as the other ones) and the one right below the coordinates (it hits it ~2x as much as the others).
When I start my program and all my pixels slowly move towards the top of the window on EVERY run (vs true randomness with my old lengthy code which was 3x as long), so there's gotta be an error in there somewhere. Could someone please lend a hand?
Thank you in advance!
EDIT: Thank you everyone for the effort! Sorry for the non-compiling code but I extracted the main purpose of the function while cutting out a ton of commented code (my other approaches to implementing this function). Locally the code has the return statement and it runs. I'll slowly go through all your answers in the next few hours (gonna have dinner soon).
EDIT2: I tried what #DodgyCodeException and #tevemadar suggested and made a list with all the 8 positions, then shuffle them each time I enter the function, and then iterate through them, trying each one in part. Still the position exactly above and below the current cell are selected most. I'm baffled. This is my old super-spaghetti code that I've written for this function and it worked perfectly with no errors, equal distribution, and (oddly enough) it's the most efficient implementation that I've tried out of everything mentioned here. After I'm done with lunch and filing some paperwork I'll thoroughly study it (it's been ~ 2 years since I wrote it) to see why it works so well. If anyone still has ideas, I'm fully open.
boolean allRan=false;
int lastDice=0, anteLastDice=0, dice = r.nextInt(3)+1;
//the initial dice usage is for selecting the row on which we'll operate:
//dice = 1 or 3 -> we operate above or under our current cell; dice = 2 -> we operate on the same row
while(!allRan)
{
if((dice==1) || (dice==3))
{
int i= r.nextInt(3);
if(((xPos-1+i) < img.getWidth())
&& ((xPos-1+i) >= 0))
{
if(((yPos-1) >= 0)
&& (img.getRGB(xPos-1+i, yPos-1) == Color.white.getRGB())
&& (dice==1))
{
result[0] = xPos-1+i;
result[1] = yPos-1;
above++;
endTime = (int) System.currentTimeMillis();
section4Runtime += (double) (endTime - startTime) / 1000;
return result;
}
else if(((yPos+1) < img.getHeight())
&& (img.getRGB(xPos-1+i, yPos+1) == Color.white.getRGB())
&& (dice==3))
{
result[0] = xPos-1+i;
result[1] = yPos+1;
below++;
endTime = (int) System.currentTimeMillis();
section4Runtime += (double) (endTime - startTime) / 1000;
return result;
}
}
// if this section is reached, it means that: the initial dice roll didn't find a free cell, or the position was out of bounds, or the dice rolled 2
// in this section we do a dice reroll (while remembering and avoiding our previous values) so that we cover all dice rolls
if(dice==1)
{
if(lastDice==0)
{
lastDice=dice;
dice += r.nextInt(2)+1; // we incrmeent randomly towards 2 or 3.
}
else
{
if(lastDice==2)
{
if(anteLastDice==0)
{
anteLastDice= lastDice;
lastDice=dice;
dice=3;
}
else
{
allRan=true;
}
}
else if(lastDice==3)
{
if(anteLastDice==0)
{
anteLastDice= lastDice;
lastDice=dice;
dice=2;
}
else
{
allRan=true;
}
}
}
}
else // dice is 3
{
if(lastDice==0)
{
lastDice=dice;
dice -= r.nextInt(2)+1; // we decrement randomly towards 2 or 1.
}
else
{
if(lastDice==2)
{
if(anteLastDice==0)
{
anteLastDice= lastDice;
lastDice=dice;
dice=1;
}
else
{
allRan=true;
}
}
else if(lastDice==1)
{
if(anteLastDice==0)
{
anteLastDice= lastDice;
lastDice=dice;
dice=2;
}
else
{
allRan=true;
}
}
}
}
}
if(dice==2)
{
int i=0;
i += r.nextInt(2)==0?-1:1;
if(((xPos+i) < img.getWidth())
&& ((xPos+i) >= 0)
&& (img.getRGB(xPos+i, yPos) == Color.white.getRGB()))
{
result[0] = xPos+i;
result[1] = yPos;
leveled++;
endTime = (int) System.currentTimeMillis();
section4Runtime += (double) (endTime - startTime) / 1000;
return result;
}
// same as above: a dice reroll (with constrictions)
if(lastDice==0)
{
lastDice=dice;
dice+= r.nextInt(2)==0?-1:1; // randomly chose if you decrement by 1 or increment by 1
}
else
{
if(lastDice==1)
{
if(anteLastDice==0)
{
anteLastDice= lastDice;
lastDice=dice;
dice =3;
}
else
{
allRan=true;
}
}
else if(lastDice==3)
{
if(anteLastDice==0)
{
anteLastDice= lastDice;
lastDice=dice;
dice =1;
}
else
{
allRan=true;
}
}
}
}
}
return result;
After much thought, I eventually figured it out. All the ideas that we all had were violating a fundamental "rule" of the first implementation that I was using: the first implementation was trying a random position on one of the 3 lines, then moving on to the next lines (without coming back to try the other positions on that line). Example: if the algo selected the line above, it would randomly try the top-left corner to see if it's free; if it wasn't then it would try the same line as the current cell and the line below (again, just with 1 of their possible positions) without coming back. All our ideas were iterating through all possibilities around the cell, which meant that it was inevitable to have the top and bottom line have more hits than the middle (since top and bottom have 3 possible points each while middle has only 2). Also, when there were holes in the field, the cells most likely to fill it up were the ones that were moving diagonally (which in the end is up or down) or those directly moving up or down, since those moving sideways only had the options left/ right. The only mystery that will remain unsolved is why (using our proposed implementations) the model would generally use the point exactly above our current cell. I have no idea why it loves going straight up most of the time with that implementation. Nevertheless, the new algorithm (which reflects the old one, but is much lighter) is:
boolean[] lines = new boolean[]{false, false, false};
byte checks =0;
while(checks < 3) // just 3 tries in total
{
dice = r.nextInt(3);
if(lines[dice]== false)
{
lines[dice] = true; // just 1 try per line
// calculated here since we reuse dice below
result[1] = yPos - 1 + dice; // will be above if dice==0; will be below if dice==2; same line if dice==1
if((dice == 0) || (dice == 2)) // top/bottom line
{dice = r.nextInt(3)-1;}
else if(dice == 1) // middle line
{dice = r.nextInt(2)==0?-1:1;} // we exclude the middle point since that's our current position
result[0] = xPos + dice; // logic is calculated above and just applied here
checks++;
}
if((result[0] >= 0)
&& (result[0] < img.getWidth())
&& (result[1] >= 0)
&& (result[1] < img.getHeight()))
{
if (img.getRGB(result[0], result[1]) == Color.white.getRGB()) // if the new cell is free
{
return result;
}
}
}
result[0] = -1; // in case we get here, reset the value so it's not used
This brings the code down from 167 lines to 33 lines (and makes it MUCH more readable). I have no idea who to select as the best solution. Please suggest if you have any ideas.
First, I have to admit I can't see what your algorithm is supposed to be doing -- it's not clear to me why you roll the each die when you do, other times using the existing value.
For a clear, easy to follow algorithm, I'd suggest scoping your dice variables inside the loop, rolling both at the same time, and making them final so that you know that each iteration has exactly one two-die roll:
while(strike < 9) {
final int roll1 = r.nextInt(3) - 1;
final int roll2 = r.nextInt(3) - 1;
strike += handleRoll(roll1,roll2);
}
You can prove the distribution to yourself by writing a simple counter for your handleRoll(), before later substituting your real code.
int[] counts = int[6];
void handleRoll(int roll1, int roll2) {
counts[1 + roll1] ++;
counts[4 + roll2] ++;
return 1;
}
(Increase the required strike count to get large enough samples to reason about)
Make sure you use the same instance of Random throughout the program -- don't keep making new ones.
(You could tidy this up a bit by creating a Coordinate class and a factory that creates random ones)
I simplified your code like this:
made a series of extract-method refactorings to tidy away detail
changed your rolls to use the range 0 to 2 instead of -1 to +1 -- since you use them in two places, and in one of those you add one again!
used x and y and only create result when needed
used final for the rolls and the resulting x and y, scoping them to the inside of the loop
turned nested ifs into an && logic
changed some odd type choices. The positions grid seems made for boolean. There's seldom any value in using short in Java.
So:
private int[] cellularSearch(int xPos, int yPos) {
boolean[][] positions =
new boolean[][] { { false, false, false },
{ false, true, false },
{ false, false, false } };
int strike = 0;
while (strike < 9) {
final int dice0 = r.nextInt(3);
final int dice1 = r.nextInt(3);
final int x = xPos + dice0 - 1;
final int y = yPos + dice1 - 1;
if (isInXrange(x) && isInYRange(y)) {
if (!alreadyTried(positions, dice1, dice0) && isWhite(x, y)) {
return new int[] { x, y };
}
markAsTried(positions, dice1, dice0);
strike++;
}
}
return null; // or whatever you intend to happen here
}
private boolean isInXrange(int x) {
return (x >= 0) && (x < img.getWidth());
}
private boolean isInYRange(int y) {
return (y >= 0) && (y < img.getHeight());
}
private boolean alreadyTried(boolean[][] positions, final int dice1, final int dice0) {
return positions[dice1 + 1][dice0 + 1];
}
private static void markAsTried(boolean[][] positions, int dice1, int dice0) {
positions[dice1][dice0] = true;
}
private boolean isWhite(final int x, final int y) {
return img.getRGB(x, y) == Color.white.getRGB();
}
I think this is equivalent to your code, with one exception -- yours doesn't roll the second die if the first roll takes you outside the width of the image. You could re-add this as a performance improvement later if you like.
But it exposes some issues. It looks as if the intent is to try every cell (you have a 3x3 grid, and you've chosen 9 "strikes") - but it doesn't increment strike when x,y is outside the image. It does increment strike when the position has been tried before. So you can exit the loop having not tried every cell.
I don't see a specific way that this causes the weighting you've described --
but it looks like the sort of thing that could lead to unexpected results.
(Anyway - since the code you've given doesn't compile, you didn't observe it with the code you've given us)
If the intention is to check every cell, it might be better to shuffle a list of cells to try, then test them in order:
List<Coords> coordsToTry = new ArrayList<>();
for(int x=0; x<2; x++) {
for(int y=0; y<2; y++) {
coordsToTry.add(new Coords( x, y));
}
}
Collections.shuffle(coordsToTry);
for(Coords coords : coordsToTry) {
if(isWhite(coords)) {
return coords;
}
}
return null; // or whatever is meant to happen when nothing found
The distribution of java.util.Random is not that uneven. You can confirm with the following code:
public static void main(String[] args) throws Exception {
final int N = 3;
Random r = new Random();
int[] counts = new int[N];
for (int i = 0; i <= 100_000; i++) {
counts[r.nextInt(N)]++;
}
System.out.println(Arrays.toString(counts));
}
UPDATE:
As you've said, the above code produces fairly evenly distributed values. However, add the following line at the beginning of the loop:
if (i % 6 == 0)
r = new Random(0);
And then you get [16667, 33334, 50000]. One value occurs twice as frequently, and another 3 times as frequently, as the first. This sets the random number generator to a newly created one with a constant seed. It simulates your code, in which you say you create a new Random() on entry to your function (albeit without a seed argument) and then your function calls nextInt() six times - this if (i % 6 == 0) statement ensures a new RNG is also created every 6 iterations.
Check your code and make sure you are only ever creating a RNG once in your whole program.
java.util.Random is a pseudorandom number generator (definition on wikipedia) and needs to be seeded.
From the docs:
If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. In order to guarantee this property, particular algorithms are specified for the class Random.
If you want to be sure to get good random numbers, use SecureRandom, which is guaranteed to produce non-deterministic output
Since you are interested in the combined distribution of the two 'dices', on top of #DodgyCodeException's suggestion, you can check statistics like
public static void main(String[] args) {
Random r=new Random();
int stat[]=new int[9];
for(int i=0;i<9000;i++)
stat[r.nextInt(3)+r.nextInt(3)*3]++;
for (int i : stat)
System.out.println(i);
}
However it is pretty even too.
There is a minor difference between generating random numbers from a power-of-two-range and otherwise, so if you really want to do some magic, you can use the fact that you are actually picking a position out of 8 possibilities (since the middle one is ruled out at the beginning).
Something like
final int xhelper[]=new int[]{-1, 0, 1,-1, 1,-1, 0, 1};
final int yhelper[]=new int[]{-1,-1,-1, 0, 0, 1, 1, 1};
...
int dir=r.nextInt(8);
int dice0=xhelper[dir];
int dice1=yhelper[dir];
But in fact I do not think it makes a difference.

Line and point collision in java

I'm making a tron game and have everything except for the collision. Currently making it through MVC (required as it is an AP Compsci project) and I am having trouble with the collision between the trail and the bike. My idea is to have a point on the racer to which it collides with (the front point). The light trails are drawn with a list of points, the first point being the start point and each point after are added when the racer turns. The last point is the current location of the bike. It draws a line between each point in paintComponent, and also uses a method in the Line class (which contains the arraylist of points) to check collision. So far I have tried to see if the front point is on any of the axis (that is, if the x or y value is equal to any of the corresponding x or y pvalues on the line) and then check the opposite coordinate and check if the x or y is in between the x or y of two points on that axis, and return true or false if they are. Here is what I mean:
public boolean checkPoint(Point p)
{
for(int k = points.size() - 1; k > 0;k -= 2)
{
//if the x's are the same ( vertical ), check if within y's
if(p.getX() == points.get(k).getX() && p.getX() == points.get(k - 1).getX())
{
if(points.get(k).getY() > points.get(k - 1).getY()){
if(p.getY() < points.get(k).getY() && p.getY() > points.get(k-1).getY())
return true;
}
if(points.get(k).getY() < points.get(k - 1).getY()){
if(p.getY() > points.get(k).getY() && p.getY() < points.get(k-1).getY())
return true;
}
}
// if the y's are the same (horizontal), check if within x's
if(p.getY() == points.get(k).getY() && p.getY() == points.get(k - 1).getY())
{
if(points.get(k).getX() > points.get(k - 1).getX()){
if(p.getX() < points.get(k).getX() && p.getX() > points.get(k-1).getX())
return true;
}
if(points.get(k).getX() < points.get(k - 1).getX()){
if(p.getX() > points.get(k).getX() && p.getX() < points.get(k-1).getX())
return true;
}
}
}
}
The game either runs really slowly after a few seconds and works, or doesn't work at all. Am I going in the right direction, how should I go about this?

Players appear to be colliding with air?

(Will be putting a bounty on this - Also, I'm not 100% sure what tags are relevant for this)
I'm incredibly confused here. I am attempting to use this (simplified) model for my archers to collide with:
However, as you can see, my archers appear to be colliding in mid-air! I would understand if they fell through (e.g. I had not put enough "points" in my collision model), but to actually appear to be colliding with NOTHING is absolutely baffling me.
I'm loading the model on the server with the same code that I'm displaying it there in the client, so that can't be the issue. I've pastebinned it here anyway.
Then, I'm adding it to three int[] arrays, like this:
coordsx = new int[80 * 10];
coordsy = new int[80 * 10];
coordsz = new int[80 * 10];
for (javax.vecmath.Vector3f vec : m.getVertices()){ //Quick note: M is a model. As you can see, I'm just going through all the vertex positions.
coordsx[DELTA+(int) vec.x] = 1;
coordsy[DELTA+(int) vec.y] = 1;
coordsz[DELTA+(int) vec.z] = 1;
}
Quick note: DELTA is the value of ((80 * 10) / 2) or to save you the math, 400. Also, I used three int[]'s and not an int[][][] because an int[][][] caused an OutOfMemory which I couldn't fix.
Now that I have got these arrays of coordinates, I'm using this code to check it:
for (int x = (int) (location.x + 1); x > location.x - 1; x--){
for (int y = (int) (location.y + 1); y > location.y - 1; y--){
for (int z = (int) (location.z + 1); z > location.z - 1; z--){
distancex = x;
distancez = z;
distancey = y;
try{
int i = 0;
if (owner.type == 0){
if (GameServer.DELTA + distancex > 0 && GameServer.DELTA + distancex < 800 && GameServer.coordsx[(int) (GameServer.DELTA + distancex)] == 1){
if (GameServer.DELTA + distancey > 0 && GameServer.DELTA + distancey < 800 && GameServer.coordsy[(int) (GameServer.DELTA + distancey)] == 1){
if (GameServer.DELTA + distancez > 0 && GameServer.DELTA + distancez < 800 && GameServer.coordsz[(int) (GameServer.DELTA + distancez)] == 1){
i = 1;
}
}
}
}
if (i == 1){
collision = true;
YDown = 0;
}
}catch (ArrayIndexOutOfBoundsException e1){
e1.printStackTrace();
}
}
}
}
if (collision){
System.out.println("Collision!");
}else{
System.out.println("No Collision!");
location.y = location.y-=YDown;
}
location is a Vector3f of the archers' X, Y, and Z relative to the ship's location - I've checked this using de-bug messages, and the location is indeed returning correctly.
As you can see, the variable i is only being set to 1 if there is a coordinate at both the X, Y, and Z location of the point that is being checked. Obviously, I am iterating through all the nearby coordinates as well, since my player is not just a single point.
Since the player appears to be colliding with air, then there is obviously something wrong. But I cannot find what.
Am I on the right track here, or am I doing everything entirely wrong? And if I am on the right track, then what is going wrong here and how can I fix it?
There is a problem with your model. Using three arrays may save memory, but it also changes the model, creating "shadows" that your archers can collide with.
Let's say that you have vertices in (1,1,1) and (2,2,2).
Using your model, there will also a vertex at (1,2,2) and any other combination where all coordinates is either 1 or 2.
So, back to the drawing board.
Maybe you can save memory by using a single bit instead of a 32 bit int for each coordinate?
Or you could change the way you store the model. What if you use a 2-dimensional array of int and store the z-coordinate(s) of the floor. This would limit your world to one (or just a few) floors at each x,y-coordinate but would save a huge amount of memory.

Program using loops and random generator (beginning java)

A drunkard in a grid of streets randomly picks one of four directions and stumbles to the next intersection, then again randomly picks one of four directions, and so on. You might think that on average the drunkard doesn't move very far because the choices cancel each other out, but that is not the case. Represent locations as integer pairs (x,y). Implement the drunkard's walk over 100 intersections, starting at (0,0) and print the ending location
Can anyone help? I'm completely lost with using random generators and loops in the same program
Below is what I have. It complies fine but doesn't print anything and I'm not sure if I got the random 100 intersection thing right
import java.util.*;
class Drunkard {
int x, y;
Drunkard(int x, int y) {
this.x = x;
this.y = y;
}
void moveNorth() {
this.y -= 1;
}
void moveEast() {
this.x += 1;
}
void report() {
System.out.println("Hiccup: " + x + ", " + y);
}
}
class Four {
public static void main(String[] args) {
Random generator = new Random();
Drunkard drunkard = new Drunkard(100, 100);
int direction;
for (int i = 0; i < 100; i++) {
direction = Math.abs(generator.nextInt()) % 4;
if (direction == 0) { // N
drunkard.moveNorth();
} else if (direction == 1) { // E
drunkard.moveEast();
} else if (direction == 2) { // S
System.out.println("Should move South.");
} else if (direction == 3) { // W
System.out.println("Should move West.");
} else {
System.out.println("Impossible!");
}
System.out.drunkard.report();
}
}
}
your program will be:
initialization
loop: for 1 to 100, do:
i = random()
if i<=0.25 : go north
if i>0.25 and i<=0.5 : go south
if i>0.5 and i<= 0.75 : go east
if i>0.75 and i<= 1 : go west
end loop
show final point.
I see a variety of problems:
You are initializing your Drunkard's position to 100,100. The assignment said to initialize to 0,0.
System.out.drunkard.report() absolutely does not compile. Just call drunkard.report().
The instructions say to print the final location, so you need to move the call to drunkard.report() down one line, so that it is outside of the for loop.
You haven't written methods for moveSouth or moveWest. Write them and add calls to them in the appropriate place.
The class Four needs to be public in order to run it directly.
Good Java programming practices say that every class should be in its own file, but this probably goes against what your instructor asked you to do.
But, I don't think that's your problem. I think there's a problem with how/where you're trying to run the program. You say it compiles fine but doesn't print any output. You know that after it compiles there is another step to run the program, right?
To be clear, here's what you should be doing. At a command line, make sure you are in the directory where your .java file lives. I'm going to assume it's called Four.java. Type the following, hitting enter after each line. (Don't type the $ prompt)
$ javac *.java
$ java Four
I copied the code you posted above, fixed the problems I highlighted, and followed my own instructions above; it works perfectly.
You can use
int direction = (new Random()).nextInt(4);
And use this direction variable to determine where he walks to. I would use recursion in this case instead of a loop.
This starts at 0,0. Generates a random number to determine location and updates the location.
Not sure about the way you are generating the random number, this seems to work well for me.
Point currentLocation = new Point();
currentLocation.setLocation(0, 0);
Point newLocation = new Point(0,0);
Random random = new Random();
//make 100 moves
for(int i=0; i<100; i++)
{
int k = random.nextInt(4);
if(k == 0)
{
//use your drunkard method here
newLocation.setLocation(currentLocation.getX(), currentLocation.getY() + 5);
}
else if (k == 1)
{
//go south
newLocation.setLocation(currentLocation.getX(), currentLocation.getY() - 5);
}
else if (k == 2)
{
//go east
newLocation.setLocation(currentLocation.getX() + 5, currentLocation.getY());
}
else if(k == 3)
{
//go west
newLocation.setLocation(currentLocation.getX() - 5, currentLocation.getY());
}
currentLocation.setLocation(newLocation);
}
System.out.println(currentLocation);
}
You're not implementing your random generator to its full extent.
Random generator = new Random();
int direction = generator.nextInt(4); // This will return a random int
// between 0 and 3
Some other useful tricks when using Random() are as follows:
int i = generator.nextInt(4)+2; // This will return a random int
// between 2 and 5
I highly recommend you check out this if you'd really like to learn all of the neat tricks that you can do using the Random Class.
All i did for this is create a loop that generated a random number between -1 and 1, and summed the values 100 times. Do that for x and for y.
int x = 0;
int y = 0;
//intial = (0,0)
//North = (0, 1)
//South = (0, -1)
//East = (1, 0)
//West = (-1, 0)
for(int i = 0; i < 100; i++)
{
x += (int) (Math.random() * 3) + (-1);
y += (int) (Math.random() * 3) + (-1);
}
System.out.printf("The Drunkard is now located at: (%d, %d)", x, y);

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