glPolygonOffset with unexpected lines - java

I am rendering triangle strips with glpolygonMode(GL_FRONT_AND_BACK, GL_LINE).
Then I enable the line offset to this setting glPolygonOffset (-0.8f, -1.0f).
No matter what setting I use for the offset I end up getting random lines that flash
in and out when moving around. Here is a gif. of what it looks like. If anyone could help
give ideas as what they think is wrong here that would be great.
Here is my method where I render the lines if anyone needs to look at it.
public void lines() {
GL11.glColor3f(0.0f, 0.0f, 0.0f);
GL11.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_LINE);
Triangle currentTri = new Triangle();
List<Triangle> triList = new ArrayList<Triangle>();
boolean xSwitch = false;
for (int z=0; z<=100; z+=2) {
GL11.glEnable(GL11.GL_POLYGON_OFFSET_LINE);
GL11.glPolygonOffset (-0.8f, -1.0f);
GL11.glBegin(GL11.GL_TRIANGLE_STRIP);
int triPointIndex = 0;
boolean zSwitch = true;
xSwitch = !xSwitch;
float zVal;
float xVal;
for (int x=0; x<100; x+=1) {
xVal = x;
float randY;
zSwitch = !zSwitch;
// this is what determines the xSwitch and zSwitch outcomes.
// changes the zVal and randY to match what must alternate.
if (xSwitch) {
if (zSwitch) {
zVal = z;
randY = randYList[z][x];
} else {
zVal = z + 2.0f;
randY = randYList[z+2][x];
}
} else {
if (zSwitch) {
zVal = z + 2.0f;
randY = randYList[z+2][x];
} else {
zVal = z;
randY = randYList[z][x];
}
}
// set up the currentVert within the currentTri so that we can use it for computing normals.
Vert currentVert = currentTri.triVerts[triPointIndex];
currentVert.x = xVal;
currentVert.y = randY;
currentVert.z = zVal;
triPointIndex++;
if (triPointIndex == 3) {
triList.add(currentTri);
Triangle nextTri = new Triangle();
Vector3f normal = new Vector3f();
float Ux; float Uy; float Uz;
float Vx; float Vy; float Vz;
if (xSwitch) {
if (triList.indexOf(currentTri) % 2 == 0) {
Vx = currentTri.triVerts[1].x - currentTri.triVerts[0].x;
Vy = currentTri.triVerts[1].y - currentTri.triVerts[0].y;
Vz = currentTri.triVerts[1].z - currentTri.triVerts[0].z;
Ux = currentTri.triVerts[2].x - currentTri.triVerts[0].x;
Uy = currentTri.triVerts[2].y - currentTri.triVerts[0].y;
Uz = currentTri.triVerts[2].z - currentTri.triVerts[0].z;
} else {
Ux = currentTri.triVerts[1].x - currentTri.triVerts[0].x;
Uy = currentTri.triVerts[1].y - currentTri.triVerts[0].y;
Uz = currentTri.triVerts[1].z - currentTri.triVerts[0].z;
Vx = currentTri.triVerts[2].x - currentTri.triVerts[0].x;
Vy = currentTri.triVerts[2].y - currentTri.triVerts[0].y;
Vz = currentTri.triVerts[2].z - currentTri.triVerts[0].z;
}
} else {
if (triList.indexOf(currentTri) % 2 == 0) {
Ux = currentTri.triVerts[1].x - currentTri.triVerts[0].x;
Uy = currentTri.triVerts[1].y - currentTri.triVerts[0].y;
Uz = currentTri.triVerts[1].z - currentTri.triVerts[0].z;
Vx = currentTri.triVerts[2].x - currentTri.triVerts[0].x;
Vy = currentTri.triVerts[2].y - currentTri.triVerts[0].y;
Vz = currentTri.triVerts[2].z - currentTri.triVerts[0].z;
} else {
Vx = currentTri.triVerts[1].x - currentTri.triVerts[0].x;
Vy = currentTri.triVerts[1].y - currentTri.triVerts[0].y;
Vz = currentTri.triVerts[1].z - currentTri.triVerts[0].z;
Ux = currentTri.triVerts[2].x - currentTri.triVerts[0].x;
Uy = currentTri.triVerts[2].y - currentTri.triVerts[0].y;
Uz = currentTri.triVerts[2].z - currentTri.triVerts[0].z;
}
}
normal.x = (Uy * Vz) - (Uz * Vy);
normal.y = (Uz * Vx) - (Ux * Vz);
normal.z = (Ux * Vy) - (Uy * Vx);
GL11.glNormal3f(normal.x, normal.y, normal.z);
nextTri.triVerts[0] = currentTri.triVerts[1];
nextTri.triVerts[1] = currentTri.triVerts[2];
currentTri = nextTri;
triPointIndex = 2;
} // close triPointIndex == 3
GL11.glVertex3f(xVal, randY, zVal);
} // close x loop
GL11.glEnd();
} // close z loop
GL11.glDisable(GL11.GL_POLYGON_OFFSET_LINE);
}

