Unity: Calculate angular velocity of rigidbody to always face specific direction - unity3d

I'm trying to make a pick up objects mechanic like the one in Amnesia. It's easy to calculate needed rigidbody's velocity, so that the held object stays in front of camera, but my problem is that the object doesn't rotate at all when I hold it. And I would rather have it always be rotated towards the camera. This could easily be achieved with simply parenting the object to player's camera, but...
The behaviour I'm after is as follows: if the bottle I picked up was standing on a table, with neck of the bottle facing ceiling, I would like to see this bottle always with its neck facing ceiling while I hold it. But if this bottle collides with something, it should behave like it actually bumped onto something, so it should rotate some small amount, but it should always try to return to its "original" rotation (in this case, neck facing ceiling).
I think that I need to calculate angular velocity for that and probably have some lerp to return to original rotation, but I'm at a loss on how to do that properly.
I think that the first thing I would need to do is to store the initial direction the moment player picks object up:
Vector3 targetDirection = playerCamera.transform.position - transform.position;
Script is on the held object, so "transform" refers to it. In FixedUpdate() I probably need to have some interpolation, so that angular velocity always tries to rotate the object to original rotation:
rigidbody.angularVelocity = Vector3.Lerp(rigidbody.angularVelocity, targetAngularVelocity, lerpSpeed * Time.fixedDeltaTime);
I don't know how to calculate targetAngularVelocity, because after all I would like the held object to return to original rotation smoothly. I'm not even sure if that's the right way to do this thing and perhaps I should do something else than to calculate angular velocity needed to rotate object properly. I tried just interpolating localRotation to original local rotation, but that did not allow the held object to bump on stuff (the movement then was very jittery). Any ideas?

You need a stabilizer. A script which will add torque/angular velocity to the object, whose angle is different from the target one. Say, you have two variables: targetDirection and currentDirection aka transform.forward. Then you write something like this in fixed update:
var rotation = Quaternion.FromToRotation(currentDirection, targetDirection).eulerAngles * sensitivity;
rigidbody.angularVelocity = rotation;
I recommend to set sensitivity about 0.05 and then increase it if the object stabilizes too slow.
Probably I confused the order, so you should put minus somewhere, but the approach itself is applicable.

Related

apply a rotation relative to any reference space - Unity

is there a way to apply a rotation for any arbitrarily orientation (Object A's rotation relative to Object B's local orientation)
I know I can simply get desired result if i do setParent thing, but i want to get without it
In my situation, my character holds water bottle and moves around the room holding it so I set its rotation like this
transform.rotation = mainCamera.transform.rotation;
but As bottle top pointing to the sky seems more natural, I want it to rotate 90 degree by its own X-axis
I tried below codes but it dosent work as i intended
`originalRotation = transform.rotation;
Quaternion rotationDelta = Quaternion.FromToRotation(Vector3.forward, mainCamera.transform.forward);
transform.rotation = rotationDelta * originalRotation;`
Yes, Like i said above if i make my character parent to the bottle will solve the issue, but i want to
do it without it.
Thank you
Try this one:
transform.forward = mainCamera.transform.up;

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);

Best way to move a game object in Unity 3D

