UPDATE
Slick and JBox use radians that go in opposite directions, that's why I was having trouble.
I am making a game using JBox2D and Slick2D (per the title). So, because I couldn't find anything online about it, I wrote a bunch of code from scratch to convert between them. However, it seems as though the angles are different, even though both documentations say they use radians.
Here is my code:
//In the update function
angle = (float) (angle % 2*Math.PI);
mass = player.getMass();
position = player.getPosition();
if(input.isKeyDown(inputLeft)){
angle-=0.015f*turnBlocks.size()/mass; //turning, pt1
} else if(input.isKeyDown(inputRight)){
angle+=0.015f*turnBlocks.size()/mass;
}
player.setTransform(position, angle); //turning, pt2
if(input.isKeyDown(inputForward)){
float xv = (float)(0.25f * Math.sin(angle) *
thrustBlocks.size() / mass); //Converting angle to vector
float yv = (float)(0.25f * Math.cos(angle) *
thrustBlocks.size() / mass);
Vec2 curVel = player.getLinearVelocity();
xv = xv + curVel.x;
yv = yv + curVel.y;
player.setLinearVelocity(new Vec2(xv, yv));
}
and
//In the render function
g.setColor(Color.gray);
for(int mass = 0; mass < massBlocks.size(); mass++){
float boxx = (float)massBlocks.get(mass)[0];
float boxy = (float)massBlocks.get(mass)[1];
int[] slicklist = tr.toSlick(position.x+boxx, position.y+boxy);
boxx = (float)slicklist[0];
boxy = (float)slicklist[1];
float[] ps = {boxx-tr.xscale/2, boxy-tr.yscale/2,
boxx+tr.xscale/2, boxy-tr.yscale/2,
boxx+tr.xscale/2, boxy+tr.yscale/2,
boxx-tr.xscale/2, boxy+tr.yscale/2};
Polygon p = new Polygon(ps);
//turning, pt3
g.fill(p.transform(Transform.createRotateTransform(radAngle, slickx, slicky)));
}
When I run the above code (with the rest of it), I get the player block(s) moving in the direction it shows it is facing. However, the collision in Jbox2D is out of sync. Here is the pattern I have found:
1 unit = pi/4 in slick
Slick direction:
7___0___1
6___.___2
5___4___3
Jbox Direction:
5___0___3
2___.___6
7___4___1
Really, I have no idea what is going on. Can somebody help?
Okay. It turns out that even thought Slick's transform and JBox's angle are both radians, They go in opposite directions. So, I made the below code with the .getWorldPosition instead of transform.
float localJBoxX = thrustBlocks.get(count)[0];
float localJBoxY = thrustBlocks.get(count)[1];
float[] localEndCoords = {localJBoxX+0.5f, localJBoxY+0.5f,
localJBoxX-0.5f, localJBoxY+0.5f,
localJBoxX-0.5f, localJBoxY-0.5f,
localJBoxX+0.5f, localJBoxY-0.5f};
float[] slickCoords = new float[localEndCoords.length];
for(byte point = 0; point<localEndCoords.length/2; point++){
Vec2 localPoint = new Vec2(localEndCoords[point*2], localEndCoords[point*2+1]);
slickCoords[point*2] = (float)tr.toSlick(player.getWorldPoint(localPoint).x, player.getWorldPoint(localPoint).y)[0];
slickCoords[point*2+1] = (float)tr.toSlick(player.getWorldPoint(localPoint).x, player.getWorldPoint(localPoint).y)[1];
}
Polygon box = new Polygon(slickCoords);
g.fill(box.transform(new Transform())); //as to return a shape
Related
I'm using Libgdx's port of box2d. I'm creating an edge shape, but it does not rotate upon collision with other polygons. Why is this?
Here's my code for setting up the edge shape.
float x = 3;
float y = 10;
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyType.DynamicBody;
bodyDef.position.set(x, y);
Body body = this.world.createBody(bodyDef);
MassData massdata = new MassData();
massdata.center.set(1,1);
massdata.mass = 10;
body.setMassData(massdata);
FixtureDef fixtureDef = new FixtureDef();
EdgeShape shape = new EdgeShape();
shape.set(0, 0, 2, 2);
fixtureDef.shape= shape;
fixtureDef.friction = 1;
fixtureDef.restitution = .5f;
fixtureDef.density = 10;
body.createFixture(fixtureDef);
That is because an Edge Shape in Box2D is meant to create static scenery. It simply cannot move due to dynamics. I guess kinematic would work. This is logic, because an EdgeShape has no mass, since it has no surface (or volume if you would consider the 2D world as 3D with a fixed depth).
Here is an excerpt taken from the manual, which confirms my initial thoughts:
Edge shapes are line segments. These are provided to assist in making
a free-form static environment for your game. A major limitation of
edge shapes is that they can collide with circles and polygons but not
with themselves. The collision algorithms used by Box2D require that
at least one of two colliding shapes have volume. Edge shapes have no
volume, so edge-edge collision is not possible.
As Martijn said, I calculate and set mass data of the body. To do this, I calculate the center of mass assuming uniform density. I am using LIBGDX and so I needed a way to do this in java. I wrote the routine using Box2D's source. Feel free to use it for whatever you like.
EdgeShapes do not have mass, and so do not behave physically. To cause this kind of behavior, manually calculation was necessary.
public static MassData calculateMassData(List<Vector2> vertices,
float density) {
float k_inv3 = 1.0f / 3.0f;
float area = 0.0f;
float I = 0.0f;
Vector2 center = new Vector2();
Vector2 s = new Vector2();
for (int i = 0, size = vertices.size(); i < size; i++) {
s.add(vertices.get(i));
}
s.div(vertices.size());
for (int i = 0, size = vertices.size(); i < size; ++i) {
// Triangle vertices.
Vector2 e1 = new Vector2(vertices.get(i));
e1.sub(s);
Vector2 e2 = new Vector2(i + 1 < size ? vertices.get(i + 1)
: vertices.get(0));
e2.sub(s);
float D = e1.crs(e2);
float triangleArea = 0.5f * D;
area += triangleArea;
// Area weighted centroid
center.add(e1.cpy().add(e2).mul(k_inv3).mul(triangleArea));
float ex1 = e1.x, ey1 = e1.y;
float ex2 = e2.x, ey2 = e2.y;
float intx2 = ex1 * ex1 + ex2 * ex1 + ex2 * ex2;
float inty2 = ey1 * ey1 + ey2 * ey1 + ey2 * ey2;
I += (0.25f * k_inv3 * D) * (intx2 + inty2);
}
MassData data = new MassData();
// Total mass
data.mass = density * area;
center.mul(1.0f / area);
data.center.set(center.cpy().add(s));
// Inertia tensor relative to the local origin (point s).
data.I = density * I;
// Shift to center of mass then to original body origin.
data.I += data.mass
* (data.center.dot(data.center) - center.dot(center));
data.I = (data.I);
return data;
}
2 limitations of edge shapes:
Edge shapes do not collide with other edge shapes
Edge shapes are not normal polygons. There's no real outside/inside definitions for any polygons built using only edge shapes.
Because of #2, other bodies can wind up inside of polygons built with edge shapes.
Because of #1, I took a different approach and constructed my polygon using a series of narrow rectangles. This is working well, but unfortunately does not solve #2.
I am not wanting to use PolygonShape for fixtures because the polygon I am attempting to model is complex. It can have hundreds of vertices.
I have tried triangulating my polygon and creating fixtures from each of these triangles. Unfortunately often the resulting triangle's area is too small for Box2D, and causes exceptions with box2d.
I am open to other solutions here.
Try: http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/physics/box2d/Body.html#setFixedRotation%28boolean%29
body.setFixedRotation(false)
Also your friction is too high. Try 0.6f
I'm trying to make a useful/generic 2D polygon class for an OpenGL ES renderer.
When I create a polygon, I give it several parameters:
Polygon(Vector3 centerpoint, int numVertices, float inPolySize)
Then, I try to generate the vertices. This is where i'm having a tough time. I need to determine the number of vertices, get an angle, find the x/y position of that angle, someone take the size into account, AND offset by the position.
OpenGL works with big arrays of data. Nothing is nice like Lists of Vector3's. Instead it's float[] arrays, with the first index being X1, second being Y1, third being Z1, fourth being X2, etc...
final int XPOS = 0;
final int YPOS = 1;
final int ZPOS = 2;
int mvSize = 3; // (x, y, z);
float[] vertices = new float[mvSize * mNumVertices];
for (int verticeIndex = 0; verticeIndex < mNumVertices; verticeIndex++)
{
double angle = 2 * verticeIndex * Math.PI / mNumVertices;
vertices[mvSize * verticeIndex + XPOS] = (((float)Math.cos(angle)) * mPolygonSize) + mPosition.GetX();
vertices[mvSize * verticeIndex + YPOS] = (((float)Math.sin(angle)) * mPolygonSize) + mPosition.GetY();
vertices[mvSize * verticeIndex + ZPOS] = mPolygonSize + mPosition.GetZ();
}
Unfortunatley, my triangle is never quite right. It's skewed a lot, the size doesn't seem right...
I figure i'm throwing the size into the wrong formula, can anyone help?
EDIT:
Here's some sample data
Polygon test = new Polygon( new Vector3(0, 1, 0), 3, .5f);
vertices[0] = -0.25
vertices[1] = 1.4330127
vertices[2] = 0.0
vertices[3] = -0.25
vertices[4] = 0.5669873
vertices[5] = 0.0
vertices[6] = 0.5
vertices[7] = 1.0
vertices[8] = 0.0
vertices[9] = -0.25
vertices[10] = 1.4330127
vertices[11] = 0.0
I can't believe I was this stupid. Basically, my render window was smaller than my screen. If my screen is a rectangle, my render window was a square.
This being the case, any triangle I draw that was up was clipped by my render window. To me, it looked like the triangle was skewed. Really, it was just clipped!
The Java math library takes radians as input, not degrees. I didn't see the angles you were using for your calculation, but if you're not converting to radians from degrees, you will get some skewed looking shapes, and would explain that your calculations are correct, but the expected result is off.
I use this method which works perfectly to draw a full circle(might be typos in code text I wrote from memory):
drawCircle(GLAutodrawble drawble){
GL gl = drawble.getGL();
gl.glTranslatef(0.0f,0.0f,-7.0f);
gl.glBeginf(GL_LINE_LOOP);
gl.glColorf(0.0f,0.0f,0.0);
final dobule PI = 3.141592654;
double angle = 0.0;
int points = 100;
for(int i =0; i < points;i++){
angle = 2 * PI * i / points;
gl.glVertexf((float)Math.cos(angle),(float)Math.sin(angle));
}
gl.glScalef(1.0f,1.0f,0.0f);
gl.glEnd();
}
I want to use the same priciples to make method to make a half circle, I don't get my head around what I should do with the cos sin stuff. Can anyone take a look and help me.
Thanks goes to all that thakes a look at the problem!
Replace :
angle = 2 * PI * i / points;
With :
angle = PI * i / points;
Notice I removed the 2 multiplier as 2*PI is 360 (in degrees) which is a full circle. PI (180 degrees) is half a circle
Change this line:
angle = 2 * PI * i / points;
to this:
angle = 1 * PI * i / points;
Drawing circle is like the drawing a lines , connecting them. And the points should too close to each other to create a smooth curve.
you can use the following code to draw a half circle in opengl.
float PI = 3.14
float step=5.0;// How far is the next point i.e it should be small value
glBegin(GL_LINE_STRIP)
for(float angle=0.0f,angle<=180; angle+=step)
{
float rad = PI*angle/180;
x = centerX+radius*cos(rad);
y = centerY+radius*sin(rad);
glVertex(x,y,0.0f);
}
glEnd();
I'm working with a Java 3D application called "Walrus" that is used to display directed graphs. The code already has a feature to highlight a node and draw label adjacent in graph given its screen coordinates.
Upon rotating the screen, the node is no more highlighted.
What I have is the node coordinates in 3D. I need to draw label to it.
Code for highlight using 3D coordinates
Point3d p = new Point3d();
m_graph.getNodeCoordinates(node, p);
PointArray array = new PointArray(1, PointArray.COORDINATES);
array.setCoordinate(0, p);
m_parameters.putModelTransform(gc);
gc.setAppearance(m_parameters.getPickAppearance());
How can I draw Label with 3D coordinates( Raster graphics throws error Renderer: Error creating immediate mode Canvas3D graphics context )
How can I convert 3D coordinates to 2D screen and use existing code to draw label at 2D screen point
Thanks,
Dakshina
I have an algorithm/method for converting [x,y,z] into [x,y] with the depth parameter:
The x value is : (int) (x - (z / depth * x))
The y value is : (int) (y - (z / depth * y))
Essentially, the depth is the focal point. The vanishing point will be at [0,0,depth].
Here's what i used to convert my 3D coordinates into perspective 2D, x2 and y2 being the 2dimensional coordinates, xyz being the 3D coordinates.
use these formulas:
x2 = cos(30)*x - cos(30)*y
y2 = sin(30)*x + sin(30)*y + z
I picked the angle 30 as it is easy for perspective purposes, also used in Isometric grids for drawing 3D on 2D papers. As the z axe will be the vertical one, x and y are the ones at 60 degrees from it right and left. Isometric Grid Picture.
I'm still working on rotation, but without altering the axes, just coordinate rotation in 3D.
Enjoy.
I found the solution.
This is the function to display Text3D at image 2D coordinates
public void drawLabel(GraphicsContext3D gc, double x, double y, int zOffset, String s) {
boolean frontBufferRenderingState = gc.getFrontBufferRendering();
gc.setBufferOverride(true);
gc.setFrontBufferRendering(true);
Point3d eye = getEye();
double labelZ = zOffset * LABEL_Z_OFFSET_SCALE
+ LABEL_Z_SCALE * eye.z + LABEL_Z_OFFSET;
double xOffset = LABEL_X_OFFSET * m_pixelToMeterScale;
double yOffset = LABEL_Y_OFFSET * m_pixelToMeterScale;
Point3d p = new Point3d(x + xOffset, y + yOffset, 0.0);
{
// Project given (x, y) coordinates to the plane z=labelZ.
// Convert from image-plate to eye coordinates.
p.x -= eye.x;
p.y -= eye.y;
double inversePerspectiveScale = 1.0 - labelZ / eye.z;
p.x *= inversePerspectiveScale;
p.y *= inversePerspectiveScale;
// Convert from eye to image-plate coordinates.
p.x += eye.x;
p.y += eye.y;
}
Transform3D scale = new Transform3D();
scale.set(LABEL_SCALE);
Vector3d t = new Vector3d(p.x, p.y, labelZ);
Transform3D translation = new Transform3D();
translation.set(t);
translation.mul(scale);
Transform3D transform = new Transform3D(m_imageToVworld);
transform.mul(translation);
gc.setModelTransform(transform);
//-----------------
int fontSize=(int)(10*m_magnification);
if(fontSize>20)
fontSize=20;
//---------------
// XXX: Courier may not be available on all systems.
Text2D text = new Text2D(s, new Color3f(1.0f, 1.0f, 1.0f),
"Courier", fontSize, Font.BOLD);
gc.draw(text);
gc.flush(true);
// NOTE: Resetting the model transform here is very important.
// For some reason, not doing this causes the immediate
// following frame to render incorrectly (but subsequent
// frames will render correctly). In some ways, this
// makes sense, because most rendering code assumes that
// GraphicsContext3D has been set to some reasonable
// transform.
gc.setModelTransform(m_objectTransform);
gc.setFrontBufferRendering(frontBufferRenderingState);
}
This is the function to take 3D coordinates and convert them to image 2D coordinates and render using above function
private boolean displayOnScreenLabel(int node, String label) {
boolean success = false;
try {
Transform3D transform = m_parameters.getObjectToEyeTransform();
Point3d nodeC = new Point3d();
m_graph.getNodeCoordinates(node, nodeC);
transform.transform(nodeC);
Point3d eye = m_parameters.getEye();
double perspectiveScale = 1.0 / (1.0 - nodeC.z / eye.z);
double centerX = eye.x + nodeC.x * perspectiveScale;
double centerY = eye.y + nodeC.y * perspectiveScale;
GraphicsContext3D gc = m_canvas.getGraphicsContext3D();
m_parameters.drawLabel(gc, centerX, centerY, m_labelZOffsetCounter++, label);
success = true;
} catch (final java.lang.OutOfMemoryError error) {
JOptionPane.showMessageDialog(m_frame, "The 3D Graphics is unable to find enough memory on your system. Kill the application!", "Out Of Memory!", JOptionPane.ERROR_MESSAGE);
} catch (Exception e) {
success = false;
}
return success;
}
Alright, so this is how I am doing it:
float xrot = 0;
float yrot = 0;
float zrot = 0;
Quaternion q = new Quaternion().fromRotationMatrix(player.model.getRotation());
if (q.getW() > 1) {
q.normalizeLocal();
}
float angle = (float) (2 * Math.acos(q.getW()));
double s = Math.sqrt(1-q.getW()*q.getW());
// test to avoid divide by zero, s is always positive due to sqrt
// if s close to zero then direction of axis not important
if (s < 0.001) {
// if it is important that axis is normalised then replace with x=1; y=z=0;
xrot = q.getXf();
yrot = q.getYf();
zrot = q.getZf();
// z = q.getZ();
} else {
xrot = (float) (q.getXf() / s); // normalise axis
yrot = (float) (q.getYf() / s);
zrot = (float) (q.getZf() / s);
}
But it doesn't seem to work when I try to put it into use:
player.model.addTranslation(xrot * player.speed, 0, zrot * player.speed);
AddTranslation takes 3 numbers to move my model by than many spaces (x, y, z), but hen I give it the numbers above it doesn't move the model in the direction it has been rotated (on the XZ plane)
Why isn't this working?
Edit: new code, though it's about 45 degrees off now.
Vector3 move = new Vector3();
move = player.model.getRotation().applyPost(new Vector3(1,0,0), move);
move.multiplyLocal(-player.speed);
player.model.addTranslation(move);
xrot, yrot, and zrot define the axis of the rotation specified by the quaternion. I don't think you want to be using them in your addTranslation() call...in general, that won't have anything to do with the direction of motion.
What I mean by that is: your 3-D object -- let's say for the sake of argument that it's an airplane -- will have a certain preferred direction of motion in its original coordinate
system. So if the original orientation has the center of mass at the origin, and the
propeller somewhere along the +X axis, the plane wants to fly in the +X direction.
Now you introduce some coordinate transformation that rotates the airplane into some other orientation. That rotation is described by a rotation matrix, or equivalently, by a
quaternion. Which way does the plane want to move after the rotation?
You could find
that by taking a unit vector in the +X direction: (1.0, 0.0, 0.0), then applying the
rotation matrix or quaternion to that vector to transform it into the new coordinate
system. (Then scale it by the speed, as you're doing above.) The X, Y, and Z components
of the transformed, scaled vector give the desired incremental motion along each axis. That transformed vector is generally not going to be the rotation axis of the quaternion, and I think that's probably your problem.