Related

circle collision causes circle to go supersonic

can anyone tell me why the circles i draw are getting stuck on each other or going super fast and flying off the window. all i want is for the circles to bounce off each other, but instead they get stuck 1/3 of the time, accelerate drastically another 1/3 of the time and only bounce the other 1/3. sorry if its messy, i've been trying a lot of different ideas and it kind of got out of hand. code uses maths that i got from gist.github/christopher4lis/f9ccb589ee8ecf751481f05a8e59b1dc. its horribly done but its the best i can do for now.
Please let me know if there is any other code that you need to help fix this.
public void bounce() {
collision = false;
for (int i = 0; i < size; i++) {
for (int a = 0; a < size; a++) {
float xVelDiff = dots[i][2] - dots[a][2];
float yVelDiff = dots[i][3] - dots[a][3];
float xDist = dots[i][0] - dots[a][0];
float yDist = dots[i][1] - dots[a][1];
if (xVelDiff * xDist + yVelDiff * yDist <= 0) {
angle = (float) -Math.atan2(dots[a][0] - dots[i][0], dots[a][1] - dots[i][1]);
float m1 = dots[i][7];
BigDecimal bd = new BigDecimal(m1).setScale(2, RoundingMode.HALF_UP);
m1 = bd.floatValue();
float m2 = dots[a][7];
float[] u1 = rotate(dots[i][2], dots[i][3], (float) angle);
float[] u2 = rotate(dots[a][2], dots[a][3], (float) angle);
float[] v1 = new float[2];
v1[0] = u1[0] * (m1 - m2) / (m1 + m2) + u2[0] * 2 * m2 / (m1 + m2);
v1[1] = u1[1];
float[] v2 = new float[2];
v2[0] = u2[0] * (m1 - m2) / (m1 + m2) + u1[0] * 2 * m2 / (m1 + m2);
v2[1] = u2[1];
float[] vFinal1 = rotate(v1[0], v1[1], (float) -angle);
float[] vFinal2 = rotate(v2[0], v2[1], (float) -angle);
if (a != i && !(dots[a][0] == 0 && dots[a][1] == 0)) {
boolean thisCollision = (dots[a][0] - dots[i][0]) * (dots[a][0] - dots[i][0]) + (dots[a][1] - dots[i][1]) * (dots[a][1] - dots[i][1]) <= (dots[a][4] + dots[i][4]) * (dots[a][4] + dots[i][4]);
// System.out.println("collision: "+collision+" i="+i+" a="+a);
if (thisCollision) {
System.out.println(vFinal2[0] + " " + vFinal2[1]);
collision = true;
dots[i][2] = vFinal1[0];
dots[i][3] = vFinal1[1];
dots[a][2] = vFinal2[0];
dots[a][3] = vFinal2[1];
return;
}
}
}
}
}
}
public float[] rotate(float velocityX, float velocityY, float angle) {
float x1 = (float) (velocityX * Math.cos(angle) - velocityY * Math.sin(angle));
float y1 = (float) (velocityX * Math.cos(angle) - velocityY * Math.sin(angle));
float vel[] = new float[2];
vel[0] = x1;
vel[1] = y1;
return vel;
}

circle collision practice, advice?

