Move Cannon.JS Body Toward Dynamic Position? - cannon.js

I'm having a hard time wrapping my head around how to do this.
What I'm trying to do, is move a physics body, by the means of velocity, toward another body, until it reaches and hits said body. (Think AI following a player)
One solution is the following:
body.velocity.x = target.position.x-body.position.x;
body.velocity.z = target.position.z-body.position.z;
This has issues, though. One being that the velocity is higher depending on the distance between the two bodies. I would prefer a fixed speed. Another way would be to use the following example: Position a body in cannon.js relative to local rotation
But in this case, I need a way of rotating the quaternion, so it faces the target position, this with only knowing the 2 positions of the bodies.
So the question is, how do I calculate the velocity OR direction of the body, so that it can follow and collide with the target body, by using a fixed speed/velocity?

To get a fixed speed, .normalize() your velocity vector and then scale (.mult()) the result by the speed you want. The result will be a vector that always has the length you want.
To get a quaternion that makes your body face in a certain direction, you can use Quaternion.setFromVectors(u,v). This method creates a quaternion which will rotate u so it points in the same direction as v. If you set u to your forward vector and v to the direction you want the body to look, you will get the correct "look at" behavior. Note that the "forward" vector might be different for your game.
// Compute direction to target
var direction = new CANNON.Vec3();
target.position.vsub(body.position, direction);
direction.y = 0;
direction.normalize();
// Get the rotation between the forward vector and the direction vector
var forward = new CANNON.Vec3(0,0,1);
body.quaternion.setFromVectors(forward, direction);
// Multiply direction by 10 and store in body.velocity
var fixedSpeed = 10;
direction.mult(fixedSpeed,body.velocity);

Related

Determine the direction an object is actually moving

In unity I am trying to compare the players actual direction with the direction they are facing and wish to move in but having major issues trying to find the actual movement direction.
I can determine the facing direction very easily with:
wishDir = transform.localEulerAngles;
But I cannot figure out how to get the objects movement direction so that I can compare. I have tried:
transform.InverseTransformDirection(rb.velocity);
I would expect this to be equal to 0,90,0 when I move to the right however it is equal to 0,0,0 (although jumps when there is acceleration).
How can I determine the direction an object is moving in?
I can determine the facing direction very easily with:
wishDir = transform.localEulerAngles;
This is already quite odd to me. localEulerAngles is a rotation in Euler space notation in degrees per axis x,y,z .. this is no "direction".
Usually if you want the direction you are looking in you would rather use transform.forward
wishDir = transform.forward;
And then
transform.InverseTransformDirection(rb.velocity);
should indeed return the direction in local space.
Note that the Debug.Log beautifies (rounds) this value to make it more human readable. If you want the exact values you could try and log e.g.
var relative = transform.InverseTransformDirection(rb.velocity);
Debug.Log(relative.ToString(F4));
which should print the values always with 4 digits after the decimal point.

Which rotation is shown in the Inspector?

The chest bone of my player can be rotated while aiming.
Now I wanted to evaluate how much (minimum and maximum rotation) I should let the chest be rotatable.
To do that, I allowed all degrees of rotation and took a look at the Inspector.
For example, the minimum value that the chest should be rotatable to the left should be Y=-15.
At Y=-15 (seen in the Inspector), it still looked natural.
Now I wanted to code this.
To my surprise, chest.localRotation.Y was a completely different value than what the Inspector is showing.
I have then taken a look at the chest variable and extended the view.
I just can't see the rotation value that the Inspector is showing.
How should I go on in this case, please?
I'm using this to rotate the bone:
Chest.LookAt(ChestLookTarget.position);
Chest.rotation = Chest.rotation * Quaternion.Euler(Offset);
Thank you!
The reason why it doesn't work:
Quaternion is not a human readable value.
One Quaternion is allways unique but can have multiple (infinite?) different representations in Euler space! The other way round one Euler represents allways exactly one Quaternion value.
If you look at the docs it explicitly says
Don't modify this directly unless you know quaternions inside out.
Than as said what you see in the inspector is the localRotation in relation to the parent Transform.
Better said it is one of the many possible Euler inputs that result in the Quaternion. What you see in the debug at localEulerAngles is another possible Euler representation. Unity usually in localEulerAngles also gives you only values > 0.
It seems that the chest anyway will only rotate around the Y axis, right?
If this is the case you can simply get the Angle between the chest's original forward vector and the target. It is way easier to handle Vector3 values than Quaternions ;)
It seems to be the same use case as in this post
// get the target direction
Vector3 targetDir = ChestLookTarget.position - Chest.position;
// Reset any difference in the Y axis
// since it would change the angle as well if there was a difference I the height
// between the two objects
targetDir.y = 0;
// however you currently rotate
// instead rotate only the Vector3 variable without applying it to the transform yet
Vector3 newDir = Vector3.RotateTowards(Chest.forward, targetDir, RotationSpeed * Time.deltaTime, 0.0f);
// Compare the target direction to the parents forward vector
float newAngle = Vector3.Angle(Chest.parent.transform.forward, newDir);
if (newAngle > MaxRotationAngle)
{
// What should happen if angle gets bigger?
return;
}
// If angle still okey set the new direction
Chest.rotation = Quaternion.LookRotation(newDir);

Why am I getting an incorrect vector when trying to find HingeJoint2D.anchor in world space?

