c# unity error can't flip my submarine on its y axis

66 Views Asked by At

This has been an issue for a week now. I can't seem to figure it out. I am trying to flip my submarine on its y axis once its goes upside-down. it rotates on my mouse position.

This code rotates my submarine on mouse position which is perfect.

Vector3 RayPos = cam.WorldToScreenPoint(transform.position);
Vector3 dir = Input.mousePosition - RayPos;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, 
rotateSpeed * Time.deltaTime);[sub flipping y][1]   

Now this code is my problem. Once my sub goes upside down it flips (y) but it only does it once and then when I go back the correct way it won't flip on (y) anymore.

Debug.Log(Mathf.Abs(Vector3.Dot(transform.up, Vector3.up)));
if (Mathf.Abs(Vector3.Dot(transform.up, Vector3.down)) < 0.125f)
{
    if (Mathf.Abs(Vector3.Dot(transform.right, Vector3.down)) > 0.825f)
    {
        SubTrans.localScale = new Vector3(transform.localScale.x, -1, 
        transform.localScale.z);
    }
    else
    {
        SubTrans.localScale = new Vector3(transform.localScale.x, 1, 
        transform.localScale.z);
    }
}
1

There are 1 best solutions below

0
On
if (Mathf.Abs(Vector3.Dot(transform.up, Vector3.down)) < 0.125f)

I assume this makes your code perform the swap only when the sub is ~90 deg to the ground. This is fine because the absolute value means it occurs on both left & right sides.

   if (Mathf.Abs(Vector3.Dot(transform.right, Vector3.down)) > 0.825f)

However this is wrong because of the absolute value. It treats up & down the same (comparatively since you're using transform.right), meaning it always flips you because abs(transform.right) is always >0.8 when the previous condition is valid.

You should be checking whether the sub is pointing up or down by checking the up direction like this

if (Mathf.Abs(Vector3.Dot(transform.up, Vector3.up)) > 0f) //less than 90deg angle with up
//flip sub upwards
else
//flip downwards

You can keep the outer if conditional if you want it to flip at certain times, but this is all that's needed.