Reading through an array 2d from center to corners - java

So for this java project I´m working on I need a loop that reads trough an 2d array from center first then 4 adjecent values then the corners of that and keep doing that till it reaches and completes the most outer layer. I need it to work on all odd sizes of square 2d arrays. I made this image to clarify my goal: http://gyazo.com/80ed4502cb16795d37b75a14ee57f565 . I personally was not able to achieve this. Thank you for your time! any piece of pseudo code or java code is welcome!

You could logically redefine the grid so that the center is 0,0.
Then, sort each grid coordinate according to distance from the center.
This assumes that the grid is an odd width.
For example:
class Point
{
int x;
int y;
}
Point gridCenter;
Comparator<Point> comparator = new Comparator<Point>()
{
#Override
public int compare(Point arg0, Point arg1)
{
int x = arg0.x - gridCenter.x;
int y = arg0.y - gridCenter.y;
int distance0 = x*x + y*y;
x = arg1.x - gridCenter.x;
y = arg1.y - gridCenter.y;
int distance1 = x*x + y*y;
return distance0 - distance1;
}
};
void test()
{
int width = 11;
int height = 13;
gridCenter = new Point();
gridCenter.x = width/2;
gridCenter.y = height/2;
List<Point> points = new ArrayList<>();
for(int x=0;x<width;x++)
{
for(int y=0;y<height;y++)
{
Point p = new Point();
p.x = x;
p.y = y;
points.add(p);
}
}
Collections.sort(points, comparator);
for(Point p : points)
{
System.out.println(p.x + "," + p.y);
}
}
You could bias center slightly if you want to guarantee that it chooses left,top before right,bottom in the sort.

Related

I am trying to add collision detection to this particle system I made

I am doing this in processing which is essentially java and I have never attempted anything like this before. Can't find any examples of collision detection using arrays to map the pixels.
I am not really trying to make them realistic collisions. I was thinking it would have the same response as if it hit a wall which is just for it to change directions in whatever axis is appropriate for the wall it hit.
I have tried checking if the x and y position are the same but can't seem to make that work. I'd appreciate any input on this.
import java.util.Arrays;
int numOfParticles = 10;
float[] x = new float[numOfParticles]; //initial position of y only matters
float[] px = new float[numOfParticles];
float[] y = new float[numOfParticles];
float[] py = new float[numOfParticles];
int speed = 10;//inversly related to speed
float[] xIncrement = new float[numOfParticles]; //the ratio of increments determines the pattern
float[] yIncrement = new float[numOfParticles]; // it is the slope of the line
//float xIncrement = 10/speed; //the ratio of increments determines the pattern
//float yIncrement = 11/speed; // it is the slope of the line
color currentColor;
int alpha = 100;//range of 0-255
//radius of ball
int radius = 1;
//thickness of line behind ball
int thickness = 5;
int rateOfColor = 5; //this is inversely related to rate but also changes the range of colors
int maxColor = 255;
int minColor = 0;
void setup(){
size(500,500);
background(0);
colorMode(HSB);
strokeWeight(thickness);
frameRate(60);
//initialize particles
for(int i = 0;i<numOfParticles;i++){
xIncrement[i] = random(0,100)/speed; //the ratio of increments determines the pattern
yIncrement[i] = random(0,100)/speed; // it is the slope of the line
x[i] = random(0,width);
px[i] = x[i];
y[i] = random(0,height);
py[i] = y[i];
}
//you can either initialize all of them individually or do a random one
//x[0] = 0;
//px[0] = x[0];
//y[0] = 450;
//py[0] = y[0];
//x[1] = width;
//px[1] = x[1];
//y[1] = 450;
//py[1] = y[1];
}
void draw(){
background(0); //comment out for criss cross
for(int i = 0; i < numOfParticles; i++){
particle(i);
}
}
void particle(int particleNum){
currentColor = color(minColor + (x[particleNum]/rateOfColor)%maxColor,255,255,alpha);
stroke(currentColor);
fill(currentColor);
ellipse(x[particleNum],y[particleNum],radius,radius);
line(px[particleNum],py[particleNum],x[particleNum],y[particleNum]);
px[particleNum] = x[particleNum];
py[particleNum] = y[particleNum];
y[particleNum]+= yIncrement[particleNum];
x[particleNum]+= xIncrement[particleNum];
if(x[particleNum] > width + 1 || x[particleNum] < 0){
x[particleNum] -= 2*xIncrement[particleNum];
xIncrement[particleNum]*=-1;
}
if( y[particleNum] > height + 1 || y[particleNum] < 0){
y[particleNum] -= 2*yIncrement[particleNum];
yIncrement[particleNum]*=-1;
}
//if(Arrays.binarySearch(x,x[particleNum]) >= 0 && Arrays.binarySearch(y,y[particleNum]) >= 0){
// xIncrement[particleNum]*=-1;
// yIncrement[particleNum]*=-1;
// print("*\n");
// stop();
//}
print("x[0] = " + x[0] + "\n");
print("x[1] = " + x[1] + "\n");
print("y[0] = " + y[0] + "\n");
print("y[1] = " + y[1] + "\n");
}
Stack Overflow isn't really designed for general "how do I do this" type questions. It's for specific "I tried X, expected Y, but got Z instead" type questions. But I'll try to help in a general sense:
You need to break your problem down into smaller pieces and then take those pieces on one at a time. Don't worry about the whole particle system. Make it work for a single particle. Do some research on collision detection.
Then if you get stuck, you can post a more specific question along with a MCVE. Good luck.

