3D ball rolling on wrong axis LibGDX - libgdx

Hello I'm trying to make a billiards game using libgdx. I'm using 3d models for the balls and an Orthographic Camera to view them. I am having trouble getting them to roll correctly after rolling on a different axis. Here is a clip of what they look like when they're rolling.
As you can see they appear to be rotating as if they were on their starting axis. Is there any way to rotate it so that it looks like it's actually rolling. I am also not very familiar with transformation matrices or quaternions so im not too sure where to go.
Edit: Updated for clarity
Here is the code I use to update the rotation
public boolean update() {
if (!visible) {
return false;
}
Vector2 vBall = ballBody.getLinearVelocity();
float vAngle = ballBody.getAngularVelocity();
isMoving = true;
float x = ballBody.getPosition().x * SCALE;
float y = ballBody.getPosition().y * SCALE;
Vector2 axisInPlane = new Vector2(y - center.y, x - center.x).rotateRad(Math.PI/2f);
Vector3 axis3D = new Vector3(axisInPlane.x,axisInPlane.y,0f);
ball3D.transform.rotate(axis, (float) Math.toDegrees(dist / RADIUS_PX));
ball3D.transform.setTranslation(mapX(x), mapY(y), 0);

Just to be sure, center is an arbitrary fixed point where there is no rotation and all rotations are derived from this distance/angle as the ball has no slippage.
So you can directly get the axis with
Vector2 axisInPlane = new Vector2(y - center.y, x - center.x).rotateRad(Math.PI/2f);
Vector3 axis3D = new Vector3(axisInPlane.x,axisInPlane.y,0f);
Also Math.toDegree takes radians as an argument, not a float, so dist/RADIUS_PX will be off, you have to supply as a fraction of 2PI (360 degs in radians). Also this should be the circumference of the ball not the radius. I don't know what class ball3D is but I would check that ball3D.transform.rotate does take degrees as an argument and if it does replace that line with
float rotateRadians =(float) Math.toDegrees((dist/CIRCUMFERENCE_PX)*Math.PI*2f);
ball3D.transform.rotate(axis, rotateRadians );

Related

How I can calculate the endpoint of a line, if I have the starting point, the angle and length of the line?

Point 1, say it is (0, 0) and I have another point that should turn around at a distance of 10f. Then I'll adding degrees angle to make it rotate. I be wanting to know how to calculate that point that this turning around each other ..
I will use the raycasting, I need to rotate the ray (clockwise) to detect collisions
So you say you have point1 and point2, both separated by a distance of 10f where point2 will be rotating around point1, and you want to know if between this separation an object at some point is intersecting them, something like the following image:
There are tutorials to get the maths for rotate a point arount another one in internet, like this one, and since you can't specify an origin for a Vector2, a translated version of the code proposed in the previews link to java should be something similar to:
public Vector2 rotatePoint(Vector2 center, Vector2 point, float angle) {
angle = angle * MathUtils.degreesToRadians; // Convert to radians
float rotatedX = MathUtils.cos(angle) * (point.x - center.x)
- MathUtils.sin(angle) * (point.y - center.y) + center.x;
float rotatedY = MathUtils.sin(angle) * (point.x - center.x)
+ MathUtils.cos(angle) * (point.y - center.y) + center.y;
// rotated new position:
return new Vector2(rotatedX, rotatedY);
}
As for the rest of the code (the intersection between objects), I guess you are looking for the RayCastCallback interface:
// initial position
Vector2 point1 = new Vector(0, 0);
// Max lenght of view
Vector2 point2 = new Vector(0, 10);
// Position of collision if occur
final Vector2 collisionPoint = new Vector();
#Override
public void render(float delta) {
//...
point2 = rotatePoint(point1, point2, 10); // rotate 10ยบ
// to detect if object at position point1 is seeing something
world.rayCast(new RayCastCallback(){
#Override
public float reportRayFixture(Fixture fixture, Vector2 point,
Vector2 normal, float fraction) {
// what do the object saw? -> fixture
// where do the object saw it? -> point
collisionPoint.set(point);
return 0; // <- return 0 to stop raycasting
}
}, point1, point2);
//... rotation and other stuffs...
}
The return parameter of reportRayFixture have this documentation:
Called for each fixture found in the query. You control how the ray cast proceeds by returning a float: return -1: ignore this fixture and continue return 0: terminate the ray cast return fraction: clip the ray to this point return 1: don't clip the ray and continue. The Vector2 instances passed to the callback will be reused for future calls so make a copy of them!
** Emphasis added.
Basically it says that you can check for all the intersections one by one, but if you care only for the first one, return 0 immediately. This is useful when you want to know if an object is being blocked by another one. In this case, I return 0 and copy the value of point to collisionPoint to let you do whatever you want to do with this value.
A very nice example can be found in this video.
Hope you find this useful.
You should consider using Intersector class to check if the line from your actor intersects with the body shape.
To calculate end of "sight" line use Vector2 that you will be rotating according to your actor rotation (which is actually answer for your question)
It should looks like:
Vector2 sightVector = new Vector2(10f, 0); //the 10f is actually your sight max distance
sightVector.rotate(actor.getRotation());
...
#Override
pblic void render(float delta) //it can be also act of the actor
{
sightVector.rotate(actor.getRotation());
Vector2 endOfLine = new Vector2(actor.getX() + sightVector.x, actor.getY() + sightVector.y); //here you are calculating the end of line
Polygon bodyShape = getBodyShape( theBody ); //you should create a method that will return your body shape
if( Intersector.intersectLinePolygon(new Vector2(actor.getX(), actor.getY()), endOfLine, bodyShape) )
{
//do something
}
...
}
Intersector has method to check intersection with circles etc also so your body Shape doesn't need to be polygon

AS3 shooting bullets to cursor from centre of character position

I'm making a top down shooter game. I've got my character moving. All I want to do next is make a bullet shoot from the center of my character to the direction my cursor is at. How would i go about doing this?
I'm really struggling to think of the code i need to make this work.
This will involve simple vector math. There are tons of resources online about this. Here's the basic gist:
1) First, calculate the angle (in radians) between your character and your target (in this case the mouse location). You can use Math.atan2() to perform this calculation.
var angle:Number = Math.atan2(mouseY - playerY, mouseX - playerX);
2) Next, use that angle to create a vector (x,y delta) which represents the direction of travel for your bullet. You use Math.cos() and Math.sin() to compute the x and y value:
var speed:Number = 5;
var vector:Point = new Point(Math.cos(angle) * speed, Math.sin(angle) * speed);
3) Now you can update the bullets position each frame by that vector:
bullet.x += vector.x;
bullet.y += vector.y;
4) And if you want to make your bullet sprite point in the direction of travel, convert that angle to degrees and set the bullet sprite's rotation:
var degrees:Number = angle * (180 / Math.PI);
bullet.rotation = degrees;
Note that for the purpose of the math here, 0 degrees is considered to be right-facing along the x-axis, not up-facing like you might naturally think of 0 degrees (at least I do). What this means is your sprites unrotated orientation should be facing right-ward.

