Alright, so I got a bit of movement code and I'm thinking I'm going to need to manually input when to go up/down a slope. All I got to work with is the slope's normal, and vector, and My current and previous position, and my yaw.
Is there a better way to rotate whether I go up or down the slope based on my yaw?
Vector3f move = new Vector3f(0,0,0);
move.x = (float)-Math.cos(Math.toRadians(yaw));
move.z = (float)-Math.sin(Math.toRadians(yaw));
System.out.println("slopeNormal.z: " + slopeNormal.z + "move.z: " + move.z);
move.normalise();
float vx = (float) (Math.sqrt(Math.pow(move.y, 2) + Math.pow(move.z, 2)) * move.x);
float vy = (float) (Math.sqrt(Math.pow(move.x, 2) + Math.pow(move.z, 2)) * move.y);
float vz = - vx * slopeNormal.x - vy * slopeNormal.y;
move.scale(movementSpeed * delta);
if(vz < 0)
move.y -= slopeVec.y * 1.5f;
if(vz > 0)
move.y += slopeVec.y * 1.5f;
Vector3f.add(pos, move, pos);
Edit: updated code.
First off, the following is incorrect:
move.x = (float)-Math.toDegrees(Math.cos(Math.toRadians(yaw)));
move.z = (float)-Math.toDegrees(Math.sin(Math.toRadians(yaw)));
Math.toDegrees converts an angle in radians to one in degrees, but the results of Math.cos and Math.sin are not angles.
Assume zero yaw is in the positive x-direction... and define vx, vy, vz = rate of motion along 3 axes, s = speed, and slope normal = nx, ny, nz where nx^2 + ny^2 + nz^2 = 1. So nx = ny = 0, nz = 1 would be flat.
First, I define x', y' = axes relative to the flat ground (motion is constrained to ground). Then (the following is not valid Java, but I'm enclosing it in code format anyway):
vx' = cos(yaw) * s
vy' = sin(yaw) * s
Then I need to rotate from x', y' coordinates to real-world coordinates. That is done using the slope normal:
vx = sqrt(vy^2 + vz^2) vx'
vy = sqrt(vx^2 + vz^2) vy'
vz = - vx' nx - vy' ny
A check on this transformation: vx^2 + vy^2 + vz^2 must equal vx'^2 + vy'^2 = s^2. I think this works out.
So to answer your question: up or down? vz > 0 is up, vz < 0 is down.
Related
I am trying to get into creative coding mainly for creating live visuals. I have recently stumbled upon this great website called https://www.openprocessing.org/ where people can share their creations.
I have attached code below for creating two moving circles but I am having trouble understanding how the creator went about doing so, If anyone could explain to me how the for loop is working as well as how the x += 0.006; y += 0.006; if (x > TWO_PI) {x = 0;} section works, it would be greatly appreciated. The use of sin, cos and the Two_PI functions has me puzzled. Here is a link to the original code:
https://www.openprocessing.org/sketch/467333
//comment
float x = 0;
float xx = 0;
float y = 0;
float yy = 0;
float sizecircle = 250;
void setup() {
size (800, 650);
frameRate (60);
strokeWeight (1);
stroke (223, 170, 22);
}
void draw() {
background (51, 51, 51);
for (float i = 0; i < TWO_PI; i += TWO_PI/100) {
line (350 + sin(x+i) * sizecircle, 275 + cos(y+i) * sizecircle, 450 + cos(xx+i) * sizecircle, 375 + sin(yy+i) * sizecircle);
}
x += 0.006;
y += 0.006;
if (x > TWO_PI) {
x = 0;
}
if (y > TWO_PI) {
y = 0;
}
xx += 0.002;
yy += 0.002;
if (xx > TWO_PI) {
xx = 0;
}
if (yy > TWO_PI) {
yy = 0;
}
}
The unit of the angle for sin and cos is Radian. 360° are 2*PI, this is the reason for TWO_PI.
The variables x, y, xx and yy are incremented for 0.0 to 2*PI. If they reach 2*PI, they start form 0.0 again.
With the following code will draw lines from a center point (cx, cy) to 100 points around a circle with radius r.
for (float i = 0; i < TWO_PI; i += TWO_PI/100) {
line(cx, cy, cx + cos(i)*r, cy + sin(i)*r);
}
The trick in the code of the question is that the lines are connection the points around 2 circles, which are rotating opposite direction:
line(cx1 + sin(i)*r, cy1 + cos(i)*r,
cx2 + cos(i)*r, cy2 + sin(i)*r);
Note, that the order of sin and cos is swapped for the start point in compare to the end point, this causes that the circles are rotating opposite directions.
The different rotation speed is caused by the different constants 0.006 respectively 0.002.
By the way, the code can be simplified, because x == y and xx == yy. It is sufficient to use 2 angles in the range [0, TWO_PI]:
float a1 = 0;
float a2 = 0;
float sizecircle = 250;
void draw() {
background (51, 51, 51);
for (float i = 0; i < TWO_PI; i += TWO_PI/100) {
line (350 + sin(a1+i)*sizecircle, 275 + cos(a1+i)*sizecircle,
450 + cos(a2+i)*sizecircle, 375 + sin(a2+i)*sizecircle);
}
a1 += 0.006;
a2 += 0.002;
}
Since sin(x) == sin(x + TWO_PI*n) and cos(x) == cos(x + TWO_PI*n) (n is an integral number), it is not necessary to "reset" the angles.
It's more about math than about programming (well, both these things goes hand in hand).
He's doing the same thing twice, once for each circle, but one of the two will "move" faster than the other, hence the difference in x += 0.006; and xx += 0.002;.
There are 2 PI radians in a full circle (so 2 PI radians == 360 degrees). That's why he's using this measure.
This line
line (350 + sin(x+i) * sizecircle, 275 + cos(y+i) * sizecircle, 450 + cos(xx+i) * sizecircle, 375 + sin(yy+i) * sizecircle);
defines how each circle is "attached" to the other one by drawing a bunch of lines between them. The idea is that the author created a loop that updated the beginning point and the end point of a line, and this loop runs as long as there are lines to draw (it goes around the circle using the 2 PI number).
So in the for (float i = 0; i < TWO_PI; i += TWO_PI/100) loop he draws every line for this position of the circles.
Than he changes the "starting point" where he'll draw the first line by increasing variables x, y, xx, yy a little bit. As they are used in the context of radians, they "circle" around the circles.
Then the draw() loop start over again and he re-draws the whole thing, but a little different as the starting points changed. This makes the drawing look like it moves.
When the "starting points" variables x, y, xx, yy are finished doing a complete turn (so when they are over 2 PI radians), he resets them. As it's a full turn, it's not a huge reset. It's like rounding the time when the clock is one minute past the hour.
Hope it helps.
my math isnt too great but im trying to learn though..
What im trying to do is give my games missiles a helix rocket effect, but i dont know how to work the Sin and Cos to make the helix play out in the right direction..
This is a 3D game by the way:
The problem is, depending on which direction the missile faces, the helix looks warped or flat..
Whats the best way to mathematically calculate a helix based on the missiles X,Y,Z/direction?, ive been trying to figure it out for a long time :/
Thanks alot!
double x = radius * Math.cos(theta);
double y = radius * Math.sin(theta);
double z = radius * Math.cos(theta);
location.add(x,y,z);
missile.shootFlame(location,2);
location.subtract(x,y,z);
Basis vectors
you need the overall direction of missile as 3D vector let call it W. From it you need to get 2 another vectors U,V which are all perpendicular to each other. To get them you can exploit cross product. So:
make W unit vector
Just W = W/|W| so:
l=sqrt(Wx*Wx+Wy*Wy+Wz*Wz);
Wx/=l;
Wy/=l;
Wz/=l;
choose U as any direction non parallel to W
so start with U=(1.0,0.0,0.0) and if U==W choose U=(0.0,1.0,0.0). If you got anything to lock to use that as U direction so the coordinate system will not rotate with time (like Up,North,Sun ...)
U should be unit so if not normalize it just like in #1
compute V
It should be perpendicular to U,W so use cross product:
V = W x U
Cross product of unit vectors is also unit vector so no need to normalize.
recompute U
As we choose the U manually we need to make sure it is also perpendicular to V,W so:
U = V x W
Now we have 3 perpendicular basis vectors where U,V lies in plane of the helix screws and W is the overall movement direction.
If you do not know how to compute the cross product see:
Understanding 4x4 homogenous transform matrices look for [edit2].
Now the Helix is easy:
Defines
so we have U,V,W on top of that we need radius r [units], movement speed v [units/s], angular speed o [rad/s] time t>=0.0 [s] and start position P0.
Helix equation
What we need is equation returning actual position for time so:
ang = o*t;
P(t) = P0 + U*r*cos(ang) + V*r*sin(ang) + W*v*t;
rewritten to scalars:
ang = o*t;
x = P0x + Ux*r*cos(ang) + Vx*r*sin(ang) + Wx*v*t;
y = P0y + Uy*r*cos(ang) + Vy*r*sin(ang) + Wy*v*t;
z = P0z + Uz*r*cos(ang) + Vz*r*sin(ang) + Wz*v*t;
[edit1] as you are incompetent to copy paste and or changing my code correctly...
Vector w = loc.getDirection();
double wX = w.getX();
double wY = w.getY();
double wZ = w.getZ();
double l = Math.sqrt((wX * wX) + (wY * wY) + (wZ * wZ));
wX = wX / l;
wY = wY / l;
wZ = wZ / l;
w = new Vector(wX,wY,wZ); // you forget to change W and use it latter ...
Vector u = new Vector(0, 1.0, 0);
if (Math.abs(wX)<1e-3) // if U and W are the same chose different U
if (Math.abs(wZ)<1e-3)
u = new Vector(1.0, 0.0, 0);
Vector v = w.crossProduct(u);
u = v.crossProduct(w);
double radius = 10; // helix radius [units]
double speed = 2.00; // movement speed [unit/s]
double omega = 0.628; // angular speed [rad/s]
//double omega = 36.0; // angular speed [deg/s]
for (double i = 0; i < 100; i += 1.0) // time [s]
{
double angle = omega * i; // actual screw position [rad] or [deg]
double x = u.getX() * radius * Math.cos(angle) + v.getX() * radius * Math.sin(angle) + wX * speed * i;
double y = u.getY() * radius * Math.cos(angle) + v.getY() * radius * Math.sin(angle) + wY * speed * i;
double z = u.getZ() * radius * Math.cos(angle) + v.getZ() * radius * Math.sin(angle) + wZ * speed * i;
loc.add(x,y,z); // What is this? should not you set the x,y,z instead of adding?
//do work
loc.subtract(x,y,z); // what is this?
}
This should provide you with helix points with traveled linear distance
speed*imax = 2.0*100.0 = 200.0 units
And screws:
omega*imax/(2*Pi) ~= 0.628*100.0/6.28 ~= 10 screws // in case of sin,cos want [rad]
omega*imax/360.0 = 36.0*100.0/360 = 10.0 screws // in case of sin,cos want [deg]
Do not forget to rem in/out the correct omega line (I choose [rad] as that is what I am used that my math libs use). Not sure If I translated to your environment correctly there may be bugs like abs has different name or u = new Vector(1.0, 0.0, 0); can be done on intermediate or declaration of variable only etc which I do not know as I do not code in it.
I have a circle of let's say 10 of radius with the center x=0 y=0. And I have a number n (e.g. 3). I want to get a point from that circle. Here is an explanation with an image:
So if n=0, the method would return 0;-6
And if n=1, the method would return 3;-5
etc.
But the method would receive parameters like the unit between each n etc.
The equation of a circle is
x = x0 + r * cos(a)
y = y0 + r * sin(a)
with (x0, y0) the center of the circle and a in 0...2Pi
so if you want y given x you will have :
sin(a) = (y - y0)/r
so
a = arcsin((y - y0)/r) if ((y - y0)/r is in -PI/2..PI/2)
a = -arcsin((y - y0)/r) if ((y - y0)/r is in -PI..-PI/2 or PI/2..PI)
a is undefine elsewhere
therefore
y = y0 + r * sin(arcsin((y - y0)/r)) if ((y - y0)/r is in -PI/2..PI/2))
y = y0 + r * sin(-arcsin((y - y0)/r)) if ((y - y0)/r is in -PI..-PI/2 or PI/2..PI))
y is undefine elsewhere
Use the roots of unity, it will give you the exponential form of a complex on the circle. You can then use the Euler formula to get the real coordinates of your point. Of course, since your circle is not unitary, you must take into account its radius.
I'm programming a software renderer in Java, and am trying to use Z-buffering for the depth calculation of each pixel. However, it appears to work inconsistently. For example, with the Utah teapot example model, the handle will draw perhaps half depending on how I rotate it.
My z-buffer algorithm:
for(int i = 0; i < m_triangles.size(); i++)
{
if(triangleIsBackfacing(m_triangles.get(i))) continue; //Backface culling
for(int y = minY(m_triangles.get(i)); y < maxY(m_triangles.get(i)); y++)
{
if((y + getHeight()/2 < 0) || (y + getHeight()/2 >= getHeight())) continue; //getHeight/2 and getWidth/2 is for moving the model to the centre of the screen
for(int x = minX(m_triangles.get(i)); x < maxX(m_triangles.get(i)); x++)
{
if((x + getWidth()/2 < 0) || (x + getWidth()/2 >= getWidth())) continue;
rayOrigin = new Point2D(x, y);
if(pointWithinTriangle(m_triangles.get(i), rayOrigin))
{
zDepth = zValueOfPoint(m_triangles.get(i), rayOrigin);
if(zDepth > zbuffer[x + getWidth()/2][y + getHeight()/2])
{
zbuffer[x + getWidth()/2][y + getHeight()/2] = zDepth;
colour[x + getWidth()/2][y + getHeight()/2] = m_triangles.get(i).getColour();
g2.setColor(m_triangles.get(i).getColour());
drawDot(g2, rayOrigin);
}
}
}
}
}
Method for calculating the z value of a point, given a triangle and the ray origin:
private double zValueOfPoint(Triangle triangle, Point2D rayOrigin)
{
Vector3D surfaceNormal = getNormal(triangle);
double A = surfaceNormal.x;
double B = surfaceNormal.y;
double C = surfaceNormal.z;
double d = -(A * triangle.getV1().x + B * triangle.getV1().y + C * triangle.getV1().z);
double rayZ = -(A * rayOrigin.x + B * rayOrigin.y + d) / C;
return rayZ;
}
Method for calculating if the ray origin is within a projected triangle:
private boolean pointWithinTriangle(Triangle triangle, Point2D rayOrigin)
{
Vector2D v0 = new Vector2D(triangle.getV3().projectPoint(modelViewer), triangle.getV1().projectPoint(modelViewer));
Vector2D v1 = new Vector2D(triangle.getV2().projectPoint(modelViewer), triangle.getV1().projectPoint(modelViewer));
Vector2D v2 = new Vector2D(rayOrigin, triangle.getV1().projectPoint(modelViewer));
double d00 = v0.dotProduct(v0);
double d01 = v0.dotProduct(v1);
double d02 = v0.dotProduct(v2);
double d11 = v1.dotProduct(v1);
double d12 = v1.dotProduct(v2);
double invDenom = 1.0 / (d00 * d11 - d01 * d01);
double u = (d11 * d02 - d01 * d12) * invDenom;
double v = (d00 * d12 - d01 * d02) * invDenom;
// Check if point is in triangle
if((u >= 0) && (v >= 0) && ((u + v) <= 1))
{
return true;
}
return false;
}
Method for calculating surface normal of a triangle:
private Vector3D getNormal(Triangle triangle)
{
Vector3D v1 = new Vector3D(triangle.getV1(), triangle.getV2());
Vector3D v2 = new Vector3D(triangle.getV3(), triangle.getV2());
return v1.crossProduct(v2);
}
Example of the incorrectly drawn teapot:
What am I doing wrong? I feel like it must be some small thing. Given that the triangles draw at all, I doubt it's the pointWithinTriangle method. Backface culling also appears to work correctly, so I doubt it's that. The most likely culprit to me is the zValueOfPoint method, but I don't know enough to know what's wrong with it.
My zValueOfPoint method was not working correctly. I'm unsure why :( however, I changed to a slightly different method of calculating the value of a point in a plane, found here: http://forum.devmaster.net/t/interpolation-on-a-3d-triangle-using-normals/20610/5
To make the answer here complete, we have the equation of a plane:
A * x + B * y + C * z + D = 0
Where A, B, and C are the surface normal x/y/z values, and D is -(Ax0 + By0 + Cz0).
x0, y0, and z0 are taken from one of the vertices of the triangle. x, y, and z are the coordinates of the point where the ray intersects the plane. x and y are known values (rayOrigin.x, rayOrigin.y) but z is the depth which we need to calculate. From the above equation we derive:
z = -A / C * x - B / C * y - D
Then, copied from the above link, we do:
"Note that for every step in the x-direction, z increments by -A / C, and likewise it increments by -B / C for every step in the y-direction.
So these are the gradients we're looking for to perform linear interpolation. In the plane equation (A, B, C) is the normal vector of the plane.
It can easily be computed with a cross product.
Now that we have the gradients, let's call them dz/dx (which is -A / C) and dz/dy (which is -B / C), we can easily compute z everywhere on the triangle.
We know the z value in all three vertex positions.
Let's call the one of the first vertex z0, and it's position coordinates (x0, y0). Then a generic z value of a point (x, y) can be computed as:"
z = z0 + dz/dx * (x - x0) + dz/dy * (y - y0)
This found the Z value correctly and fixed my code. The new zValueOfPoint method is:
private double zValueOfPoint(Triangle triangle, Point2D rayOrigin)
{
Vector3D surfaceNormal = getNormal(triangle);
double A = surfaceNormal.x;
double B = surfaceNormal.y;
double C = surfaceNormal.z;
double dzdx = -A / C;
double dzdy = -B / C;
double rayZ = triangle.getV1().z * modelViewer.getModelScale() + dzdx * (rayOrigin.x - triangle.getV1().projectPoint(modelViewer).x) + dzdy * (rayOrigin.y - triangle.getV1().projectPoint(modelViewer).y);
return rayZ;
}
We can optimize this by only calculating most of it once, and then adding dz/dx to get the z value for the next pixel, or dz/dy for the pixel below (with the y-axis going down). This means that we cut down on calculations per polygon significantly.
this must be really slow
so much redundant computations per iteration/pixel just to iterate its coordinates. You should compute the 3 projected vertexes and iterate between them instead look here:
triangle/convex polygon rasterization
I dislike your zValueOfPoint function
can not find any use of x,y coordinates from the main loops in it so how it can compute the Z value correctly ?
Or it just computes the average Z value per whole triangle ? or am I missing something? (not a JAVA coder myself) in anyway it seems that this is your main problem.
if you Z-value is wrongly computed then Z-Buffer can not work properly. To test that look at the depth buffer as image after rendering if it is not shaded teapot but some incoherent or constant mess instead then it is clear ...
Z buffer implementation
That looks OK
[Hints]
You have too much times terms like x + getWidth()/2 why not compute them just once to some variable? I know modern compilers should do it anyway but the code would be also more readable and shorter... at least for me
I'm just trying to code a nice looking physics game.
The ball collision looks nice but if the balls are colliding too slow, they "stick" in each other. I have no clue why they do.
Here's my collision function:
private void checkForCollision(ArrayList<Ball> balls) {
for (int i = 0; i < balls.size(); i++) {
Ball ball = balls.get(i);
if (ball != this && ball.intersects(this)) {
this.collide(ball, false);
}
}
}
public boolean intersects(Ball b) {
double dx = Math.abs(b.posX - posX);
double dy = Math.abs(b.posY - posY);
double d = Math.sqrt(dx * dx + dy * dy);
return d <= (radius + b.radius);
}
private void collide(Ball ball, boolean b) {
double m1 = this.radius;
double m2 = ball.radius;
double v1 = this.motionX;
double v2 = ball.motionX;
double vx = (m1 - m2) * v1 / (m1 + m2) + 2 * m2 * v2 / (m1 + m2);
v1 = this.motionY;
v2 = ball.motionY;
double vy = (m1 - m2) * v1 / (m1 + m2) + 2 * m2 * v2 / (m1 + m2);
if (!b)
ball.collide(this, true);
System.out.println(vx + " " + vy);
motionX = vx * BOUNCEOBJECT;
motionY = vy * BOUNCEOBJECT;
}
But this is what happens when they collide with a low speed:
So do you have an idea?
EDIT:
The update of Alnitak works very nice... but one problem is still there... if i add gravity like this:
public void physic() {
motionY += GRAVITY; // <= this part (GRAVITY is set to 0.3D)
checkForCollision(screen.balls);
keyMove();
bounceWalls();
posX += motionX;
posY += motionY;
}
They still move into each other. I think this is the wrong way to add gravity, or isn't it?
And I think I did something wrong with the collision formula, because they don't fall right:
!
and then they slowly sink into the ground.
EDIT:
found an AMAZING tutorial: http://www.ntu.edu.sg/home/ehchua/programming/java/J8a_GameIntro-BouncingBalls.html
This is a common problem that happens because sometimes the delta-v of the bouncing ball is insufficient to take it back out of the collision zone.
So the collision routine reverses the direction again, taking it back inside the other ball, ad-infinitum.
You should add a sufficient offset (in the direction of the collision force) to the position of the ball to ensure that the newly calculated positions are no longer colliding.
Alternatively, check whether the balls would collide once you add the new motion values:
public boolean intersects(Ball b) {
double dx = b.posX - (posX + motionX); // no need for Math.abs()
double dy = b.posY - (posY - motionY);
double d = dx * dx + dy * dy; // no need for Math.sqrt()
return d < (radius + b.radius) * (radius + b.radius);
}
but you should also change ball.intersects(this) to intersects(ball).
They may appear to collide slightly too early, but on a fast moving ball it probably won't be visible.
(m1 - m2) * v1 / (m1 + m2) + 2 * m2 * v2 / (m1 + m2);
This has an integer value 2. Please make it 2.0f or 2.0d then check it out. It must be the problem for small speeds. Becuse integer constant autocasts multiplied doubles.
If this does not work, then Alnitak 's answer would be helpful.
If you need real nice physics, you should use the force then convert it to velocity then convert it to displacement . Look at integrator techniques like Runge Kutta and Euler Integration
Force-->acceleration-->velocity-->displacement
if collision occurs, just update the force then the rest will be flowing.
----> http://codeflow.org/entries/2010/aug/28/integration-by-example-euler-vs-verlet-vs-runge-kutta/ <-----
http://www.forums.evilmana.com/game-programming-theory/euler-vs-verlet-vs-rk4-physics/
http://www.newagepublishers.com/samplechapter/001579.pdf
http://cwx.prenhall.com/bookbind/pubbooks/walker2/
Verlet integration is a point between Runge-Kutta-4 and Euler Integration preferably for molecular dynamics (a good example for bouncing balls if you ommit the electrical fields and bonds)
Just found an AMAZING tutorial:
http://www.ntu.edu.sg/home/ehchua/programming/java/J8a_GameIntro-BouncingBalls.html