- Home /
Smooth Y rotation based on X rotation (C#)
Hello, I am trying to simulate a shark swim inside water.
At the moment I can get it to move and rotate based on its velocity.
But my rotations on Y aren't smooth because they change on condition and so they aren't relative.
My game is 2.5D so the character (a shark) won't move in the Z axis.
If you want to understand better the rotation I want to achieve you can check this video of Hungry Shark that moves exactly as I would like to:
Here is my code for the moment:
public class UnitPlayerMove : MonoBehaviour
{
public float speed;
private bool isFlying;
public float flyingForce;
private float baseY;
private float angleZ;
// Use this for initialization
void Start()
{
angleZ = transform.rotation.eulerAngles.z;
}
void Update()
{
float moveHorizontal = CFInput.GetAxis("Horizontal");
float moveVertical = CFInput.GetAxis("Vertical");
float CFAngleX = CFInput.ctrl.GetStick(0).GetAngle();
float angleX;
float angleY;
if (CFAngleX >= 0f )
{
angleY = 270f;
angleX = -(CFAngleX - 90f);
}
else
{
angleY = -270;
angleX = -(-CFAngleX - 90f);
}
Quaternion targetRotation = Quaternion.Euler(angleX, angleY, angleZ);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * speed);
Vector3 movement = new Vector3(moveHorizontal, moveVertical, 0.0f);
rigidbody.velocity = movement * speed;
rigidbody.position = new Vector3 (
rigidbody.position.x,
rigidbody.position.y,
1.0f
);
}
}
PS: CFAngleX is the angle obtained by a touch stick plugin, the joystick was oriented in a strange way and so I've made this little part of code you saw to get a normal X angle.
If you want an idea about how to achieve a smooth Y rotation based on the X one (or something else if I am on the wrong way), please let me know.
In advance, thank you.