Questions in topic: "gimbal-lock"
http://answers.unity.com/questions/topics/single/7166.html
The latest questions for the topic "gimbal-lock"How can I display euler angles 0-360 without triggering gimbal lock/ flipping values?
http://answers.unity.com/questions/1590733/how-can-i-display-euler-angles-0-360-without-trigg.html
I found that solution but it's not working. When I rotatate object around one axis,sometiomes script modify two values.
public static Vector3 ConvertQuant2Euler(Quaternion quaternion)
{
float tempEuler;
float[] eulerAngles = new float[3];
float[] fixedEulerAngles = new float[3];
//Convert pitch - X
tempEuler = Mathf.Atan2(2 * quaternion.x * quaternion.w + 2 * quaternion.y * quaternion.z, 1 - 2 * quaternion.x * quaternion.x - 2 * quaternion.z * quaternion.z);
eulerAngles[0] = tempEuler * 180 / Mathf.PI;
if (eulerAngles[0] < 0)
{
fixedEulerAngles[0] = 180 + (180 + eulerAngles[0]);
}
if (eulerAngles[0] > 0)
{
fixedEulerAngles[0] = eulerAngles[0];
}
//Convert yaw - Y
tempEuler = Mathf.Asin(2 * quaternion.x * quaternion.y + 2 * quaternion.z * quaternion.w);
eulerAngles[1] = tempEuler * 180 / Mathf.PI;
if (eulerAngles[1] < 0)
{
fixedEulerAngles[1] = 180 + (180 + eulerAngles[1]);
}
if (eulerAngles[1] > 0)
{
fixedEulerAngles[1] = eulerAngles[1];
}
//Convert roll - Z
tempEuler = Mathf.Atan2(2 * quaternion.y * quaternion.w + 2 * quaternion.x * quaternion.z, 1 - 2 * quaternion.y * quaternion.y - 2 * quaternion.z * quaternion.z);
eulerAngles[2] = tempEuler * 180 / Mathf.PI;
if (eulerAngles[2] < 0)
{
fixedEulerAngles[2] = 180 + (180 + eulerAngles[2]);
}
if (eulerAngles[2] > 0)
{
fixedEulerAngles[2] = eulerAngles[2];
}
return new Vector3(fixedEulerAngles[0], fixedEulerAngles[1], fixedEulerAngles[2]);
}euleranglesgimbal-lockWed, 16 Jan 2019 11:50:34 GMTCDAXRCRotation sync over network on dedicated server
http://answers.unity.com/questions/1578287/rotation-sync-over-network-on-dedicated-server.html
This was probably asked a dozen of times, but I can't seem to find the answer anywhere.
I have a dedicated server for a space game written in C# console application. The problems that I'm facing is the synchronisation of GameObject rotations. I'm suspecting the issue being related to gimbal lock, but I am not sure.
Here I have my player movement/rotation controller:
public class PlayerMovement : MonoBehaviour {
[SerializeField] float maxSpeed = 40f;
[SerializeField] float shipRotationSpeed = 60f;
Transform characterTransform;
void Awake()
{
characterTransform = transform;
}
void Update()
{
Turn();
Thrust();
}
float Speed() {
return maxSpeed;
}
void Turn() {
float rotX = shipRotationSpeed * Time.deltaTime * CrossPlatformInputManager.GetAxis("Vertical");
float rotY = shipRotationSpeed * Time.deltaTime * CrossPlatformInputManager.GetAxis("Horizontal");
characterTransform.Rotate(-rotX, rotY, 0);
}
void Thrust() {
if (CrossPlatformInputManager.GetAxis("Move") > 0) {
characterTransform.position += shipTransform.forward * Speed() * Time.deltaTime * CrossPlatformInputManager.GetAxis("Move");
}
}
}
This script is applied to my character object which is a ship. Note that the character object has a child object which is the ship itself and has fixed rotation and position that do not change. When character has moved/rotated I send the following to the server: position(x, y, z) and rotation(x, y, z, w).
Now here is the actual script that receives network packet information and updates the other players in game:
public class CharacterObject : MonoBehaviour {
[SerializeField] GameObject shipModel;
public int guid;
public int characterId;
public string name;
public int shipId;
Vector3 realPosition;
Quaternion realRotation;
public void Awake() {
}
public int Guid { get { return guid; } }
public int CharacterId { get { return characterId; } }
void Start () {
realPosition = transform.position;
realRotation = transform.rotation;
}
void Update () {
// Do nothing
}
internal void LoadCharacter(SNCharacterUpdatePacket cuPacket) {
guid = cuPacket.CharacterGuid;
characterId = cuPacket.CharacterId;
name = cuPacket.CharacterName;
shipId = cuPacket.ShipId;
realPosition = new Vector3(cuPacket.ShipPosX, cuPacket.ShipPosY, cuPacket.ShipPosZ);
realRotation = new Quaternion(cuPacket.ShipRotX, cuPacket.ShipRotY, cuPacket.ShipRotZ, cuPacket.ShipRotW);
UpdateTransform();
Instantiate(Resources.Load("Ships/Ship1/Ship1"), shipModel.transform);
}
internal void UpdateCharacter(SNCharacterUpdatePacket cuPacket) {
realPosition = new Vector3(cuPacket.ShipPosX, cuPacket.ShipPosY, cuPacket.ShipPosZ);
realRotation = new Quaternion(cuPacket.ShipRotX, cuPacket.ShipRotY, cuPacket.ShipRotZ, cuPacket.ShipRotW);
UpdateTransform();
}
void UpdateTransform() {
transform.position = Vector3.Lerp(transform.position, realPosition, 0.1f);
transform.rotation = Quaternion.Lerp(transform.rotation, realRotation, 0.5f);
}
}
Do you see anything wrong with the code ?
My experience with 2 players in game is the following:
When I start the game with two players they spawn at the same location (0,0,0) and same rotation (0,0,0).
Lets say that The other player is rotating continuously around the X-axis only. What I am experiencing is:
1. First 90 deg. of rotation it renders fine.
2. Next 180 deg. of rotation the object stays in place
3. The last 90 deg. of rotation renders fine
In the first version I did not send the 'w' value of Quaternion, but then added it in the second version and it did not help. Note that there is no restrictions in rotation and users can rotate endlessly in all directions.
Btw the positioning works fine.
I might not understand Quaternions fully, but I thought that they had a purpose in avoiding the gimbal lock issue.
Any help would be appreciated.rotationnetworkinggimbal-lockdedicated-serverThu, 06 Dec 2018 08:53:37 GMTBoki83Quaternion rotation flips axises when upside down
http://answers.unity.com/questions/1573212/quaternion-rotation-flips-axises-when-upside-down.html
I suspect this is called a gimbal lock but I can't really find how to solve it. I basically want my character to be able to walk around a ramp. Gravity is applied to the characters negative up vector.
The player velocity is calculated and "stored" in a variable in world space. This should be translated / rotated towards the models local space to be able for it to move around, wether it's on a wall or ceiling.
When the player walks against something it get's rotated towards the hitting plane (it's still an early piece of code) and should move further. This works until the character wants to be upside down. I suspect gimbal lock is happening at that point, where the axis is either turning around (you can't actually walk the ceiling in this case since it goes back and forth);
var moveDirection = transform.TransformDirection(PlayerVelocity.normalized);
moveDirection = rot * PlayerVelocity;
transform.Translate(moveDirection * Time.deltaTime, Space.World);
or it basically flips it's axis where the forward kind of turns around;
var angle = Vector3.SignedAngle(Vector3.up, transform.up, transform.forward);
Quaternion rot = Quaternion.AngleAxis(angle, transform.forward);
moveDirection = rot * PlayerVelocity;
transform.Translate(moveDirection * Time.deltaTime, Space.World);
also not using quaternions and doing transform.translate in space.self gives the same problem as the first piece of code. What am I doing wrong here, can anyone advice me on what to do? I found sites like https://answers.unity.com/questions/284018/rigidbody-rotation-problem-when-upside-down.html and https://www.reddit.com/r/Unity3D/comments/2f81g6/quaternion_rotations_character_is_flipping_over/#ampf=undefined but they didn't offer me a solution, unless I implemented it wrong.rotationquaterniongimbal-lockMon, 19 Nov 2018 18:52:15 GMTSjiggle[SOLVED]aligning rigidbody to be "level" with world's X and Z coords. How can I make sure it faces the same way (Y coord)?
http://answers.unity.com/questions/1539912/im-aligning-a-rigidbody-to-be-level-with-the-world.html
So basically, my aircraft is flying. Once the player glides for a little bit, if their craft is not level, this code runs to "level" them back out, so their X and Z are closer to 0.
However, when this code runs, my Y ends up being much different, for example the aircraft will be going south but the correction, while doing ultimately what I need (leveling X / Z) , ends up with the plane facing east or a completely different direction.
I was considering, manually doing it first on the Z axis, and when that is done, manually doing it on the X axis.
But reading around, and playing around with it, I'm concerned about gimbal lock affecting me such that, where my code might expect a value between 0-360, in reality (at least in the inspector) that number can keep going well beyond 360?
What is a good way to improve this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PhysicsFlyer : MonoBehaviour {
public float AmbientSpeed = 100.0f;
public float RotationSpeed = 100.0f;
Rigidbody rb;
public bool needCorrecting;
public bool corrected = true;
[Header("Movement Input.")]
public float pitch;
public float yaw;
public float roll;
public float inputTimeout = 2f;
float itimer;
public bool havePushed;
public bool isLevel;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody> ();
itimer = inputTimeout;
}
public float stability = 1f;
// public float speed = 2.0f;
// Update is called once per frame
void Update(){
if (Input.anyKey) {
havePushed = true;
corrected = false;
} else {
itimer -= .1f;
if (itimer <= 0f) {
itimer = inputTimeout;
havePushed = false;
}
}
if (Mathf.Abs (transform.rotation.eulerAngles.x) <= 15f) {
if (Mathf.Abs (transform.rotation.eulerAngles.z) <= 15f) {
print ("We are level");
isLevel = true;
} else {
isLevel = false;
}
} else {
isLevel = false;
}
if (!isLevel && !havePushed) {
if(!corrected)
needCorrecting = true;
} else {
needCorrecting = false;
}
}
void FixedUpdate () {
Quaternion AddRot = Quaternion.identity;
Vector3 torqueVector = Vector3.zero;
if (needCorrecting) {
Vector3 predictedUp = Quaternion.AngleAxis (
rb.angularVelocity.magnitude * Mathf.Rad2Deg * stability / 2f,
rb.angularVelocity
) * transform.up;
torqueVector = Vector3.Cross (predictedUp, Vector3.up);
torqueVector = new Vector3 (torqueVector.x, 0f, torqueVector.z);
print ("Correcting");
corrected = true;
}
float roll = 0;
float pitch = 0;
float yaw = 0;
roll = Input.GetAxis("Roll") * (Time.fixedDeltaTime * RotationSpeed);
pitch = Input.GetAxis("Vertical") * (Time.fixedDeltaTime * RotationSpeed);
yaw = Input.GetAxis("Horizontal") * (Time.fixedDeltaTime * RotationSpeed);
AddRot.eulerAngles += new Vector3(pitch, yaw, -roll);
if(corrected && needCorrecting)
AddRot.eulerAngles += torqueVector * 2f;
rb.rotation *= AddRot;
Vector3 AddPos = Vector3.forward;
AddPos = rb.rotation * AddPos;
rb.velocity = AddPos * (Time.fixedDeltaTime * AmbientSpeed);
}
}
Please,feel free to throw this script on a primitive shape like a cube with a rigidbody to see what I mean
Edit: Solution was to replace lines 95-105 with this code I found online from like 10 years ago and combining it with my last attempted solution:
levelPoint.transform.position = new Vector3(frontPoint.transform.position.x,rearPoint.transform.position.y,frontPoint.transform.position.z);
/*Where "frontPoint" is a gameobject at the front the craft, and "rearPoint" is at the rear, where typically we are pivoting around in my scenario....This way "levelPoint" is always globally in "front and level" to/of the craft.*/
var qTo = Quaternion.LookRotation(levelPoint.transform.position - transform.position);
qTo = Quaternion.Slerp(transform.rotation, qTo, 2f * Time.deltaTime);
rb.MoveRotation(qTo);
I don't understand the math, at least consciously, but it is doing exactly what I need it to. Hope this code helps someone but not too much because this is my pay dirt lol.rigidbodyquaternionmatheuleranglesgimbal-lockWed, 08 Aug 2018 15:30:53 GMTThomas-Hawkmultiplying gyro output
http://answers.unity.com/questions/1527792/multiplying-gyro-output.html
All i need is gyro input in, multiply by modifier then move camera by the result. Surely this must be possible although i can't find a single example of it. Should be really really simple but i just can't make it work ( also eulers don't work as gimbal lock breaks them)
i.e. so if i move the phone 45 degrees the camera moves 90 degrees.quaternioncamera rotategyroscopegimbal-lockTue, 10 Jul 2018 20:26:00 GMTforferdeilighow do i take gyro rotation and multiply it?
http://answers.unity.com/questions/1527786/how-do-i-take-gyro-rotation-and-multiply-it.html
All i need is gyro input in, multiply by modifier then move camera by the result. Surely this must be possible although i can't find a single example of it. Should be really really simple but i just can't make it work ( also eulers don't work as gimbal lock breaks them)
i.e. so if i move the phone 45 degrees the camera moves 90 degrees.c#camerarotationquaterniongimbal-lockTue, 10 Jul 2018 20:15:55 GMTforferdeiligGimbal Lock Problem
http://answers.unity.com/questions/1476791/gimbal-lock-problem-1.html
Hello everyone, I have this problem with Quaternions, I tried to pass the rotation of some objects to the rotation of one object, but at some angles I get the Gimbal Lock problem, like when the X rotation is 90, the Y rotation rotates on the Z axis, this is the code:
switch (axis)
{
case Axis.X:
switch (typeOfEditing)
{
case EditType.Rotation:
if (oldRotAxis != transform.localEulerAngles.x)
{
newRotAxis = transform.localEulerAngles.x - oldRotAxis;
objToMove.localRotation = Quaternion.AngleAxis(newRotAxis, Vector3.right) * objToMove.localRotation;
follower.localRotation = Quaternion.Euler(newRot);
oldRotAxis = transform.localEulerAngles.x;
}
break;
}
break;
case Axis.Z:
switch (typeOfEditing)
{
case EditType.Rotation:
if (oldRotAxis != -transform.localEulerAngles.x)
{
newRotAxis = -transform.localEulerAngles.x + oldRotAxis;
objToMove.localRotation = Quaternion.AngleAxis(newRotAxis, Vector3.forward) * objToMove.localRotation;
follower.localRotation = Quaternion.Euler(newRot);
oldRotAxis = -transform.localEulerAngles.x;
}
break;
}
break;
case Axis.Y:
switch (typeOfEditing)
{
case EditType.Rotation:
if (oldRotAxis != transform.localEulerAngles.y)
{
newRotAxis = transform.localEulerAngles.y - oldRotAxis;
objToMove.localRotation = Quaternion.AngleAxis(newRotAxis, Vector3.up) * objToMove.localRotation;
follower.localRotation = Quaternion.Euler(newRot);
oldRotAxis = transform.localEulerAngles.y;
}
break;
}
break;
}
Is there a method, to apply a rotation to each axis and evading the Gimbal Lock? I have tried also the Quaternion.Euler but gives me the same results.quaternionrotation axisquaternionsgimbal-lockangleaxisMon, 05 Mar 2018 18:17:06 GMThectoralesCamera Bounce when Orbiting too Qucikly
http://answers.unity.com/questions/1465967/camera-bounce-when-orbiting-too-qucikly.html
Hi All, I have this issue that when I orbit too quickly the camera some how bonces as if gimbal lock. However when I Orbit slowly this doesn't happen.
Has anyone come across this issue? If so how did you manage to work around it?
Please see the link below, which illustrates the issue I am referring to.
https://youtu.be/Vec31SJe-5Qcamerarotationorbitgimbal-lockThu, 08 Feb 2018 16:52:39 GMTShanmf3dC# 360 Orbital Camera Controller (Gimbal Lock Issue)
http://answers.unity.com/questions/1464747/c-360-orbital-camera-controller-gimbal-lock-issue.html
I have a stationary cube in my scene that I'm orbiting a camera around. I have my MainCamera nested under a GameObject that I'm calling 'OrbitalCamera'.
I setup the script so that a click (or tap) and drag will rotate the camera around the object in space so it feels like you're rotating the cube (ie: if I click the top of a face on the cube, and pull down, I'm rotating the X value) but you'll actually be rotating the camera.
For the most part, my script works. However, after rotating the Y so much, the camera is upside down and the X gets inverted. Here's my (updated) script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OrbitalCamera : MonoBehaviour {
public bool cameraEnabled;
[SerializeField] private float touchSensitivity = 5f;
[SerializeField] private float orbitDampening = 10f;
protected Transform xFormCamera;
protected Transform xFormParent;
protected Vector3 localRotation;
protected float cameraDistance;
void Start () {
cameraEnabled = true;
xFormCamera = transform;
xFormParent = transform.parent;
cameraDistance = transform.position.z * -1;
}
void LateUpdate () {
if (cameraEnabled) {
if (Input.GetMouseButton(0)) {
if (Input.GetAxis("Mouse X") != 0 || Input.GetAxis("Mouse Y") != 0) {
localRotation.x += Input.GetAxis("Mouse X") * touchSensitivity;
localRotation.y -= Input.GetAxis("Mouse Y") * touchSensitivity;
}
}
}
// TODO:: FIX CAMERA ROTATION / GIMBAL LOCK ISSUE
Quaternion yaw = Quaternion.AngleAxis(localRotation.x, transform.up);
Quaternion pitch = Quaternion.AngleAxis(localRotation.y, transform.right);
//Quaternion qt = Quaternion.Euler(localRotation.y, localRotation.x, 0);
// NOTE:: ROTATING PITCH AND YAW SEPARATELY WORK FLAWLESSLY, BUT ROTATION SHOULD HAPPEN TOGETHER
//xFormParent.rotation = Quaternion.Slerp(xFormParent.rotation, pitch, Time.deltaTime * orbitDampening);
//xFormParent.rotation = Quaternion.Slerp(xFormParent.rotation, yaw, Time.deltaTime * orbitDampening);
// NOTE:: MULTIPLYING PITCH AND YAW STILL PRODUCES GIMBAL LOCK AND CAMERA SPINS INFINITELY AT CERTAIN ANGLES
xFormParent.rotation = Quaternion.Slerp(xFormParent.rotation, pitch * yaw, Time.deltaTime * orbitDampening);
// NOTE:: USING QUATERNION EULERS GENERATES A GIMBAL LOCK AND CAMERA DOES NOT SPIN
//xFormParent.rotation = Quaternion.Lerp(xFormParent.rotation, qt, Time.deltaTime * orbitDampening);
}
}
Is there a good method to achieve this type of 360 camera? I'd like dragging from right to left to always move the camera left and dragging left to right to always move the camera right -- no matter how the camera is oriented.c#unity 5camera rotatecamera movementgimbal-lockTue, 06 Feb 2018 03:39:29 GMTbrandoncluffJust updated to 2017.3.0f3 And my moving platforms are locking my character's rotation
http://answers.unity.com/questions/1451034/just-updated-to-201730f3-and-my-moving-platforms-a.html
I'm making a 3D platformer. I've been using the standard setup for moving platforms. When the character lands on a platform, they become a child object to the platform, and follow it.
This was working perfectly through several Unity versions up until 2017.3.0f3. Now, when the character lands on the platform, their rotation is fixed to whatever it was when they landed. So if you land facing forward, relative to the camera, you're stuck facing forward until you get off the platform.
Here is my code that finds the camera relative rotation for the player:
private void ComputeRotation()
{
Quaternion inputDirection = Quaternion.Euler(0, (Mathf.Atan2(LSX, LSY) * Mathf.Rad2Deg) + CameraObject.transform.rotation.eulerAngles.y, 0);
if (new Vector2(LSX, LSY).magnitude > 0f) //If the User pushes the joystick beyond a deadzone
{ //Rotate the character to face the direction the joystick is being held relative to the rotation of the camera
Direction = (Quaternion.Slerp(Direction, (inputDirection), Time.deltaTime * TurnRate * turnSpeed));
inputTransformDifference = Mathf.DeltaAngle(inputDirection.eulerAngles.y, transform.rotation.eulerAngles.y);
inputTransformDifference = Mathf.Abs(inputTransformDifference);
}
}
This is where that rotation is applied:
public void Rotate(Quaternion rotation)
{
rigidbody.rotation = rotation;
}
and to set the parent:
groundable.SetParent(collision.transform);
(groundable is the name of an interface)
I haven't the foggiest idea why this might have broken. I don't think this is gimbal lock, because the platforms aren't rotating, and when I did have rotating platforms cause gimbal lock, that could be temporarily remedied by re-instantiating the pre-fab, which hasn't fixed this issue.
Thanks for any thoughts you have
UPDATE: I rolled back to 5.6.5f1, and it un-broke, so I know it's the version that broke it.rotationchild objectparent transformgimbal-lockSat, 06 Jan 2018 04:19:27 GMTSpencerRiedelThird Person Camera on a speherical world
http://answers.unity.com/questions/1441585/third-person-camera-on-a-speherical-world.html
Hi all,
I am trying to implement a third person camera which will rotate around the player’s X and Y axis. My player is always facing upright towards the planet’s center meaning the Y direction changes depending where you are on the planet. The problem is rotating around the player’s local space.
Desired outcome is a camera controller like in Grow Up.
If anyone can help me with a solution it would be highly appreciated, thanks.rotationquaternionsplanetthird-person-cameragimbal-lockTue, 12 Dec 2017 07:16:47 GMTEliteFrameCAT Animation works in Max, not when imported in Unity
http://answers.unity.com/questions/1428481/cat-animation-works-in-max-not-when-imported-in-un.html
Hello,
I have rigged model that works fine in max, when I hit the play button,
when I do export it in fbx for unity I get the message for each bone of the CAT
saying:
The plug-in has detected one or more animation controllers that cannot be directly supported. Using the Bake Animation option may better address these limitations. The following nodes are affected...
Even using the Baking animation box when into Unity the model runs the the feet the other way around and the the arms the palms down.
Does anybody knows why and how to fix this?
bestfbx3dsmaxgimbal-lockTue, 31 Oct 2017 17:15:46 GMTflavio_ninYaw Pitch Roll order?
http://answers.unity.com/questions/1372966/yaw-pitch-roll-order.html
I am trying to obtain the Yaw Pitch and Roll from the quaternion and feed it into an Aerospace application.
I want to know how the Euler Angles are processed from a Quaternion, which order and is it okay to get the Euler Angle and feed it to a RHS coordinate system application?
Also I notice that the Pitch ranges only from -90 to + 90 (Gimbal lock / heading changes?). I want to know if I can directly calculate Yaw Pitch and Roll from the Quaternion as follows?
**roll** = Mathf.Rad2Deg * Mathf.Atan2(2.0f * (m_localQuat[2] * m_localQuat[3] - m_localQuat[0] * m_localQuat[1]), (m_localQuat[3] * m_localQuat[3] - m_localQuat[0] * m_localQuat[0] + m_localQuat[1] * m_localQuat[1] - m_localQuat[2] * m_localQuat[2]));
**pitch** = Mathf.Rad2Deg * Mathf.Asin(Clamp(2 * (m_localQuat[0] * m_localQuat[3] + m_localQuat[1] * m_localQuat[2], -1.0f, 1.0f)));
**yaw** = Mathf.Rad2Deg * Mathf.Atan2(2.0f * (m_localQuat[1] * m_localQuat[3] - m_localQuat[2] * m_localQuat[0]), (m_localQuat[3] * m_localQuat[3] - m_localQuat[0] * m_localQuat[0] - m_localQuat[1] * m_localQuat[1] + m_localQuat[2] * m_localQuat[2]));
The Mathf.Asin2 keeps the pitch in the -90/90 range so I have another equation that can expand the values to -180/180.
Let me know how I can pass rotations successfully? I also feel like Rigidbodies/FixedUpdate and Timescale has a direct impact on sending these values as my output graph doesn't look right when my roll is not 0. I am trying to send the values through a 8MS thread (Trying to interpolate as my Update thread is not fast enough)
Thanks,
Lakshmirotationquaternionrigidbodiesgimbal-lockaerodynamicsMon, 03 Jul 2017 00:19:15 GMTShrikky23IMU Sensor and Quaternion
http://answers.unity.com/questions/1371605/imu-sensor-and-quaternion.html
Hi,
I'm currently working on a Unity Game where an object is orientated according to an IoT sensor ( IMU).
I programmed the sensor so it sends a quaternion to the game via mqtt.
I have something that work without quaternion but is subject to gimbal-lock and I think that my magnometer is not well calibrated ( the heading would not turn regularly )
So I tried some algorithm that would not use Roll Pitch and Yaw.
My problem is that the object do move, but if I want to do a 360° with my cube, then I need to turn the sensor of, let's say 1500° ( did not check the true number).
I don't know if the quaternion calculated by the sensor is wrong or if I don't use it correctly in Unity.
I receive this kind of message : quaternion 0.23 -0.19 -0.91 0.30
Here's my code in unity:
String[] parsed = message.Split();
q.w = float.Parse(parsed[1],
System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
q.x = float.Parse(parsed[2],
System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
q.z = float.Parse(parsed[3],
System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
q.y = float.Parse(parsed[4],
System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
Just some parsing when I receive it, and I exchange Z & Y axis.
Then in the update :
_3Dmodel.transform.rotation = Quaternion.Inverse(q);
On the sensor side, I use this algorithm :
void MadgwickQuaternionUpdate(float ax, float ay, float az, float gx, float gy, float gz, float mx, float my, float mz)
{
float q1 = q[0], q2 = q[1], q3 = q[2], q4 = q[3]; // short name local variable for readability
float norm;
float hx, hy, _2bx, _2bz;
float s1, s2, s3, s4;
float qDot1, qDot2, qDot3, qDot4;
// Auxiliary variables to avoid repeated arithmetic
float _2q1mx;
float _2q1my;
float _2q1mz;
float _2q2mx;
float _4bx;
float _4bz;
float _2q1 = 2.0f * q1;
float _2q2 = 2.0f * q2;
float _2q3 = 2.0f * q3;
float _2q4 = 2.0f * q4;
float _2q1q3 = 2.0f * q1 * q3;
float _2q3q4 = 2.0f * q3 * q4;
float q1q1 = q1 * q1;
float q1q2 = q1 * q2;
float q1q3 = q1 * q3;
float q1q4 = q1 * q4;
float q2q2 = q2 * q2;
float q2q3 = q2 * q3;
float q2q4 = q2 * q4;
float q3q3 = q3 * q3;
float q3q4 = q3 * q4;
float q4q4 = q4 * q4;
// Normalise accelerometer measurement
norm = sqrtf(ax * ax + ay * ay + az * az);
if (norm == 0.0f) return; // handle NaN
norm = 1.0f / norm;
ax *= norm;
ay *= norm;
az *= norm;
// Normalise magnetometer measurement
norm = sqrtf(mx * mx + my * my + mz * mz);
if (norm == 0.0f) return; // handle NaN
norm = 1.0f / norm;
mx *= norm;
my *= norm;
mz *= norm;
// Reference direction of Earth's magnetic field
_2q1mx = 2.0f * q1 * mx;
_2q1my = 2.0f * q1 * my;
_2q1mz = 2.0f * q1 * mz;
_2q2mx = 2.0f * q2 * mx;
hx = mx * q1q1 - _2q1my * q4 + _2q1mz * q3 + mx * q2q2 + _2q2 * my * q3 + _2q2 * mz * q4 - mx * q3q3 - mx * q4q4;
hy = _2q1mx * q4 + my * q1q1 - _2q1mz * q2 + _2q2mx * q3 - my * q2q2 + my * q3q3 + _2q3 * mz * q4 - my * q4q4;
_2bx = sqrtf(hx * hx + hy * hy);
_2bz = -_2q1mx * q3 + _2q1my * q2 + mz * q1q1 + _2q2mx * q4 - mz * q2q2 + _2q3 * my * q4 - mz * q3q3 + mz * q4q4;
_4bx = 2.0f * _2bx;
_4bz = 2.0f * _2bz;
// Gradient decent algorithm corrective step
s1 = -_2q3 * (2.0f * q2q4 - _2q1q3 - ax) + _2q2 * (2.0f * q1q2 + _2q3q4 - ay) - _2bz * q3 * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx) + (-_2bx * q4 + _2bz * q2) * (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) - my) + _2bx * q3 * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 - q3q3) - mz);
s2 = _2q4 * (2.0f * q2q4 - _2q1q3 - ax) + _2q1 * (2.0f * q1q2 + _2q3q4 - ay) - 4.0f * q2 * (1.0f - 2.0f * q2q2 - 2.0f * q3q3 - az) + _2bz * q4 * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx) + (_2bx * q3 + _2bz * q1) * (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) - my) + (_2bx * q4 - _4bz * q2) * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 - q3q3) - mz);
s3 = -_2q1 * (2.0f * q2q4 - _2q1q3 - ax) + _2q4 * (2.0f * q1q2 + _2q3q4 - ay) - 4.0f * q3 * (1.0f - 2.0f * q2q2 - 2.0f * q3q3 - az) + (-_4bx * q3 - _2bz * q1) * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx) + (_2bx * q2 + _2bz * q4) * (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) - my) + (_2bx * q1 - _4bz * q3) * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 - q3q3) - mz);
s4 = _2q2 * (2.0f * q2q4 - _2q1q3 - ax) + _2q3 * (2.0f * q1q2 + _2q3q4 - ay) + (-_4bx * q4 + _2bz * q2) * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx) + (-_2bx * q1 + _2bz * q3) * (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) - my) + _2bx * q2 * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 - q3q3) - mz);
norm = sqrtf(s1 * s1 + s2 * s2 + s3 * s3 + s4 * s4); // normalise step magnitude
norm = 1.0f / norm;
s1 *= norm;
s2 *= norm;
s3 *= norm;
s4 *= norm;
// Compute rate of change of quaternion
qDot1 = 0.5f * (-q2 * gx - q3 * gy - q4 * gz) - beta * s1;
qDot2 = 0.5f * (q1 * gx + q3 * gz - q4 * gy) - beta * s2;
qDot3 = 0.5f * (q1 * gy - q2 * gz + q4 * gx) - beta * s3;
qDot4 = 0.5f * (q1 * gz + q2 * gy - q3 * gx) - beta * s4;
// Integrate to yield quaternion
q1 += qDot1 * deltat;
q2 += qDot2 * deltat;
q3 += qDot3 * deltat;
q4 += qDot4 * deltat;
norm = sqrtf(q1 * q1 + q2 * q2 + q3 * q3 + q4 * q4); // normalise quaternion
norm = 1.0f / norm;
q[0] = q1 * norm;
q[1] = q2 * norm;
q[2] = q3 * norm;
q[3] = q4 * norm;
}
That I call with this command in my loop:
updateImu();
MadgwickQuaternionUpdate(imu.ax, imu.ay, imu.az, imu.gx * PI / 180.0f, imu.gy * PI / 180.0f, imu.gz * PI / 180.0f, imu.mx, imu.my, imu.mz);
publishQuaternion();
Then I directly publish the quaternion without any other calculation.rotationrotatequaterniongimbal-lockThu, 29 Jun 2017 12:10:40 GMTArk_RevanIs it possible to rotate an object around its z-axis without changing its x-axis and y-axis?
http://answers.unity.com/questions/1283549/is-it-possible-to-rotate-an-object-an-object-aroun.html
Hi Unity Answers,
I'm currently working on a small game involving a rotating cube. The player clicks a button, which Lerps the cube's rotation on the z-axis by 90 degrees. This works fine, but if I click the other button (which rotates the cube around the x-axis), the cube will behave strangely. Sometimes it will rotate in the wrong direction, sometimes it will jitter. But I know that one of the key problems here is the z-axis rotating the x-axis during the Lerp sequence.
Here is the code I use to lerp:
IEnumerator LerpRotation(float a_Start, float a_End, float a_Duration, string a_Axis)
{
float i = 0;
float Rotation;
//A stylistic choice meant to make the cube rotate faster until it finishes.
float IncreaseRate = 0.0002f;
while (i < 1)
{
//a_Duration, in this scenario, is 2.0f
i += Time.deltaTime * a_Duration * IncreaseRate;
Rotation = Mathf.LerpAngle(a_Start, a_End, i);
switch (a_Axis)
{
case "x":
WonderCube.transform.eulerAngles = new Vector3(
Rotation,
WonderCube.transform.eulerAngles.y,
WonderCube.transform.eulerAngles.z);
break;
case "y":
WonderCube.transform.eulerAngles = new Vector3(
WonderCube.transform.eulerAngles.x,
Rotation,
WonderCube.transform.eulerAngles.z);
break;
case "z":
WonderCube.transform.eulerAngles = new Vector3(
WonderCube.transform.eulerAngles.x,
WonderCube.transform.eulerAngles.y,
Rotation);
break;
}
if (IncreaseRate < 2.0f)
IncreaseRate += 0.05f;
yield return null;
}
}
Again, this seems to work fine for the z-axis, but as soon as the x-axis is involved, the cube starts misbehaving. I've done some research and found something called Gimbal Lock (found here: http://answers.unity3d.com/questions/573035/avoiding-gimbal-lock.html), which might be related. However, I'm unsure if this is the same thing. I'd just like to be able to rotate around the z-axis without adjusting the direction of my x-axis and y-axis.
I'm thinking a dummy that doesn't rotate might work, but RotateAround is (according to Unity) obsolete, and I'm not sure how to use a dummy's axis for rotation.
I'd really appreciate some help on what I can do to improve this rotation code. Thanks very much.
**EDIT**: I've continued researching the problem, but I haven't found any solutions. I've tried researching if I was rotating in local space, but i'm using eulerAngles which is in World Space.
I also recorded a gif of the issue. Sorry for the low quality: http://imgur.com/a/BbwS7
It's hard to see it, but the jitter I mentioned is demonstrated in that gif. When I click the right button twice, the Y rotation and the Z Rotation jump to 180, despite the fact that only the X Rotation should be changed here.
I'd also like to clarify, as I have a better grasp on the problem now: my issues are that the rotation of the cube is follow the body, which I don't want, and that the cube is acting strangely when I rotate it on the X-Axis (regardless of the orientation of the Z-Axis and Y-Axis, as seen in the gif).rotationquaternionlerpgimbal-lockSun, 11 Dec 2016 23:34:49 GMTaskull100Gimbal Lock with Quaternions
http://answers.unity.com/questions/1268382/gimbal-lock-with-quaternions.html
What is the difference between these
1. ctrl.spawnedObject.transform.localRotation *= Quaternion.Euler( 0f, 0f, 90f );
2. ctrl.spawnedObject.transform.Rotate( new Vector3( 0f, 0f, 90f ), Space.Self );
3. ctrl.spawnedObject.transform.localRotation *= Quaternion.AngleAxis( 90f, Vector3.forward );
and this?
Vector3 worldVec = ctrl.transform.localToWorldMatrix.MultiplyVector( Vector3.back );
ctrl.spawnedObject.transform.RotateAround( ctrl.spawnedObject.transform.position, worldVec, 90f );
I have an object inside of a container. The object is spawned as prefab with a default Euler rotation of (90, 0, 180). I would like to rotate the object on the local Z axis. However, all rotations listed in the first code block result in a rotation on the local Y axis.
The second code block performs the expected rotation around the local Z axis.
I'd like to better understand why.
In the editor, I can see that the block is gimbal locked (rotating the Y, and Z parameters rotate the object on the Y axis) and the block's transform.forward reads as Euler (0, -1, 0).
I created an example project here: https://github.com/lrgsteven/help_unity_gimbal
Thanks for your help.transformquaterniongimbal-lockMon, 07 Nov 2016 20:01:58 GMTsbsmithHow to rotate objects using 2 different axis at the same time?
http://answers.unity.com/questions/1267494/how-to-rotate-objects-using-2-different-axis-at-th.html
The current project i've been working on goes like this:
there's a grid of Hex tile objects. When a hex tile gets clicked, it gets pushed down and goes back up. All the hexes around it will flip 180 degrees along the axis parallel to which side they correspond to. My Hexes have a pointy top, so left and right sides just rotate z axis by 180 and -180. When it comes to top right/left or bottom right/left, i get matched with gimbal lock.
I have been using DOTween to rotate my objects. I've been looking around and i can't seem to find a work around gimbal lockrotationgimbal-lockSat, 05 Nov 2016 21:22:27 GMTdumbletGimbal lock hell even with quaternions?
http://answers.unity.com/questions/1220023/gimbal-lock-hell-even-with-quaternions.html
I'm trying to make some flight controls and I think I'm running into gimbal lock issues since my camera view is periodically flipping out. I'm using quaternions as much as I can though, so I thought I wouldn't run into this issue. Specifically, I'm trying to change the roll and yaw and my camera will regularly spin around like crazy for a few frames, ultimately settling back into the correct position. My code is
float tarRollAngle = -tarAngle;
float tarYawAngle = tarAngle;
//Only update tar angle if it's changed enough
if(Mathf.Abs(rotateRollTarAngle - tarRollAngle) > 5)
{
rotateRollTarAngle = tarRollAngle;
rotateRollStartTime = Time.time;
rotateRollStartAngle = Globals.cockpit.transform.localRotation.eulerAngles.z;
rotateYawTarAngle = tarYawAngle;
rotateYawStartTime = Time.time;
rotateYawStartAngle = Globals.cockpit.transform.localRotation.eulerAngles.y;
}
Quaternion yawRot = Quaternion.AngleAxis(Mathf.Lerp(rotateYawStartAngle, rotateYawTarAngle, (Time.time - rotateYawStartTime) * rotSpeed), Vector3.up);
Quaternion rollRot = Quaternion.AngleAxis(Mathf.Lerp(rotateRollStartAngle, rotateRollTarAngle, (Time.time - rotateRollStartTime) * rotSpeed), Vector3.forward);
Globals.cockpit.transform.localRotation = yawRot * rollRot;
edit: I think the issue is actually caused by accessing the z and y angles from the rotations for my start angles. It's not accounting for the fact that I can get something like 357 instead of -3.quaternionmathgimbal-lockSat, 23 Jul 2016 17:51:44 GMThomer_3Unity animator with blender bones causes gimbal lock.
http://answers.unity.com/questions/1199540/unity-animator-with-blender-bones-causes-gimbal-lo.html
I have made a model with blender and imported it to unity and started making animations for it but when I rotate one bone along one axis it turns on another part way through then moves back as it finishes the rotation, which reminds me of how a gimbal lock problem usually looks. I have tried changing interpolation to quaternions but this does not fix it, or change anything.
The bone by default out of blender has a rotation of 0,0,47 In blender I cannot seem to change the rotation to 0,0,0 In the animator when I add a rotation property in has xyz under it when it should have wxyz (when the interpolation is set to quaternion) ? I have tried for a long time to fix this, I have searched on the net for it but cannot find an answer.
I appreciate any help on this.animationanimatorquaternionbonegimbal-lockWed, 08 Jun 2016 07:59:34 GMTnutmmmCannot look aside after applying animation
http://answers.unity.com/questions/1192300/cannot-look-aside-after-applying-animation.html
Hi, I wish to start my game by having the player lie on the floor, then get up gradually (as if you've passed out). For this I've created an animator, and currently it looks like this:
![alt text][1]
And I've created two animations, one is onFloor, which does literally nothing but fixes the camera on the floor; the other is getUp, which brings the player up to standard position (standing). The following is a screenshot of GetUp
![alt text][2]
The thing is, after applying the animator (along with the animations), my mouse is able to control the camera to look straight upwards or downwards, but it cannot look right or left. I've heard issues about gimbal lock, and I've done everything in my knowledge to fix it, including adjusting the interpolation of the two clips to Quaternion mode.
I use the standard asset FPSController, currently building in 5.3.4f1.
Thanks!
[1]: /storage/temp/70728-擷取.png
[2]: /storage/temp/70730-擷取1.pnganimationanimatorfpscontrollergimbal-lockWed, 25 May 2016 13:40:58 GMTbr90218super quadratic mouse-look needs polishing
http://answers.unity.com/questions/1182425/super-quadratic-mouse-look-buggy.html
Hi, I've been trying to create the seemingly ultimate mouselook for a space game.. this script spins objects 360 deg. on the x and y Axes.. in addition it will rotate 360 on the z axis.. The purpose is that I want to fly around things and go upside down or sideways when necessary but still have my local down vector mapped locally downward (upward in this case).. like I'm upside down under an asteroid moving forward.. my local down direction is actually the global up.. so when I'm flipped, the xy axis flips.. everything has been going well in that respect , but there are poles `#pragma strict
import System.Collections.Generic; //need for the generic list type
//enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
var axes:RotationAxes = RotationAxes.MouseXAndY;
var sensitivityX = 15F;
var sensitivityY = 15F;
var zenabled=true;
var minimumX = -360F;
var maximumX = 360F;
var minimumY = -60F;
var maximumY = 60F;
var minimumZ= -89F;
var maximumZ = 89F;
var rotationX = 0F;
var rotationY = 0F;
var rotArrayX = new List.<float>();
var rotArrayY = new List.<float>();
var xflipped=false;
var yflipped=false;
var sp:spacepilot;
var rotAverageX = 0F;
var rotAverageY = 0F;
var frameCounter = 20.0;
var rb:Rigidbody ;
var originalRotation:Quaternion;
//var testa=false;
//var testb=false;
//var testc=false;
//var testd=false;
//var testf=false;
var i=0.0;
var onside=false;
var xyadust=0.0;
var Zupsideright=true;
var changeY=1;
var changeX=1;
var testg=false;
var reversepolarity=false;
var ZtargetRotation=0.0;
var smoothing=.5;
/////////////////////////////////////////////////////////////////////////////////////////////////////
function Update ()
{
if (Input.GetKey("a"))
ZtargetRotation+=1;
if (Input.GetKey("r"))//right the ship back to proper level
ZtargetRotation=0;
if (Input.GetKey("d"))
ZtargetRotation-=1;
transform.localRotation=Quaternion.Lerp(transform.localRotation,Quaternion.Euler(transform.localEulerAngles.x,transform.localEulerAngles.y,ZtargetRotation),Time.deltaTime*10/smoothing);
if (ZtargetRotation>360)
ZtargetRotation=0;
if (ZtargetRotation<0)
ZtargetRotation=360;
changeY=1;//reset these values each time.
changeX=1;//reset these values each time.
reversepolarity=false;//reset these values each time.
if (Input.GetKey("left")) rotationX-=5;
if (Input.GetKey("down")) rotationY-=5;
if (Input.GetKey("up"))rotationY+=5;
if (Input.GetKey("right"))reversepolarity=true;
//if (axes == RotationAxes.MouseXAndY){//this returns true, why ?i dont know
rotAverageY = 0f;//resets rotation averages for fresh calculations each time
rotAverageX = 0f;
//if (rotationX>360)//makes sure the vales stay in -360 to 360 rage(they werent before i added this)
//rotationX=0.0;
if (rotationY>maximumY)
rotationY=maximumY;
//if (rotationX<-360)
//rotationX=0.0;
if (rotationY<minimumY )
rotationY=minimumY ;
///////////////////////////////////////////////////////////
if( ( rotationY>-90 && rotationY<-270)||(rotationY>90&&rotationY<270)){//y is now 1/4 of the way right or left and entering flipped status
yflipped=true;
xflipped=true;
}
else {yflipped=false;
xflipped=false;
}
if( ( rotationX<-90&& rotationX>-270)||(rotationX>90&&rotationX<270)){//x is now 1/4 of the way up or down and entering flipped status
xflipped=true;
yflipped=true;
}
else {yflipped=false;
xflipped=false;
}
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////on either side below///////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if ((ZtargetRotation>45&&ZtargetRotation<135)||(ZtargetRotation<315 && ZtargetRotation>225))//we are on the right or left side// x and y will exchange values here i think in this zone
{ onside=true;
if (ZtargetRotation>45&&ZtargetRotation<135){//on left side
if (yflipped==true)
{//if we are backwards change xrotation to negative
//yflipped=false;//i think this flips y back
flipX();// will make sensitivityX negative if positive and viceversa...will calculate a position change once in the end
%|-1296279953_82|%
if (xflipped==false){//just y is flipped
flipX();// will make sensitivityX if positive
flipY();// will make sensitivityY if positive
}
else{//x flipped too
xflipped=false;//i think this flips x back as well
flipY();// will make sensitivityY if positive in this case x though as the values are flipped y stayed positive here i think
}//end x flipped too
}//end if y flipped
else
{//we are just on a 45 and xy is flipped for that reason
reversepolarity=true;
flipY();// will make sensitivityY if positive in this case x though as the values are flipped y stayed positive here i think
}//end just on side brackets
}//end on right side==true
else
%|465685525_104|%
if (ZtargetRotation<315 && ZtargetRotation>225)
{ //on right side==true
if (yflipped==true)
{//if we are backwards change xrotation to negative
flipX();// will make sensitivityX negative if positive and viceversa...will calculate once in the end a positionchange
flipY();// will make sensitivityY negative if positive and viceversa
if (xflipped==false)
{//just y is flipped
flipX();// will make sensitivityX negative if positive and viceversa...will calculate once in the end a positionchange
flipY();// will make sensitivityY negative if positive and viceversa
}//endjust y flipped
else{//x flipped too
flipY();// will make sensitivityX negative if positive and viceversa...will calculate once in the end a positionchange
}//endx flipped too
}//end if y flipped
else{
//testa=false;
//we are just flipped x and y due to being on a 45
reversepolarity=true;
flipX();
}//end else
} //end just flipped x and y due to being on a 45
%|-1681659214_128|%
%|-1280828419_129|%
else
{onside=false;
}//end onside false
//////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (ZtargetRotation>135&&ZtargetRotation<225){//if we are upsidedown change xrotation to negative//carefull z has no negatives remember its range is from 0 to 360
//z isflipped
if (yflipped==true)///this will be false if on a 45
{//if we are backwards change xrotation to negative
if (xflipped==false){//just y is flipped
}
else{//x flipped too
flipX();
}}//end if y flipped
else{//we are just upsidedown
flipX();
flipY();
}
}//end if upside down
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////
///////// normal x rotation below
//////////
/////////////////////////////////////////////////////////////////////////////////
else{//upside right //-----------------------------------------------
if (ZtargetRotation<45||ZtargetRotation>315) //carefull z has no negatives remember its range is from 0 to 360
{//ship is upright start brackets
Zupsideright=true;
if (yflipped==true){//upside right and yflipped==true brackets
//if( ( rotationY>-92 && rotationY<-268)||(rotationY>92&&rotationY<268))
flipY();
flipX();//test added
if (xflipped==false){//upside right and Y flipped && x not ==true brackets
}//end Y flipped && x not ==true brackets
if (xflipped==true){//x is flipped too x is left right btw
flipY();
flipX();
}
}//end yflipped==true brackets
%|635788875_182|%
//x is not flipped either here so rotation is normal
if (xflipped==true){//upside right and Y not flipped && x is flipped just x
flipX();
flipY();
}//end xflipped==true brackets
}//end ynotflipped brackets
}//end shipzupright ... this value doesnt flip based on when the others do i think
else {Zupsideright=false;
}}//endupsideright
//////////////////////////////////////////////////////////////////////////
/////////////////////////////figuring orientation above////////////////////////////////////////
/////////////////////////final calculations below////////////////////////////////////////////////////
rotationX += Input.GetAxis("Mouse X") * sensitivityX*changeX;//this will get all prior input and final movement added
rotationY += Input.GetAxis("Mouse Y") * sensitivityY*changeY;//this will get all prior input and final movement added
if (reversepolarity==true){
rotArrayY.Add(rotationX);
rotArrayX.Add(rotationY);
}else
if (reversepolarity==false){
rotArrayY.Add(rotationY);
rotArrayX.Add(rotationX);
}
if (rotArrayY.Count >= frameCounter) {
rotArrayY.RemoveAt(0);
}
if (rotArrayX.Count >= frameCounter) {
rotArrayX.RemoveAt(0);
}
for(var j = 0; j < rotArrayY.Count; j++) {
rotAverageY += rotArrayY[j];
}
for(var i = 0; i < rotArrayX.Count; i++) {
rotAverageX += rotArrayX[i];
}
rotAverageY /= rotArrayY.Count;
rotAverageX /= rotArrayX.Count;
rotAverageY = ClampAngle (rotAverageY, minimumY, maximumX);
rotAverageX = ClampAngle (rotAverageX, minimumX, maximumX);
var yQuaternion:Quaternion = Quaternion.AngleAxis (rotAverageY, Vector3.left);
var xQuaternion:Quaternion = Quaternion.AngleAxis (rotAverageX, Vector3.up);
var zQuaternion:Quaternion= Quaternion.AngleAxis (transform.localEulerAngles.z, Vector3.forward);
transform.localRotation = originalRotation * xQuaternion * yQuaternion * zQuaternion ;
}//end update brackets
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function Start ()
{
rb = GetComponent.<Rigidbody>();
if (rb)
rb.freezeRotation = true;
originalRotation = transform.localRotation;
}
/////////////////////////////////////////////////////////////////////////////////////////////
function flipX(){
if (changeX==1)
changeX=-1;
else
changeX=1;
}
//----------------------------------------------
function flipY(){
if (changeY==1)
changeY=-1;
else
changeY=1;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static function ClampAngle (angle:float , min:float, max:float)
{
angle = angle % 360;
if ((angle >= -360F) && (angle <= 360F)) {
if (angle < -360F) {
angle += 360F;
}
if (angle > 360F) {
angle -= 360F;
}
}
return Mathf.Clamp (angle, min, max);
}
`cameramouselookgimbal-lockFri, 06 May 2016 16:03:15 GMTspringwaterRotate one gameobject in 90 degree increments based on another gameobjects rotation.
http://answers.unity.com/questions/1116500/rotate-one-gameobject-in-90-degree-increments-base.html
What I'm trying to do is rotate Gameobject 1's Y axis based on the Y axis range of Gameobject 2.
So, for instance, if Gameobject 1 is angled anywhere between NorthWest and NorthEast, then Gameobject 2 should be facing exactly North, then if Gameobject 1 changes it's angle to anywhere between NorthEast and SouthEast, then Gameobject 2 should change it's angle to be exactly East.
I tried to do it based on the y angle of the objects but I think i was running into some kind of gimbal lock issue.rotationrotation detectiongimbal-lockWed, 23 Dec 2015 16:27:12 GMTRenStrikeSpining gameObjects using eulerangles not working as intended
http://answers.unity.com/questions/1095251/spining-gameobjects-using-eulerangles-not-working.html
Hello, I'm trying to turn two different gameObjects: a tank turret around the Y-axis (horizontally) and its barrel around the X-axis (vertically) by adding both of them the following script:
[System.Serializable]
public class Properties
{
public Limit horizontalLimit = new Limit(Vector2.zero);
public Limit verticalLimit = new Limit(Vector2.zero);
public float speed = 0f;
}
public Properties properties;
(Turret's spins between [-360, 360] degrees horizontally and [0, 0] vertically and barrel, for example, between [-25, 40] degrees vertically and [0,0] horizontally)
What I have done is this method which is called in Update() one:
private void Rotate()
{
float mouseX = Input.GetAxis("Mouse X");
float mouseY = Input.GetAxis("Mouse Y");
mouseX = Mathf.Clamp(mouseX, properties.horizontalLimit.min, properties.horizontalLimit.max);
mouseY = Mathf.Clamp(mouseY, properties.verticalLimit.min, properties.verticalLimit.max);
gameObject.transform.Rotate(new Vector3(mouseY, mouseX, 0) * Time.deltaTime * properties.speed);
}
When placing running the scene the tank turret rotates perfectly and smoothly. However the tank's behaves oddly: barrel rotates around the X-axis without limits even beign clamped between a min and a max.
I've been investigating and the problem might me the Gimbal lock effect due to the use of euler angles.
So I changed Rotate() method using Quaternions instead. As I'm quite new into rotations my new Rotation() method is not working properly, can you help me?
private void Rotate()
{
// Aiming point
Vector3 direction = Input.mousePosition - gameObject.transform.position;
// Rotation quaternion
Quaternion rotation = Quaternion.LookRotation(direction);
Vector3 eulers = rotation.eulerAngles;
// Clamp the rotation to its limits
Mathf.Clamp(eulers.x, properties.verticalLimit.min, properties.verticalLimit.max);
Mathf.Clamp(eulers.y, properties.horizontalLimit.min, properties.horizontalLimit.max);
// Perform the rotation smoothly
gameObject.transform.Rotate(gameObject.transform.up * properties.speed * Time.deltaTime, eulers.y);
gameObject.transform.Rotate(gameObject.transform.right * properties.speed * Time.deltaTime, eulers.x);
}
Cheers, Héctorc#unity5euleranglesspingimbal-lockSun, 08 Nov 2015 13:35:21 GMThectorhfmImporting from blender adds gimbal locks
http://answers.unity.com/questions/1091469/importing-from-blender-adds-gimbal-locks.html
For every model I have created in Blender today, when I import into unity and try to rotate individual objects using the inspector, both y & z values rotate around the vertical axis. This happens with both .blend & .fbx formats, but not .obj. It only seems to be happening with newly created models; I tried importing a model I had created some time ago & had no issues.
I have tried creating several models, including one which was simply a pair of cubes, and in every case it's the same result; the model as a whole rotates OK, but the individual components are all gimbal locked. I'm using the newest versions of both programs. Does anyone have any idea why this is happening or how to fix it?rotationimporting assetsgimbal-lockSun, 01 Nov 2015 23:18:04 GMTcaptaincheeseWhy is rotation locking to an axis?
http://answers.unity.com/questions/1087070/why-is-rotation-locking-to-an-axis.html
I have a 3rd person skateboarding character (imagine Tony Hawks) whose rotation I wish to set at the top of a half pipe (so that they launch straight "up" and land back down on the pipe, without moving either forward or backwards). I'm doing this as, for small half pipes, some forward momentum is maintained so they hit the top and keep moving forward. Not ideal!
![alt text][1]
**Fig 1 - Skateboarder and halfpipe.**
In order to set the correct rotation (as if the player is riding an invisible wall aligned with the half pipe), I figure the players local x rotation should be 270.
![alt text][2]
**Fig 2 - Halfpipe with "wall". No matter the angle player goes up halfpipe, they should behave as if riding this (nonexistant) wall **
To do this, I have a collider/trigger set up at the lip of the pipe, with an OnTriggerEnter() calling this code:
if (coll.gameObject.tag == "Player")
{
Vector3 newEulerAngles = new Vector3(270,
coll.gameObject.transform.rotation.eulerAngles.y,
coll.gameObject.transform.rotation.eulerAngles.z);
float speed = 100000; // want this to be instant
float step = speed * Time.deltaTime;
coll.gameObject.transform.rotation =
Quaternion.RotateTowards(coll.gameObject.transform.rotation,
Quaternion.Euler(newEulerAngles), step);
}
When trying this however, the y and z rotation is set to zero, every time.
![alt text][3]
**Fig 3 - Approaching pipe at an angle**
![alt text][4]
**Fig 3 - On trigger, player rotation is snapped to (270, 0, 0), despite only x being altered**
I've tried various methods and they all behave this way, for example the simpler script:
if (coll.gameObject.tag == "Player")
{
Vector3 newEulerAngles = new Vector3(270,
coll.gameObject.transform.rotation.eulerAngles.y,
coll.gameObject.transform.rotation.eulerAngles.z);
coll.gameObject.transform.rotation = Quaternion.Euler(newEulerAngles);
}
I've done some looking around and my best guess is this has something to do with Gimbal locking, but I could be way off. If anyone can point out why the player is snapping to this angle and ignoring the previous y, z values I'd love to learn!
[1]: /storage/temp/56816-basic.png
[2]: /storage/temp/56817-wall.png
[3]: /storage/temp/56819-approach.png
[4]: /storage/temp/56820-straight.pngrotationanglesquaternionseuler anglesgimbal-lockFri, 23 Oct 2015 22:28:46 GMTDavid-SelkirkRotation Problem - Simulating Gimbal lock
http://answers.unity.com/questions/1075277/rotation-problem-simulating-gimbal-lock.html
I'm Having a problem with rotations.
I've done some research about this problem but it seems that everyone solves it with rotateArround.
I'm trying to replicate the rotations of a SpaceShip on a graphic representation. For that, I have to replicate its rotation on X, Y and Z on another object.
My object 1 is a gray cube and object two is a Colored cube with other cubes in it.
The red represents X.
The green represents y.
The blue represents z.
When I rotate cube 1 on X axis, the cube two red (and its children) should rotate the same amount.
The Y and Z work ok but the X is big problem.
![alt text][1]
![alt text][2]
[1]: /storage/temp/55401-cubes.png
In the end - the lowest cube on the hierarchy should be on the same position that the reference object.
[2]: /storage/temp/55403-cubes-3.png
The problems are:
-x only rotates between [270, 90] and after that the cube rotates in a weird way.
- when I copy the rotation values using quaternions the W recalculates automatically and I can't copy on only one axis.
The CODE:
if (xBool) {
transform.localEulerAngles = new Vector3 (originalObj.localEulerAngles.x, transform.localEulerAngles.y, transform.localEulerAngles.z);
}
if (yBool) {
transform.localEulerAngles = new Vector3 (transform.localEulerAngles.x, originalObj.localEulerAngles.y, transform.localEulerAngles.z);
}
if (zBool) {
transform.localEulerAngles = new Vector3 (transform.localEulerAngles.x, transform.localEulerAngles.y, originalObj.localEulerAngles.z);
}
Can someone help me?
thank you for your time!rotationrotate objecteuleranglesrotatearoundgimbal-lockFri, 02 Oct 2015 11:55:08 GMTsadsaRotating TO certain angle while avoiding gimbal lock
http://answers.unity.com/questions/1038130/rotating-to-certain-angle-while-avoiding-gimbal-lo.html
Hello. I'm currently encountering gimbal lock issue in custom, in-game inspector that let you precisely set rotation of object, minus "precisely" part.
I can't use Rotate* methods, because they're rotating BY specific angle, which makes the tool useless for building levels for my game and while I try to use euler angles, the aforementioned gimbal lock occurs. I've looked through other solutions, but all require using Rotate* methods which as I said are useless to me as I need to set angles precisely.rotationgimbal-lockSat, 29 Aug 2015 22:13:38 GMTdarkhogWeird behavior when setting eulerAngles directly
http://answers.unity.com/questions/1037671/weird-behavior-when-setting-eulerangles-directly.html
Hello, I'm using following code to set object's rotation in my custom (in-game) level editor:
Quaternion quat = LevEditGlobals.currentGO.transform.rotation;
Vector3 rot = quat.eulerAngles;
if (transformAxis == Axis.X){
rot.x = float.Parse(this.GetComponent<InputField>().text,System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
}
if (transformAxis == Axis.Y){
rot.y = float.Parse(this.GetComponent<InputField>().text,System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
}
if (transformAxis == Axis.Z){
rot.z = float.Parse(this.GetComponent<InputField>().text,System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
}
quat.eulerAngles = rot;
LevEditGlobals.currentGO.transform.rotation = quat;
As you can see, first I get object's current rotation, then I set specific items, based on values of specific variable. So far, so good.
The problem is that when I try to set last one (Z), the real thing that is being changed is rotation on Y axis for some reason (and yes, transformAxis equals Axis.Z). No points for guessing what happens when I trty to change Y rotation (it changes Y rotation, spoiler alert).
I guess problem rises from my use of euler angles, but I don't know how to write it in quaternion code.rotationquaternionsgimbal-lockFri, 28 Aug 2015 23:48:58 GMTdarkhogEncountering Gimbal Lock when using Transform.Rotate(Axis, Angle)
http://answers.unity.com/questions/1006851/encountering-gimbal-lock-when-using-transformrotat.html
Hi, folks! I have a question about avoiding gimbal lock when using Transform.Rotate(). So, I'm making a simple "Inspection" interface, where users can drag the cursor across the screen to rotate a 3D object.
**[Here's what it looks like when it works.][1]**
I'm rotating the object using Transform.Rotate() and an angle/axis pair, calculated from the cross product of the user's mouse direction and the camera's forward vector. Everything works pretty darn well, *except* for when the camera I'm using is pointed 90 degrees straight down (euler 90, 0, 0) -- suddenly, I can only rotate the object horizontally to the camera.
**[Here's what you get when it fails!][2]**.
Rotate that camera back down to (85, 0, 0) and things work again, but I do need the straight-down angle to work and I'm pulling my hair out trying to deal with this one. I dimly remember dealing with a similar problem -- which my peers called gimbal lock -- back when I was a little more naive, and would try to rotate objects by directly changing the components of transform.eulerAngles. It's been my impression that the whole angle-axis system wouldn't be prone to the same issues, but it seems that's not the case.
Anyway, I'd greatly appreciate it if you guys have some information about how I can solve this problem. For reference, here's the source for the rotation functionality:
//Get the vector direction of the user's mouse / finger as they drag:
Vector2 mouseDiff = (Vector2)Input.mousePosition - oldMousePos;
//Calculate the desired axis of rotation by crossing mouseDiff with the camera's forward vector
Vector3 axis = Vector3.Cross((Vector3)mouseDiff.normalized, camera.transform.forward).normalized;
//Calculate the amount to rotate this frame:
float angleDiff = mouseDiff.magnitude * rotateMouseSensitivity * Mathf.Deg2Rad;
//Do the deed! :
Object.transform.Rotate(axis, angle, Space.World);
//Update oldMousePos
oldMousePos = Input.mousePosition;
[1]: http://gfycat.com/KnobbyDimpledIndianpangolin#
[2]: http://gfycat.com/GrouchyHardtofindKestrelc#rotategimbal-lockcrossvector3 operationsTue, 14 Jul 2015 14:50:20 GMTpikzillaHow To get x Axis to 360 Degree?
http://answers.unity.com/questions/975001/how-to-get-x-axis-to-360-degree-1.html
in unity system,prevent Gimbal-lock x Axis Converted y,z Axis
I Want get x Axis to 360 Degree
in system , 0 degree = 0
90 degree = 90
91 degree = 89 and -180y , -180z
180 degree = 0 and -180y , -180z
270 degree = -90 and -180y , -180z
360 degree = 0 and -360y , -360z
How Can i get x Axis 360 not -90 ~ 0 ~ 90
or Convert x Axis to 360 degree valuec#x-axisgimbal-lockThu, 28 May 2015 06:31:37 GMTswkwon