can anyone tell me what i'm doing wrong? i'm trying to get the circles to bounce off each other but they don't seem to be working.i keep making changes to fix the issue but that only makes more issues, whilst the main issue isn't resolved. have i used the wrong math's algorithm to check for collisions? or is it right and i have just made an error i cant seem to find? any help would be appreciated.
public float[][] CreateDots() {
if (first == true) {
for (int i = 0; i < dotNumber; i++) {
do{
dotX = r.nextInt(300);
dotY = r.nextInt(300);
dotWidth = r.nextFloat() * 50;
dotRadius = dotWidth / 2;
dotMass = r.nextFloat() / 10;
dotCentreX = dotX + dotRadius;
dotCentreY = dotY + dotRadius;
dotVelocityX = r.nextFloat();
dotVelocityY = r.nextFloat();
dots[i][0] = dotX;
dots[i][1] = dotY;
dots[i][2] = dotVelocityX;
dots[i][3] = dotVelocityY;
dots[i][4] = dotRadius;
dots[i][5] = dotCentreX;
dots[i][6] = dotCentreY;
dots[i][7] = dotMass;
dots[i][8] = dotWidth;
}while(collision == true);
}
first = false;
} else {
for (int i = 0; i < dotNumber; i++) {
dots[i][0] = dots[i][0] + dots[i][2];
dots[i][1] = dots[i][1] + dots[i][3];
if (dots[i][0] + dots[i][8] >= wallX) {
dots[i][2] = -dots[i][2];
}
if (dots[i][1] + dots[i][8] >= wallY) {
dots[i][3] = -dots[i][3];
}
if (dots[i][0] < 0) {
dots[i][2] = -dots[i][2];
}
if (dots[i][1] < 0) {
dots[i][3] = -dots[i][3];
}
}
}
repaint();
return dots;
}
public void bounce() {
collisionDot = false;
for (int i = 0; i < dotNumber; i++) {
for (int a = i + 1; a < dotNumber; a++) {
// difference between the x and y velocity of two dots
float xVelDiff = dots[i][2] - dots[a][2];
float yVelDiff = dots[i][3] - dots[a][3];
//difference between the centre x and y of two dots
float xDist = dots[i][5] - dots[a][5];
float yDist = dots[i][6] - dots[a][6];
System.out.println(xVelDiff + " * " + xDist + " + " + yVelDiff + " * " + yDist + " = "+ (xVelDiff * xDist + yVelDiff * yDist));
//not quite sure yet
if (xVelDiff * xDist + yVelDiff * yDist <= 0) {
angleCollision = (float) -Math.atan2(dots[a][0] - dots[i][0], dots[a][1] - dots[i][1]);
float mass = (dots[i][7] + dots[a][7]);
float mass2 = (dots[i][7] - dots[a][7]);
// x and y velocity and angle of collision for the two dots
float[] u1 = rotate(dots[i][2], dots[i][3], (float) angleCollision);
float[] u2 = rotate(dots[a][2], dots[a][3], (float) angleCollision);
//Velocity of dot 1
float[] v1 = new float[2];
v1[0] = u1[0] * mass2 / mass + u2[0] * 2 * dots[a][7] / (mass);
v1[1] = u1[1];
// velocity of dot 2
float[] v2 = new float[2];
v2[0] = u2[0] * mass2 / mass + u1[0] * 2 * dots[a][7] / (mass);
v2[1] = u2[1];
// final velocity of two colliding dots is:
float[] vFinal1 = rotate(v1[0], v1[1], (float) -angleCollision);;
float[] vFinal2 = rotate(v2[0], v2[1], (float) -angleCollision);;
if (a != i && !(dots[a][0] == 0 && dots[a][1] == 0)) {
// if the x and y distance between the two dots centres is less than their radii combined then the dots have collided
boolean thisCollision = Math.pow(xDist, 2) + Math.pow(yDist, 2) <= Math.pow((dots[a][4] + dots[i][4]), 2);
//if the dots collided, create new final velocity's from the angle of collision and the x and y velocitys at collision
if (thisCollision) {
collisionDot = true;
dots[i][2] = vFinal1[0];
dots[i][3] = vFinal1[1];
dots[a][2] = vFinal2[0];
dots[a][3] = vFinal2[1];
return;
}
}
}
}
}
}
public float[] rotate(float velocityX, float velocityY, float angle) {
float x1 = (float) (velocityX * Math.cos(angle) - velocityY * Math.sin(angle));
float y1 = (float) (velocityX * Math.sin(angle) - velocityY * Math.cos(angle));
float vel[] = new float[2];
vel[0] = x1;
vel[1] = y1;
return vel;
}

Collision Detection in a Tile Based Platformer