My method scale isn't working, what may be the issue?

I have been trying to scale a Shape in java, but I'm having some problems. When i try it the Shape simple dissapears... This method receives 2 points, toScale is the point that i want the shape to extend to, and p1 is the point that I clicked in the rectangle that is around the shape to select (there's a rectangle(boundingBox) surrounding the shape wheter is a polygone or a rectangle or just polylines)
Here's the scale method code:
public void scale(Point toScale, Point p1) {
Graphics g = parent.getGraphics();
int distanceToClicked = 0;
int distanceToBoundingBox = 0;
int scaleFactor = 0;
Vector<Point> pointsAux = new Vector<Point>();
Iterator<Point> it = points.iterator();
while (it.hasNext()){
Point p = it.next();
distanceToClicked = (int) Math.sqrt(Math.pow(getCentroid().getX()-p1.getX(), 2)+Math.pow(getCentroid().getY()-p1.getY(),2));
distanceToBoundingBox = (int) Math.sqrt(Math.pow(getCentroid().getX()-toScale.getX(),2)+Math.pow(getCentroid().getY()-toScale.getY(),2));
scaleFactor = distanceToClicked/distanceToBoundingBox;
p = new Point((int)p.getX()*scaleFactor,(int) p.getY()*scaleFactor);
pointsAux.add(p);
}
points.clear();
points.addAll(pointsAux);
}
public Point getCentroid(){
int sumx = 0;
int sumy = 0;
for(int i = 0; i<points.size();i++){
sumx+=points.get(i).getX();
sumy+=points.get(i).getY();
}
Point centroid = new Point(sumx/points.size(), sumy/points.size());
return centroid;
}
Any help would be appreciated
Thanks in advance, and eventually I'm sorry for the misunderstanding code
Something like that would do the trick:
public Collection<Point> scaleShape(float scale, Collection<Point> shape) {
Point centroid = getCentroid();
Collection<Point> scaledShape = new ArrayList<>(shape.size());
for (Point point : shape) {
Point diff = new Point(point.x() - centroid.x(), point.y() - centroid.y());
Point scaledPoint = new Point(
(int) (centroid.x() + scale * diff.x()),
(int) (centroid.y() + scale * diff.y()));
scaledShape.add(scaledPoint);
}
return scaledShape;
}
Basically, every points make a linear function with the centroid. Centroid's relative x = 0, while the current computed point is at relative x = 1. You want to find the point if it were at relative x = scale.