In the scene, I have a long chain of children that are connected via hinge to their parent. For my code, I need the position of the hinge anchors in world space, so I use:
public Vector2 hingeVector => hinge.anchor + (Vector2)gameObject.transform.position;
For the first hinge, that code gives the correct position. But for the second hinge this happens:
The red point is the vector I get, the blue point is the actual position. As you can see, it's a somewhat small but still problematic difference.
Is there any way I can fix this? I couldn't find anything like this online.
You need to add the object's rotation
The anchor values are axis aligned and aren't affected by rotation, but in order to calculate the anchor point in world space, knowing the transform's position, you need to rotate the anchor point values by the object's rotation then add it to the position:
Vector2 p = hinge.anchor.Rotate(gameObject.transform.rotation.eulerAngles.z)
+ (Vector2)gameObject.transform.position;

Unity3D - Relative position on y-axis independent of rotation?

I have an object (A) with another object (B) next to it. I am trying to calculate the "height" of object B, so that i can position another object at that height relative to the position of object A. I know this sounds like gibberish (i'm a bit tired) so i have put diagrams to try and explain.
So in the left image the yellow line represents what i am trying to calculate. I have an position (orange) on the surface of a cylinder (grey) (calculated position using mesh data) which i am trying to use to calculate the radius of the object (black line). To do this i need a position at the center of the object (grey) at the same height (red dot) so i can calculate the direction from one to the other and use the length (.magnitude) as the radius.
My problem is i can't work out, how i can calculate the height (yellow line) without rotation having any effect.
I currently use projectOnPlane however if i rotate the object as seen in the second image, the radius decreases significantly when it should be consistent as the object is not changing size.
Vector3 RadDirection = (Vector3.ProjectOnPlane(orangePoint, grey.transform.up) - Vector3.ProjectOnPlane(grey.transform.position, grey.transform.up));
float radius = RadDirection.magnitude;
Any help would be much appreciated, thanks.
**UPDATE: The grey block in the diagram is a vector3 position rather than a game object. The radius calculation i am trying to do happens during runtime so i can't parent an object to the grey and review the inspector.
**UPDATE 2: Sorry, something i should have mentioned. The object i'm doing this on will not always be a perfect cylinder, it could be something such as a wine glass, where i need to calculate the radius of the glass not the stem. Another example could be a chemistry beaker which normally tapers to a point, so i would need to calculate the radius at the height of the orange point. Sorry i should have put that in the question.
Here's a diagram to illustrate what i mean in update 2. Again the orange dot is acting as a visual representation of a Vector3 position on the surface of the object's (in this case a beaker) mesh.
**Update 3: I appear to have solved the issue and so i have posted my answer below but at the time of writing i can't accept it (have to wait 2 days) and so cant close/answer the question. I would like to thank everyone that contributed and tried to help me solve this problem. I hope i can help you all someday :)
You can use transform.TransformDirection() or transform.InverseTransformDirection()
To get the height take the result of the subtraction and set the X, Z coordinate to zero:
Vector3 height = orangeBox.position - greenPoint.position;
height.x = 0;
height.z = 0;
Complete solution:
Vector3 direction = orangeBox.position - greenPoint.position;
direction = greyBox.transform.InverseTransformDirection(direction);
direction.x = 0;
direction.z = 0;
height = direction.magnitude;
redPoint.position = greenPoint.position + greyBox.transform.up * height;
I appear to have solved my problem using the following:
public static Vector3 ProjectPointOnLine(Vector3 linePoint, Vector3 lineVec, Vector3 point)
{
//get vector from point on line to point in space
Vector3 linePointToPoint = point - linePoint;
float t = Vector3.Dot(linePointToPoint, lineVec);
return linePoint + lineVec * t;
}
I found this here, it has lot's of other useful looking functions:
http://wiki.unity3d.com/index.php/3d_Math_functions
I basically pass in the origin of the beaker (green point) as the "linePoint", the upwards direction of the beaker "lineVec" with beaker.transform.up and finally i pass in the world vector3 point on the surface of the beaker mesh (orange point) it returns back a point in the middle of the beaker at the same height as my orange dot. I then just subtract the one from the other and take the magnitude as the radius. The radius value calculated is correct in that's it the value i was expecting and only changes after the sixth decimal place during rotation which gives plenty of accuracy as i only need three or four decimal places.
I'm happy to provide further details or help if anyone else needs help doing this.

How to make Gravity for multiple planets in Unity3d

What i'm looking to do is something similar to our solar system, where you are gravitically drawn to one planet till you leave it's pull, and then once you're on another planet be drawn to that gravity.
I have found many entries online about how to create gravity for a single planet, but none i've found work for multiple sources.
Any help would be GREATLY appreciated.
Projects I've already looked at were mainly for single planet gravity.
unity 3.3, create local gravity on object
http://answers.unity3d.com/questions/13639/how-do-i-make-a-small-planet-with-gravitational-pu.html
http://answers.unity3d.com/questions/701618/how-could-i-simulate-planetary-gravity-that-has-an.html
This could be done easily by adding a normal force relative to the planet on the surrounding objects.
According to physics of Universal gravitational force you can calculate the gravitational force. Then calculated the normal force at the moment and add the force.
void FixedUpdate(){
// Do the Force calculation (refer universal gravitation for more info)
// Use numbers to adjust force, distance will be changing over time!
forceSun = G x (massPlanet x massSun)/d^2;
// Find the Normal direction
Vector3 normalDirectionSun = (planet.position - sun.position).normalized;
// calculate the force on the object from the planet
Vector3 normalForceSun = normalDirection * forceSun;
// Calculate for the other systems on your solar system similarly
// Apply all these forces on current planet's rigidbody
// Apply the force on the rigid body of the surrounding object/s
rigidbody.AddForce(normalForceSun);
// .... add forces of other objects.
}
With various m1, m2 values you will be able to make the system more realistic. As an example make the object move/accelerate towards the planets with higher mass.