I have a set of methods in my platformer in progress to detect and resolve collisions between entities and the tilemap, but they are doing a bad job of it.
The bottom method is the one being called, like this:
player.velocity = player.velocity.add(getFinalCollisionVector());
where player.velocity is a Vec2D.
private List<Rectangle2D> getCollidingTiles(){
List<Rectangle2D> collidingTiles = new ArrayList<Rectangle2D>();
for(int x = (int) (this.getX()/Tile.SIZE); x <= (int) (this.getX()/Tile.SIZE) + this.getRect2D().getWidth()/Tile.SIZE; x++){
for(int y = (int) (this.getX()/Tile.SIZE); y <= (int) (this.getX()/Tile.SIZE) + this.getRect2D().getHeight()/Tile.SIZE; y++){
if(map.getTileAt(x, y).getAttribute(Attribute.SOLID))
if(map.getCollisionBoxAt(x,y).isColliding(this.collisionBox))
collidingTiles.add(new Rectangle2D.Double(x, y, Tile.SIZE, Tile.SIZE));
}
}
return collidingTiles;
}
private List<Vec2D> getAllTileCollisionVectors(){
List<Rectangle2D> collidingTiles = getCollidingTiles();
List<Vec2D> collisionVectors = new ArrayList<Vec2D>();
for(Rectangle2D rec : collidingTiles){
collisionVectors.add(getCorrectionVector(rec));
}
return collisionVectors;
}
private Vec2D getCorrectionVector(Rectangle2D target)
{
Vec2D ret = new Vec2D();
double x1 = (this.getX() + this.getSize().x) - target.getX();
double x2 = this.getX() - (target.getX() + target.getWidth());
double y1 = (this.getY() + this.getSize().y) - target.getY();
double y2 = this.getY() - (target.getY() + target.getHeight());
// calculate displacement along X-axis
if (x1 < x2)
{
ret.x = x1;
}
else if (x1 > x2)
{
ret.x = x2;
}
// calculate displacement along Y-axis
if (y1 < y2)
{
ret.y = y1;
}
else if (y1 > y2)
{
ret.y = y2;
}
return ret;
}
protected Vec2D getFinalCollisionVector(){
List<Vec2D> collisionVectors = getAllTileCollisionVectors();
if(collisionVectors.size() < 1)
return new Vec2D(0,0);
Vec2D finalVector = new Vec2D();
for(Vec2D vec : collisionVectors){
finalVector = finalVector.add(vec);
}
return finalVector;
}
What am I doing wrong in my code? This is the behavior that the player shows, where he falls (due to gravity) to that point, and then he freezes.
OP here:
Since there are no other answers, I've posted my own.
I've abandonded the old implementation,started from the ground up, and it works now. This is the new implementation:
public Corners getCornersAreSolid(double x, double y) {
int leftTile = (int)(x / Tile.SIZE);
int rightTile = (int)((x + moveData.collisionBox.getWidth()) / Tile.SIZE);
int topTile = (int)(y / Tile.SIZE);
int bottomTile = (int)((y + moveData.collisionBox.getHeight()) / Tile.SIZE);
boolean topLeft = hasAttribute(map, Attribute.SOLID, topTile, leftTile);
boolean topRight = hasAttribute(map, Attribute.SOLID, topTile, rightTile);
boolean bottomLeft = hasAttribute(map, Attribute.SOLID, bottomTile, leftTile);
boolean bottomRight = hasAttribute(map, Attribute.SOLID, bottomTile, rightTile);
Corners solidCorners = new Corners();
solidCorners.topLeft = topLeft;
solidCorners.topRight = topRight;
solidCorners.bottomRight = bottomRight;
solidCorners.bottomLeft = bottomLeft;
return solidCorners;
}
private boolean hasAttribute(GameMap map, Attribute attribute, int tileY, int tileX) {
boolean result = false;
if (tileX >= 0 && tileX < map.getWidthInTiles() && tileY >= 0 && tileY < map.getHeightInTiles()) {
result = map.getTileAt(tileX, tileY).getAttribute(attribute);
}
return result;
}
public Vec2D getNextPosition() {
int currCol = (int) (getX() / Tile.SIZE);
int currRow = (int) (getY() / Tile.SIZE);
double destX = getX() + moveData.velocity.x;
double destY = getY() + moveData.velocity.y;
double tempX = getX();
double tempY = getY();
Corners solidCorners = getCornersAreSolid(getX(), destY);
boolean topLeft = solidCorners.topLeft;
boolean topRight = solidCorners.topRight;
boolean bottomLeft = solidCorners.bottomLeft;
boolean bottomRight = solidCorners.bottomRight;
this.framesSinceLastCollision += 1;
if(moveData.velocity.y < 0) {
if(topLeft || topRight) {
moveData.velocity.y = 0;
tempY = currRow * Tile.SIZE;
this.framesSinceLastCollision = 0;
}
else {
tempY += moveData.velocity.y;
}
}
else if(moveData.velocity.y > 0) {
if(bottomLeft || bottomRight) {
moveData.velocity.y = 0;
tempY = (currRow + 1) * Tile.SIZE - moveData.collisionBox.getHeight() % Tile.SIZE - 1 ;
this.framesSinceLastCollision = 0;
}
else {
tempY += moveData.velocity.y;
}
}
solidCorners = getCornersAreSolid(destX, getY());
topLeft = solidCorners.topLeft;
topRight = solidCorners.topRight;
bottomLeft = solidCorners.bottomLeft;
bottomRight = solidCorners.bottomRight;
if(moveData.velocity.x < 0) {
if(topLeft || bottomLeft) {
moveData.velocity.x = 0;
tempX = currCol * Tile.SIZE;
this.framesSinceLastCollision = 0;
}
else {
tempX += moveData.velocity.x;
}
}
if(moveData.velocity.x > 0) {
if(topRight || bottomRight) {
moveData.velocity.x = 0;
tempX = (currCol + 1) * Tile.SIZE - moveData.collisionBox.getWidth() % Tile.SIZE -1 ;
this.framesSinceLastCollision = 0;
}
else {
tempX += moveData.velocity.x;
}
}
return new Vec2D(tempX, tempY);
}
private static class Corners{
public boolean topLeft, topRight;
public boolean bottomLeft, bottomRight;
public Corners(){
topLeft = false;
topRight = false;
bottomLeft = false;
bottomRight = false;
}
}