LibGdx Bow and arrow game physics

I'm working on a new game written with LibGdx Engine and Java.
I've got a problem with some of the physics in this game.
I want to shoot the arrow in a ballistic trajectory (angry bird style)
and can't find the equation to do so .
I am using these velocity equations:
float velx = (float) (Math.cos(rotation) * spd);
float vely = (float) (Math.sin(rotation) * spd);
I add this to the current position and the arrow shoots in one direction - straight.
I thought maybe changing the rotation would help me achieve what I want (a ballistic path).
It does help, but I want to have the trajectory as well.
I saw this
ProjectileEquation class that someone already posted but didn't know how to work with it:
public class ProjectileEquation
{
public float gravity;
public Vector2 startVelocity = new Vector2();
public Vector2 startPoint = new Vector2();
public Vector2 gravityVec = new Vector2(0,-10f);
public float getX(float n) {
return startVelocity.x * (n ) + startPoint.x;
}
public float getY(float n) {
float t = n;
return 0.5f * gravity * t * t + startVelocity.y * t + startPoint.y;
}
}
I'm looking for some help to help me use this class for ballistic trajectories.
This is how I tried using it:
for(int i =0;i<30;i++)
{
Texture f = ResData.Square_1;
ProjectileEquation e= new ProjectileEquation();
e.gravity = 1;
e.startPoint = new Vector2(bow.getX(),bow.getY());//new Vector2(-bow.getX(),-bow.getY()); //My bow is opposite so it suppose to work fine
e.startVelocity = getVelocityOf(bow.getRotation());
Vector3 touchpos = new Vector3();
s.draw(f,e.getX(i) ,e.getX(i),5,5);
}
The ProjectileEquation class you post looks like it'll calculate the X and Y position given a time delta, so the float you pass in should be the time delta since you started the arrow moving (in seconds).
That code will not give you the angle of the arrow though. To find that, I would suggest you keep hold of the previous X and Y, then you can use Math.atan2() to calculate the angle based on the previous XY and the current XY. Google atan2 for a load of info on how to use it.
The very best way to do this however would be to use Box2d and model the scene correctly. Then you wouldn't have to get involved in the maths at all. I read somewhere that that's what Angry Birds uses, and is an excellent choice for modelling these sorts of physics games.
I hope your game goes well.

