'Unity Quaternion rotation with rigidbody is influences rotations it shouldn't
Hey fellow programmers,
I have a small problem with Quaternion (who doesn't). I make an airship that is flying using rigidbody. Making it fly forward and turning was not a problem, but now I try to make it lean again the direction of the turn (like a person driving a motor leaning into when doing a turn). The
problem is that the ship is making rotations around the x-axis, while i didn't program anything in that would influence it. I checked rotationSpeed
, but that only influence y and z-axis. It goes wrong around deltaRotation
, where the x-axis is influenced. I tried forcing it to be 0 with deltaRotation.x = 0.0f;
, but the ship still goes down without me changing the x-axis. Does anyone know what is happenning, and how to fix it?
if (Input.GetKey(KeyCode.W))
{
if (speed < maxSpeed)
{
speed += maxSpeed / incrementsSpeed;
}
}
if (Input.GetKey(KeyCode.S))
{
if (speed > 0)
{
speed -= maxSpeed / incrementsSpeed;
}
else
{
speed = 0;
}
}
if (Input.GetKey(KeyCode.D))
{
if (rotationSpeed.y < maxRotationSpeed)
{
rotationSpeed.y += maxRotationSpeed / incrementsRotationSpeed;
}
}
if (Input.GetKey(KeyCode.A))
{
if (rotationSpeed.y > -maxRotationSpeed)
{
rotationSpeed.y -= maxRotationSpeed / incrementsRotationSpeed;
}
}
forwardPower = transform.forward * speed;
//Calculate lean value of airship, depending on the speed and turn angle of the ship
float currentLeaningValue = rotationSpeed.y * speed;
float maxValue = maxRotationSpeed * maxSpeed;
float currentValue = ExtensionMethod.Mapz(currentLeaningValue, -maxValue, maxValue, -maxLeaningAngle, maxLeaningAngle);
//map the value of rotation to inspector rotation
float realRot = ExtensionMethod.Mapz(transform.eulerAngles.z, 0f, 360f, -180f, 180f);
realRot = 180 - Mathf.Abs(realRot);
if (currentValue < 0.0f && realRot > 0)
{
realRot *= -1f;
}
//Calculate force of leaning
float leanRotationSpeed = (currentValue - realRot) / incrementsRotationSpeed;
//Add lean force to turn rotation speed
rotationSpeed = new Vector3(0, rotationSpeed.y, -leanRotationSpeed);
//Convert to Quaternion, here something goes wrong
Quaternion deltaRotation = Quaternion.Euler(rotationSpeed);
//Did this to see if I manually put the x rotation to 0, it would work. Sadly it didn't
deltaRotation.x = 0.0f;
//Add forces to actual movement of airship
rb.MoveRotation(rb.rotation * deltaRotation);
rb.MovePosition(transform.position + forwardPower);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|