java graphics gouraud shading

I want to fill triangles with gouraud shading
I calculated normals for each vertex and used the following code but it dosn't work correctly
I interpolated colors against y using these formulas
Ir = Ir2 - (Ir2 - Ir1)* (v2.y -y)/dy;
Ig = Ig2 - (Ig2 - Ig1)* (v2.y -y)/dy;
Ib = Ib2 - (Ib2 - Ib1)* (v2.y -y)/dy;
and against x direction using
rr = r2- (r2-r1)*(Xs2-j)/dxs;
in method drawCurrentTriangle(Graphics2D g) how can i calculate color from interpolated vertex normal.(there is no lights in the scene (only triangle color))
public boolean convert(Triangle triangle) {
ensureCapacity();
clearCurrentScan();
triangle.getVlist()[0].r = triangle.normals[0].x;
triangle.getVlist()[0].g = triangle.normals[0].y;
triangle.getVlist()[0].b = triangle.normals[0].z;
triangle.getVlist()[1].r = triangle.normals[1].x;
triangle.getVlist()[1].g = triangle.normals[1].y;
triangle.getVlist()[1].b = triangle.normals[1].z;
triangle.getVlist()[2].r = triangle.normals[2].x;
triangle.getVlist()[2].g = triangle.normals[2].y;
triangle.getVlist()[2].b = triangle.normals[2].z;
for (int i = 0; i < 3; i++) {
Vector3d v1 = triangle.getVlist()[i];
Vector3d v2;
if (i == 2) {
v2 = triangle.getVlist()[0];
} else {
v2 = triangle.getVlist()[i + 1];
}
// ensure v1.y < v2.y
if (v1.y > v2.y) {
Vector3d temp = v1;
v1 = v2;
v2 = temp;
}
double dy = v2.y - v1.y;
Ir1 = v1.r;
Ig1 = v1.g;
Ib1 = v1.b;
Ir2 = v2.r;
Ig2 = v2.g;
Ib2 = v2.b;
// ignore horizontal lines
if (dy == 0) {
continue;
}
int startY = Math.max(FastMath.ceil(v1.y), minY);
int endY = Math.min(FastMath.ceil(v2.y) - 1, maxY);
top = Math.min(top, startY);
bottom = Math.max(bottom, endY);
double dx = v2.x - v1.x;
double Ir;
double Ig;
double Ib;
double Ic;
double Ia;
double Yc;
// special case: vertical line
if (dx == 0) {
int x = FastMath.ceil(v1.x);
// ensure x within view bounds
x = Math.min(maxX + 1, Math.max(x, minX));
for (int y = startY; y <= endY; y++) {
Ir = Ir2 - (Ir2 - Ir1)* (v2.y -y)/dy;
Ig = Ig2 - (Ig2 - Ig1)* (v2.y -y)/dy;
Ib = Ib2 - (Ib2 - Ib1)* (v2.y -y)/dy;
scans[y].setBoundary(x, Ir, Ig, Ib);
}
} else {
// scan-convert this edge (line equation)
double gradient = dx / dy;
// (slower version)
for (int y = startY; y <= endY; y++) {
int x = FastMath.ceil(v1.x + (y - v1.y) * gradient);
// ensure x within view bounds
x = Math.min(maxX + 1, Math.max(x, minX));
Ir = Ir2 - (Ir2 - Ir1)* (v2.y -y)/dy;
Ig = Ig2 - (Ig2 - Ig1)* (v2.y -y)/dy;
Ib = Ib2 - (Ib2 - Ib1)* (v2.y -y)/dy;
scans[y].setBoundary(x, Ir, Ig, Ib);
}
// check if visible (any valid scans)
for (int i = top; i <= bottom; i++) {
if (scans[i].isValid()) {
return true;
}
}
return false;
}
}
}
protected void drawCurrentTriangle(Graphics2D g) {
int y = scanConverter.getTopBoundary();
double Xs1 = 0;
double Xs2 = 0;
double dxs = 0;
double r1 = 0;
double g1 = 0;
double b1 = 0;
double r2 = 0;
double g2 = 0;
double b2 = 0;
double rr = 0;
double gg = 0;
double bb = 0;
while (y <= scanConverter.getBottomBoundary()) {
GouraudTriangleScanConverter.Scan scan = scanConverter.getScan(y);
if (scan.isValid()) {
r1 = scan.rL;
g1 = scan.gL;
b1 = scan.bL;
r2 = scan.rR;
g2 = scan.gR;
b2 = scan.bR;
Xs1 = scan.left;
Xs2 = scan.right;
dxs = Xs2-Xs1;
for (int j = scan.left; j < scan.right; j++) {
rr = r2- (r2-r1)*(Xs2-j)/dxs;
gg = g2- (g2-g1)*(Xs2-j)/dxs;
bb = b2- (b2-b1)*(Xs2-j)/dxs;
if(rr > 255) rr = 255;
if(gg > 255) gg = 255;
if(bb > 255) bb = 255;
g.setColor(new Color((int)rr, (int)gg, (int)bb));
g.drawLine(j,y,j,y);
}
//g.drawLine(scan.right,y,scan.right,y);
}
y++;
}
}
public static class Scan {
public int left;
public int right;
public double rL = -1;
public double gL = -1;
public double bL = -1;
public double rR = -1;
public double gR = -1;
public double bR = -1;
/**
* Sets the left and right boundary for this scan if
* the x value is outside the current boundary.
*/
public void setBoundary(int x, double r, double g, double b) {
if (x > max)
max = x;
if (x < left) {
left = x;
rL = r;
gL = g;
bL = b;
}
if (x - 1 > right) {
right = x - 1;
rR = r;
gR = g;
bR = b;
}
}
/**
* Determines if this scan is valid (if left <= right).
*/
public boolean isValid() {
return (left <= right);
}
}
how can i apply colors to mesh.when i in
fix colors(no lighting)