Hexagonal Grid (Flat Top) Distance Calculation

I have been working on creating a hexagonal (flat top) grid for a simulation I am working on. I have attempted to work out the distance between the hexagons, from a specified target hexagon.
The solution I have works for most of the time, apart from every odd column from the target hexagon north of the target is shifted up by 1. I know that sounds confusing but I have attached an image to explain what I mean:
As you guys can see, the bottom half of the grid below the target hexagon and every other column above the target Hexagon is correct. I cannot understand why :S
Here is an explanation of the Axial & Cube Co-ords.
http://www.redblobgames.com/grids/hexagons/#coordinates
Here is the code responsible for converting the Axial Co-ords to Cube Co-ords.
public void setQR(int theQ, int theR){
this.q = theQ;
this.r = theR;
this.x = this.q;
this.z = this.r - (this.q - (this.q&1)) /2;
this.y = -(this.x + this.z);
}
And heres the code for working out distance.
FYI, the Hexagons are created from a CentrePoint (CPx, CPy).
private double distance = 0;
public double workOutDistance(Hexagon hexagon, HexagonFood target){
double targetX = target.getCPX();
double targetY = target.getCPY();
double hexagonX = hexagon.getCPX();
double hexagonY = hexagon.getCPY();
double deltaX = (targetX-hexagonX)*-1;
double deltaY = (targetY-hexagonY)*-1;
double deltaXRadius = (deltaX/(SimField.hexSize)/1.5);
double deltaYApothem = (deltaY/(SimField.hexSize/1.155)/2);
hexagon.setQR((int)deltaXRadius, (int)deltaYApothem);
ArrayList<Integer> coords = new ArrayList<>();
coords.add(
Math.abs(hexagon.getX() - target.getX())
);
coords.add(
Math.abs(hexagon.getZ() - target.getZ())
);
coords.add(
Math.abs(hexagon.getY() - target.getY())
);
System.out.println(coords);
distance = Collections.max(coords);
return distance;
}
Can anyone please tell me why this is happening ? Would be greatly appreciated.
EDIT:
After changing Int to Double as suggested by Tim, I get this.
http://i.stack.imgur.com/javZb.png
**
SOLUTION
**
after experimenting with the answers given, This small tweak solves the problem.
changing this..
public void setQR(int theQ, int theR){
this.q = theQ;
this.r = theR;
this.x = this.q;
this.z = this.r - (this.q - (this.q&1)) /2;
this.y = -(this.x + this.z);
}
to this..
public void setQR(int theQ, int theR){
this.q = theQ;
this.r = theR;
this.x = this.q;
if (this.r>0){
this.z = this.r - (this.q - (this.q&1))/2;
}
else {
this.z = this.r - (this.q + (this.q&1))/2;
}
this.y = -(this.x + this.z);
}
You're casting a double to an int when calling setQR(); are you sure that's doing what you expect? Doubles use floating point math, so the number you'd expect to be 2.0 might actually be 1.999999989, which would then be rounded down to 1 when cast to an int.
I'm also skeptical of the line that reads this.z = this.r - (this.q - (this.q&1)) /2;. You're adding 1 when the number is odd, which seems to be the failure case you're experiencing; I'd make sure that line is doing what you're expecting, too.
If you're not stepping through this with a debugger and examining the values, you're doing it wrong.
You could also take an entirely different approach to this problem. You know the X/Y (cartesian) coordinates of your two hexagons, which means you can get each hexagon's cubic coordinates relative to the origin of your hexagonal space. The distance between the two hexagons is simply the sum of the absolute values of the differences between the two hexagons' X, Y and Z cubic coordinates. (That is, dist = |h2.X - h1.X| + |h2.Y - h1.Y| + |h2.Z - h1.Z|) So rather than trying to compute the vector between the two centerpoints and then convert that into cubic coordinates, you could just compute the distance directly in cubic coordinates (just like you would if these were squares in cartesian coordinates)...
Even if you take this approach, though, I'd strongly recommend that you debug what's going on with your original approach. Even if you end up throwing away the code, the exercise of debugging will probably teach you valuable lessons that you'll be able to apply in the future.
Note to readers: "cubic" coordinates aren't 3-dimensional cartesian coordinates, they're a hexagon-specific coordinate system for which a link was provided by the OP.
The fact that the computation (that is, the conversion from offset- to cube coordinates, and the computation of the distance in cube coordinates) seems to be correct suggests that Tim was right with his assumption about the floating point errors.
You should try to change the line
hexagon.setQR((int)deltaXRadius, (int)deltaYApothem);
from your original code to something like
hexagon.setQR((int)Math.round(deltaXRadius), (int)Math.round(deltaYApothem));
Which could solve the issue in this case.
If not ... or... in any case, here's a small example, basically doing the same as you did, but as a MVCE...
import java.awt.Point;
public class HexagonsTest
{
public static void main(String[] args)
{
// Above and below
test(8,6, 8,5, 1);
test(8,6, 8,7, 1);
// Left
test(8,6, 7,5, 1);
test(8,6, 7,6, 1);
// Right
test(8,6, 9,5, 1);
test(8,6, 9,6, 1);
// The first one that was wrong:
test(8,6, 7,4, 2);
}
private static void test(int x0, int y0, int x1, int y1, int expected)
{
int distance = computeStepsDistance(x0, y0, x1, y1);
System.out.println(
"Distance of (" + x0 + "," + y0 + ") to " +
"(" + x1 + "," + y1 + ") is " + distance +
", expected " + expected);
}
private static int computeStepsDistance(int x0, int y0, int x1, int y1)
{
Point cp0 = convertOffsetToCubeCoordinates(x0, y0, null);
Point cp1 = convertOffsetToCubeCoordinates(x1, y1, null);
int cx0 = cp0.x;
int cy0 = cp0.y;
int cz0 = -cx0-cy0;
int cx1 = cp1.x;
int cy1 = cp1.y;
int cz1 = -cx1-cy1;
int dx = Math.abs(cx0 - cx1);
int dy = Math.abs(cy0 - cy1);
int dz = Math.abs(cz0 - cz1);
return Math.max(dx, Math.max(dy, dz));
}
private static Point convertOffsetToCubeCoordinates(
int ox, int oy, Point p)
{
int cx = ox;
int cz = oy - (ox - (ox&1)) / 2;
int cy = -cx-cz;
if (p == null)
{
p = new Point();
}
p.x = cx;
p.y = cy;
return p;
}
}

