Vector always pointing to (0, 0, 0)

Updated on January 11, 2017 in [A] Unity Scripting
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
7 on January 10, 2017

//Edit: There is a GIF in here but I don’t know how to show it, open the link instead.

The code is supposed to snap the camera rotation at a right angle to a planet, however it always does it at (0, 0, 0).

 public GameObject planet;
 void SnapCameraToPlanetTangent()
 {
 Vector3 pointToCenter = transform.position + planet.transform.position;
 Vector3 tangent = Vector3.Cross(transform.TransformDirection(Vector3.forward), pointToCenter);
 float difference = Vector3.Angle(transform.TransformDirection(Vector3.left), tangent);
 float dot = Vector3.Dot(transform.TransformDirection(Vector3.up), tangent);
 if (dot < 0)
 {
 transform.eulerAngles += new Vector3(0, 0, difference) * Time.deltaTime * rotateSpeed;
 }
 else transform.eulerAngles += new Vector3(0, 0, -difference) * Time.deltaTime * rotateSpeed;
 }
 

The green ball’s transform is (0,0,0), the white ball is set to “planet”.

  • Liked by
Reply
0 on January 11, 2017

bump

  • Liked by
Reply
Cancel
2 on January 11, 2017

I can’t help you exactly but I think your Math is a bit off.
For example, when calculating the direction from your current position and the planet’s position you should substract the vectors and not add them.
Also you said the camera should “snap” to the desired rotation but it seems you try to interpolate between the two positions. I would simplify this by using the Lerp function to interpolate from the current to the desired rotation.

Helpful
on January 11, 2017

When I think about it, I don’t even need to add the two vectors.
pointToCenter = planet.transform.position; works just as well (the problem persists, however).

Guru
on January 11, 2017

No, you don’t add them up, you subtract them from each other.
planetposition – yourposition

Show more replies
  • Liked by
Reply
Cancel
2 on January 11, 2017

I am an idiot.

Wise
on January 11, 2017

No, you’re no… Nah, i agree.

Helpful
on January 11, 2017

I*

Show more replies
  • Liked by
Reply
Cancel