Rotating an Object (To Face Another Object) Only on X and Y Axis
Hello, I did some research on the topic and I couldn't understand any answers so I decided to ask here. I would like my character to face the object, here is that part of the script:
 function lookAt ()
 {
     var rotation = Quaternion.LookRotation(Target.position - transform.position);
     transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * Damping);
 }
 
               The problem comes when "Target" gets to close to this object and it leans slightly back to deal with the Y axis, I thought if it would only face the objects X and Z axis it might fix this. Any help is appreciated. Thanks.
Answer by Geometrical · Mar 26, 2016 at 07:57 PM
Hello, the answer is pretty simple:
 function lookAt() {
     // Store the other object's position in a temporary variable
     var temp = Target.position;
     // Deflate it's x and z coordinate
     temp.x = temp.z = uint.MinValue;
     var lookRotation = Quaternion.LookRotation (temp);
     transform.rotation = Quaternion.Slerp (transform.rotation, lookRotation, Damping * Time.deltaTime);
 }
 
              This somewhat works, but he faces the wrong way, the target is my player so it is constantly moving and cannot set the angle to anything specific, how would I go about with this?
It does not work again, the object only face upwards now
What's the forward axis on your player's model/object? X, Y, or Z? Only use the forward axis to get the direction, make the other axis 0.
Answer by Alrick · Mar 27, 2016 at 08:13 PM
did you try something like:
transform.LookAt(new Vector3(Target.position.x, Target.position.y, transform.position.z));
OR
Target.LookAt(new Vector3(transform.position.x, transform.position.y, Target.position.z));
Depends on what should look at what.
Answer by TobiasW · Mar 26, 2016 at 04:55 PM
Untested, but this should work:
 var delta = target.position - transform.position;
 var angle = Math.Atan2(delta.y, delta.x) * Mathf.Rad2Deg;
 var rotation = Quaternion.Euler(0, angle, 0);
 
              Would I put all of that under my lookAt function? How would I intergrate this to my script?
Also, it somewhat works, but he faces the wrong way.
Yeah, it would just replace "var rotation = Quaternion.LookRotation(Target.position - transform.position);"
And depending on how exactly the way is wrong, try using "angle+180" or "-angle" in Quaternion.Euler.
Alternatively, this should also do it:
  function lookAt ()
  {
      var delta = Target.position - transform.position;
      delta.z = 0;
      var rotation = Quaternion.LookRotation(delta);
      transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * Damping);
  }
 
                  Oh yes I see where you may be confused, the Target is my player that is constantly moving around, and I cannot set a specific angle as it may change once the player moves.
Your answer