Can't Understand IndexOutOfBoundsException

I don't know if this is a simple problem or not, but I just can't see what the problem is. I've gotten three reports now from my app in Google Play of an IndexOutOfBoundsException at points.get(++i).
public GameThread(SurfaceHolder sHolder, Context context, Handler handler)
{
points = new ArrayList<Float>();
running = true;
mSurfaceHolder = sHolder;
}
protected void doDraw(Canvas canvas)
{
Paint p = new Paint();
p.setStyle(Paint.Style.FILL);
p.setColor(Color.WHITE);
for (int i = 0; i < points.size(); i++)
{
float x = points.get(i);
float y = points.get(++i);
canvas.drawPoint(x, y, p);
}
}
public boolean onTouchEvent(MotionEvent event)
{
float x = event.getX();
float y = event.getY();
points.add(x);
points.add(y);
return true;
}
The index it fails at is trying to access the location equal to its size (Actually one error says
java.lang.IndexOutOfBoundsException: Invalid index 2205, size is 2206 which makes NO sense at all to me), and its size varies.
The only way I can see this happening is if for some reason only one object is added to points, and I don't know why that would happen. onTouchEvent isn't running in its own thread, is it?
The problem is at this line:
float y = points.get(++i);
When i = points.size()-1, you preincrement, and then you invoke points.get(++i);. At this point, i = points.size() => Out of bounds. Just remove the ++ to fix it.
EDIT
Alternatively, you can try this approach:
List<Point> points = ...
protected void doDraw(Canvas canvas) {
Paint p = new Paint();
p.setStyle(Paint.Style.FILL);
p.setColor(Color.WHITE);
for (Point p : points) {
canvas.drawPoint(p.x, p.y, p);
}
}
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
points.add(new Point(x, y));
return true;
}
I would make the for-loop safe from problems like this by letting the for loop construct handle all of the i variable logic, don't try to do it yourself.
for (int i = 0; i+1 < points.size(); i+=2){
float x = points.get(i);
float y = points.get(i+1);
canvas.drawPoint(x, y, p);
}
Your problem is in your for-loop. While the first access would work, the second access is not guaranteed to be correct. If you only have one object, then the loop can't work because you are trying to access the next element in the array, which doesn't exist.
Try
for (int i = 0; i < points.size()-1; i++)
suppose your array length is 10
float y = points.get(++i);
you can replace this statement by
^^^
float y = points.get(i+1);
You are increasing value of Y here as well as here
for (int i = 0; i < points.size(); i++)
^^^
In for loop it checks i<points.size() means it 9 or less than 9
when you reach to 9
and in for loop you are accessing points.get(++i);
it will access points.get(10) <-------- here you gets exception
and your arry is 0-9 then is no element at 10
Use your Point object correctly, like:
Point point = new Point();
point.x = value;
point.y = value;
to print, or use.. its just point.x and point.y still. (in case of android.graphics.Point;)
If you want to store several points, you can use for example ArrayList
ArrayList<Point> pointArray = new ArrayList<Point>();
pointArray.add(new Point(event.getX(), event.getY()));
To loop it throught:
for(Point p : pointArray){
// do something with p.x and p.y
}