I'm going through a few different Unity tutorials and the way a game object is moved around in each is a little different.
What are the pros/cons to each of these methods and which is preferred for a first person RPG?
// Here I use MovePosition function on the rigid body of this component
Rigidbody.MovePosition(m_Rigidbody.position + movement);
//Here I apply force to the rigid body and am able to choose force mode
Rigidbody.AddForce(15 * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
// Here I directly change a transforms position value, in this case the cam
Transform.transform.position = playerTransform.position + cameraOffset;
Thanks!!
EDIT;
Something I have noticed is that the applied force seems to memic wheeled vehicles while the position changes memic walking/running.
RigidBodies and Velocities/Physics
The only time, I personally have used the rigidbodys system was when implementing my own boids (flocking behaviour) as you need to calculate a few separate vectors and apply them all to the unit.
Rigidbody.MovePosition(m_Rigidbody.position + movement);
This calculates a movement vector towards a target for you using the physics system, so the object's velocity and movement can still be affected by drag, angular drag and so on.
This particular function is a wrapper around Rigidbody.AddForce I believe.
Pros :
Good if realistic physical reactions is something you are going for
Cons:
A bit unwieldy to use if all you are trying to achieve is moving a object from point A to point B.
Sometimes an errant setting set too high somewhere (for example: Mass > 10000000) can cause really screwy bugs in behaviour that can be quite a pain to pin down and mitigate.
Notes: Rigidbodies when colliding with another Rigidbody would bounce from each other depending on physics settings.
They are also affected by gravity. Basically they try to mimic real life objects but it can be sometimes difficult to tame the objects and make them do exactly what you want.
And Rigidbody.AddForce is basically the same as above except you calculate the vector yourself.
So for example to get a vector towards a target you would do
Vector3 target = target.position - myPosition;
Rigidbody.AddForce(target * 15 * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
If you don't plan on having any major physics mechanics in your game, I would suggest moving by interpolating the objects position.
As it is far easier to get things to behave how you want, unless of course you are going for physical realism!
Interpolating the units position
Pros :
Perhaps a little strange to understand at first but far simpler to make objects move how you want
Cons:
If you wanted realistic reactions to objects impacting you'd have to do a lot of the work yourself. But sometimes this is preferable to using a physics system then trying, as I've said earlier to tame it.
You would use the technique in say a Pokemon game, you don't stop in Pokemon and wait for ash to stop skidding or hit a wall and bounce uncontrollably backwards.
This particular function is setting the objects position like teleporting but you can also use this to move the character smoothly to a position. I suggest looking up 'tweens' for smoothly interpolating between variables.
//change the characters x by + 1 every tick,
Transform.transform.position.x += 1f;
Rigidbody.MovePosition(m_Rigidbody.position + movement);
From the docs:
If Rigidbody interpolation is enabled on the Rigidbody, calling Rigidbody.MovePosition results in a smooth transition between the two positions in any intermediate frames rendered. This should be used if you want to continuously move a rigidbody in each FixedUpdate.
https://docs.unity3d.com/ScriptReference/Rigidbody.MovePosition.html
Rigidbody.AddForce(15 * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
This will make the object accelerate, so it won't travel at a constant velocity (this is because of Newton's second law, Force=mass*acceleration). Also if you have another force going in the opposite direction this force could get cancelled out and the object won't move at all.
Transform.transform.position = playerTransform.position + cameraOffset;
This will teleport the object. No smooth transition, no interaction with any forces already in the game, just an instant change in position.

Rigidbody Velocity Messing Up Physics UNITY

I am trying to move my player by using rigidbody.velocity:
rigidbod.velocity = new Vector2 (Input.GetAxis ("Horizontal") * maxSpeed, rigidbod.velocity.y);
the problem is, this messes up of my explosion code. The character is supposed to be knocked back when near an explosion. I know why it happens; if the player is still, the rigidbody's X velocity would be returned as 0, meaning any outside forces pushing the player along the X axis would counteract this. So when I add the explosion, the player cuts to his new position a few units away. It looks very unnatural and jerky, as he should be pushed back, but his code is telling him to be still unless a key is pressed. I'm posting this to see if there's any way I can re-write this code to be able to move the player while being pushed correctly from outside forces. I heard that AddForce works, but when I used it, my player's velocity constantly increased. He is wither way too fast or way too slow. Any ideas on how I can get this to work? I tried adding rigidbody.velocity.x after where it says 'maxspeed' hoping that it would allow outside force input, and it works, but it messes up the movement code, making him go way too fast. I can't seem to get both the explosions and the movement code to work correctly at the same time. Any help would be greatly appreciated. Thanks.
which is exactly why in the Unity docs they explicitly state:
In most cases you should not modify the velocity directly, as this can
result in unrealistic behaviour.
instead of modifying the velocity directly, you should be using an AddForce(..)
Vector2 force = new Vector2 (Input.GetAxis ("Horizontal") * maxSpeed, 0f);
rigidbody.AddForce(force);
//or if in update:
rigidbody.AddForce(force * Time.deltaTime);

Get simplified rotation of object

In my game, Im always rotating a gameobject (Cube) with Quaternion.Lerp. And I need which face of this cube is looking up. So I think I can use current rotation of object to get this (if there is a better way please say it).
Firstly this gameobject's rotation (0,0,0). when I rotate it forward it becomes (90,0,0). There is no problem. But after that, when I rotate it second time it doesnt become (180,0,0). it is (0,180,180). How can I prevent unity to do this.
Try using euler angles instead of quaternions, they are much simpler, here is an example:
transform.eulerAngles = new Vector3(180, 0, 0);
There are multiple ways of representing a rotation with Euler angles. When you convert the rotation of your GameObject (stored internally as a quaternion) to Euler angles (using either transform.eulerAngles or transform.rotation.eulerAngles) you may not get the result you're expecting.
You could get around this by storing a Vector3 (let's call it currentRotation) containing the rotation of your object in Euler angles, and construct Quaternions from it using Quaternion.Euler(currentRotation). You can do your interpolation by calculating your target rotation (targetRotation) as a Vector3, then constructing a Quaternion for it before doing Quaternion.Lerp:
var targetRotationQuaternion = Quaternion.Euler(targetRotation);
var currentRotationQuaternion = Quaternion.Euler(currentRotation);
transform.rotation = Quaternion.Lerp(currentRotationQuaternion, targetRotationQuaternion, *your t*);
Incidentally, this answer is very similar to a comment on http://answers.unity3d.com/questions/667037/transformrotationeulerangles-not-accuarate.html but it's worth reproducing here in case that ever gets taken down.