How can i find angle between two circle points in cocos2dx

I am working in cocos2dx game developing and working on circle gesture detection . I would like to ask how can I find angle between two points.How can i find angle between two points A and B.my ccTouchesMoved event as follows.
void HelloWorld::ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent)
{
CCLog("Touches moved");
CCTouch *touch = (CCTouch*)pTouches->anyObject();
location = touch->getLocation();
location=CCDirector::sharedDirector()->convertToGL(location);
prevLocation=CCDirector::sharedDirector()->convertToGL(touch->getPreviousLocationInView());
deltax=prevLocation.x-location.x;//difference of x
deltay=prevLocation.y-location.x;//difference of y
angle=??// i want this angle using deltax and deltay
}
You need to include math header and you can calculate angle in degree using formula:
angle = atan2 (deltay, deltax) * (180 / PI);

Strange stability issues with Matrix scale/rotation in Actionscript

I have a Flash app where I am performing a scale and rotation operation about the center of _background:MovieClip (representing a page of a book). I have simple event listeners on the GESTURE_ROTATE and GESTURE_SCALE events of this MC which update some variables currentRotation and currentScaleX, currentScaleY. I then have the following code trigger on the ENTER_FRAME event of the app.
The problem I am encountering is upon rotating the MC beyond the limits of roughly 60 or -60 degrees, or scaling slightly and rotating, the MC begins to oscillate and finally spin wildly out of control and off the screen. I've tried several things to debug it, and even tried Math.flooring the currentRotationValue and rounding the values of currentScaleX/Y to the tenths place (Math.floor(currentScale * 10) / 10), but neither of these seems to remedy it. I'm a little stuck at this point and have tried researching as much as I can, but couldn't find anything. Any suggestions? Is there an issue with doing this operation on each frame perhaps?
private function renderPage(e:Event) {
var matrix:Matrix = new Matrix();
// Get dimension of current rectangle.
var rect:Rectangle = _background.getBounds(_background.parent);
// Calculate the center.
var centerX = rect.left + (rect.width/2);
var centerY = rect.top + (rect.height/2);
// Translating to the desired reference point.
matrix.translate(-centerX, -centerY);
matrix.rotate(currentRotation / 180) * Math.PI);
matrix.scale(currentScaleX, currentScaleY);
matrix.translate(centerX, centerY);
_background.transform.matrix = matrix;
}
I'm not certain what behaviour you're trying to produce, but I think the problem is that centerX and centerY define the middle of _background in _background.parent's coordinate space. You're then translating the matrix so that _background is rotated around the values centerX, centerY, but in _background's coordinate space.
Assuming you want _background to rotate around a point which remains static on screen, what you actually need to do is use two different Points:
matrix.translate(-_rotateAroundPoint.x, -_rotateAroundPoint.y);
matrix.rotate(currentRotation / 180) * Math.PI);
matrix.scale(currentScaleX, currentScaleY);
matrix.translate(_centerOnPoint.x, _centerOnPoint.y);
Where _rotateAroundPoint is the point around which _background should turn in it's own coordinate space, and _centerOnPoint is the point around which it should turn in its parent's coordinate space.
Both of those values only need to be recalculated when you want to pan _background, rather than every frame. For example:
private var _rotateAroundPoint:Point = new Point(_background.width * 0.5, _background.height * 0.5);
private var _centerOnPoint:Point = new Point(50, 50);
private function renderPage(e:Event) {
var matrix:Matrix = new Matrix();
matrix.translate(-_rotateAroundPoint.x, -_rotateAroundPoint.y);
matrix.rotate((currentRotation / 180) * Math.PI);
matrix.scale(currentScaleX, currentScaleY);
matrix.translate(_centerOnPoint.x, _centerOnPoint.y);
_background.transform.matrix = matrix;
}