How to check if VERTEX ARRAY is clockwise?

Solved, used this code:
if ( !isClockwise(TempVectArray) ) { Collections.reverse(TempVectArray); }
...
private boolean isClockwise(ArrayList<Vec2> arl){
Iterator<Vec2> it = arl.iterator();
Vec2 pt1 = (Vec2)it.next();
Vec2 firstPt = pt1;
Vec2 lastPt = null;
double area = 0.0;
while(it.hasNext()){
Vec2 pt2 = (Vec2) it.next();
area += (((pt2.x - pt1.x) * (pt2.y + pt1.y)) / 2);
pt1 = pt2;
lastPt = pt1;
}
area += (((firstPt.x - lastPt.x) * (firstPt.y + lastPt.y)) / 2);
return area < 0;
}
Suppose I get a vertex array from the user tapping on the screen, but need it to be clockwise.
Maybe you know of some standard methods to check if it is clockwise and if it's not, then make it clockwise?
Thanks!
One way to do it is to first calculate the average point, and then sort everything around it by angle. Should be something like this:
public static void sortPointsClockwise(ArrayList<PointF> points) {
float averageX = 0;
float averageY = 0;
for (PointF point : points) {
averageX += point.x;
averageY += point.y;
}
final float finalAverageX = averageX / points.size();
final float finalAverageY = averageY / points.size();
Comparator<PointF> comparator = new Comparator<PointF>() {
public int compare(PointF lhs, PointF rhs) {
double lhsAngle = Math.atan2(lhs.y - finalAverageY, lhs.x - finalAverageX);
double rhsAngle = Math.atan2(rhs.y - finalAverageY, rhs.x - finalAverageX);
// Depending on the coordinate system, you might need to reverse these two conditions
if (lhsAngle < rhsAngle) return -1;
if (lhsAngle > rhsAngle) return 1;
return 0;
}
};
Collections.sort(points, comparator);
}
public static void sortPointsCounterClockwise(ArrayList<PointF> points) {
sortPointsClockwise(points);
Collections.reverse(points);
}
You have the sequence numbers and positions of the nodes. Get the movements which hold x and y changes in the move. All left to do is define a control structure such as:
if(movement_before is "up")
movement should-be "up" or "up-right"
if(movement_before is "up-left")
movement should-be "up" or "up-left" or "up-right"
etc..

Categories

Resources