Point inside Oriented Bounding Box?

I have an OBB2D class based on SAT.
This is my point in OBB method:
public boolean pointInside(float x, float y)
{
float newy = (float) (Math.sin(angle) * (y - center.y) + Math.cos(angle) *
(x - center.x));
float newx = (float) (Math.cos(angle) * (x - center.x) - Math.sin(angle) *
(y - center.y));
return (newy > center.y - (getHeight() / 2)) &&
(newy < center.y + (getHeight() / 2))
&& (newx > center.x - (getWidth() / 2)) &&
(newx < center.x + (getWidth() / 2));
}
public boolean pointInside(Vector2D v)
{
return pointInside(v.x,v.y);
}
Here is the rest of the class; the parts that pertain:
public class OBB2D
{
private Vector2D projVec = new Vector2D();
private static Vector2D projAVec = new Vector2D();
private static Vector2D projBVec = new Vector2D();
private static Vector2D tempNormal = new Vector2D();
private Vector2D deltaVec = new Vector2D();
private ArrayList<Vector2D> collisionPoints = new ArrayList<Vector2D>();
// Corners of the box, where 0 is the lower left.
private Vector2D corner[] = new Vector2D[4];
private Vector2D center = new Vector2D();
private Vector2D extents = new Vector2D();
private RectF boundingRect = new RectF();
private float angle;
//Two edges of the box extended away from corner[0].
private Vector2D axis[] = new Vector2D[2];
private double origin[] = new double[2];
public OBB2D(float centerx, float centery, float w, float h, float angle)
{
for(int i = 0; i < corner.length; ++i)
{
corner[i] = new Vector2D();
}
for(int i = 0; i < axis.length; ++i)
{
axis[i] = new Vector2D();
}
set(centerx,centery,w,h,angle);
}
public OBB2D(float left, float top, float width, float height)
{
for(int i = 0; i < corner.length; ++i)
{
corner[i] = new Vector2D();
}
for(int i = 0; i < axis.length; ++i)
{
axis[i] = new Vector2D();
}
set(left + (width / 2), top + (height / 2),width,height,0.0f);
}
public void set(float centerx,float centery,float w, float h,float angle)
{
float vxx = (float)Math.cos(angle);
float vxy = (float)Math.sin(angle);
float vyx = (float)-Math.sin(angle);
float vyy = (float)Math.cos(angle);
vxx *= w / 2;
vxy *= (w / 2);
vyx *= (h / 2);
vyy *= (h / 2);
corner[0].x = centerx - vxx - vyx;
corner[0].y = centery - vxy - vyy;
corner[1].x = centerx + vxx - vyx;
corner[1].y = centery + vxy - vyy;
corner[2].x = centerx + vxx + vyx;
corner[2].y = centery + vxy + vyy;
corner[3].x = centerx - vxx + vyx;
corner[3].y = centery - vxy + vyy;
this.center.x = centerx;
this.center.y = centery;
this.angle = angle;
computeAxes();
extents.x = w / 2;
extents.y = h / 2;
computeBoundingRect();
}
//Updates the axes after the corners move. Assumes the
//corners actually form a rectangle.
private void computeAxes()
{
axis[0].x = corner[1].x - corner[0].x;
axis[0].y = corner[1].y - corner[0].y;
axis[1].x = corner[3].x - corner[0].x;
axis[1].y = corner[3].y - corner[0].y;
// Make the length of each axis 1/edge length so we know any
// dot product must be less than 1 to fall within the edge.
for (int a = 0; a < axis.length; ++a)
{
float l = axis[a].length();
float ll = l * l;
axis[a].x = axis[a].x / ll;
axis[a].y = axis[a].y / ll;
origin[a] = corner[0].dot(axis[a]);
}
}
public void computeBoundingRect()
{
boundingRect.left = JMath.min(JMath.min(corner[0].x, corner[3].x), JMath.min(corner[1].x, corner[2].x));
boundingRect.top = JMath.min(JMath.min(corner[0].y, corner[1].y),JMath.min(corner[2].y, corner[3].y));
boundingRect.right = JMath.max(JMath.max(corner[1].x, corner[2].x), JMath.max(corner[0].x, corner[3].x));
boundingRect.bottom = JMath.max(JMath.max(corner[2].y, corner[3].y),JMath.max(corner[0].y, corner[1].y));
}
public void set(RectF rect)
{
set(rect.centerX(),rect.centerY(),rect.width(),rect.height(),0.0f);
}
// Returns true if other overlaps one dimension of this.
private boolean overlaps1Way(OBB2D other)
{
for (int a = 0; a < axis.length; ++a) {
double t = other.corner[0].dot(axis[a]);
// Find the extent of box 2 on axis a
double tMin = t;
double tMax = t;
for (int c = 1; c < corner.length; ++c) {
t = other.corner[c].dot(axis[a]);
if (t < tMin) {
tMin = t;
} else if (t > tMax) {
tMax = t;
}
}
// We have to subtract off the origin
// See if [tMin, tMax] intersects [0, 1]
if ((tMin > 1 + origin[a]) || (tMax < origin[a])) {
// There was no intersection along this dimension;
// the boxes cannot possibly overlap.
return false;
}
}
// There was no dimension along which there is no intersection.
// Therefore the boxes overlap.
return true;
}
public void moveTo(float centerx, float centery)
{
float cx,cy;
cx = center.x;
cy = center.y;
deltaVec.x = centerx - cx;
deltaVec.y = centery - cy;
for (int c = 0; c < 4; ++c)
{
corner[c].x += deltaVec.x;
corner[c].y += deltaVec.y;
}
boundingRect.left += deltaVec.x;
boundingRect.top += deltaVec.y;
boundingRect.right += deltaVec.x;
boundingRect.bottom += deltaVec.y;
this.center.x = centerx;
this.center.y = centery;
computeAxes();
}
// Returns true if the intersection of the boxes is non-empty.
public boolean overlaps(OBB2D other)
{
if(right() < other.left())
{
return false;
}
if(bottom() < other.top())
{
return false;
}
if(left() > other.right())
{
return false;
}
if(top() > other.bottom())
{
return false;
}
if(other.getAngle() == 0.0f && getAngle() == 0.0f)
{
return true;
}
return overlaps1Way(other) && other.overlaps1Way(this);
}
public Vector2D getCenter()
{
return center;
}
public float getWidth()
{
return extents.x * 2;
}
public float getHeight()
{
return extents.y * 2;
}
public void setAngle(float angle)
{
set(center.x,center.y,getWidth(),getHeight(),angle);
}
public float getAngle()
{
return angle;
}
public void setSize(float w,float h)
{
set(center.x,center.y,w,h,angle);
}
public float left()
{
return boundingRect.left;
}
public float right()
{
return boundingRect.right;
}
public float bottom()
{
return boundingRect.bottom;
}
public float top()
{
return boundingRect.top;
}
public RectF getBoundingRect()
{
return boundingRect;
}
public boolean overlaps(float left, float top, float right, float bottom)
{
if(right() < left)
{
return false;
}
if(bottom() < top)
{
return false;
}
if(left() > right)
{
return false;
}
if(top() > bottom)
{
return false;
}
return true;
}
public static float distance(float ax, float ay,float bx, float by)
{
if (ax < bx)
return bx - ay;
else
return ax - by;
}
public Vector2D project(float ax, float ay)
{
projVec.x = Float.MAX_VALUE;
projVec.y = Float.MIN_VALUE;
for (int i = 0; i < corner.length; ++i)
{
float dot = Vector2D.dot(corner[i].x,corner[i].y,ax,ay);
projVec.x = JMath.min(dot, projVec.x);
projVec.y = JMath.max(dot, projVec.y);
}
return projVec;
}
public Vector2D getCorner(int c)
{
return corner[c];
}
public int getNumCorners()
{
return corner.length;
}
public boolean pointInside(float x, float y)
{
float newy = (float) (Math.sin(angle) * (y - center.y) + Math.cos(angle) *
(x - center.x));
float newx = (float) (Math.cos(angle) * (x - center.x) - Math.sin(angle) *
(y - center.y));
return (newy > center.y - (getHeight() / 2)) &&
(newy < center.y + (getHeight() / 2))
&& (newx > center.x - (getWidth() / 2)) &&
(newx < center.x + (getWidth() / 2));
}
public boolean pointInside(Vector2D v)
{
return pointInside(v.x,v.y);
}
public ArrayList<Vector2D> getCollsionPoints(OBB2D b)
{
collisionPoints.clear();
for(int i = 0; i < corner.length; ++i)
{
if(b.pointInside(corner[i]))
{
collisionPoints.add(corner[i]);
}
}
for(int i = 0; i < b.corner.length; ++i)
{
if(pointInside(b.corner[i]))
{
collisionPoints.add(b.corner[i]);
}
}
return collisionPoints;
}
};
What could be wrong? When I getCollisionPoints for 2 OBBs I know are penetrating, it returns no points.
Thanks
I also tried:
public boolean pointInside(float x, float y)
{
float xx = (x - center.x);
float yy = (y - center.y);
float newx = (float) (xx * Math.cos(angle) - yy * Math.sin(angle));
float newy = (float) (xx * Math.sin(angle) + yy * Math.cos(angle));
return (newy > center.y - (getHeight() / 2)) &&
(newy < center.y + (getHeight() / 2))
&& (newx > center.x - (getWidth() / 2)) &&
(newx < center.x + (getWidth() / 2));
}
With no luck.
I didn't read all of your class, but I'm assuming angle is the angle by which you would need to rotate your rectangle clockwise in order to make it axis-aligned.
I believe that both sin(angle) * (y-center.y) and cos(angle) * (x-center.x) are equal to the distance between your center point and the point you're testing. So newy will always equal twice that distance, and newx will always equal 0.
This is how I prefer to rotate a point about another point: get the angle and distance between the two points, then apply the rotation to the angle, then calculate the new position from the angle and distance. In pseudocode:
//takes a point and rotates it `theta` angles
//counterclockwise around the given center point
function rotateAboutPoint(x,y, centerX, centerY, theta){
radius = sqrt((centerX-x)**2 + (centerY-y)**2) //`**` is the exponentiation operator
currentAngle = atan2(y-centerY, x-centerX) //prefer `atan2` over ordinary `atan` if you can get it
newAngle = currentAngle + theta
newX = centerX + radius*cos(newAngle)
newY = centerY + radius*sin(newAngle)
return (newX, newY)
}
function pointInside(x,y){
//point must be rotated clockwise, so we provide a negative angle
newX, newY = rotateAboutPoint(x,y,center.x, center.y, -angle)
return (
newY > center.y - (getHeight() / 2) &&
newY < center.y + (getHeight() / 2) &&
newX > center.x - (getHeight() / 2) &&
newX < center.x + (getHeight() / 2) &&
)
}

Categories

Resources