Search Unity

Make an Object look another in Axis Y

Discussion in 'Editor & General Support' started by marcelobr, Jan 20, 2013.

  1. marcelobr

    marcelobr

    Joined:
    Sep 10, 2012
    Posts:
    12
    I need to make my object to look the other only on the y axis
    my code is doing my object to look the other in all axes, and that can not happen,
    I want it to look only to the next object on the y axis
    can anyone help me please?

    Code (csharp):
    1. // turn up
    2.         if(Input.GetKey("w")){
    3.            
    4.             Quaternion target = Quaternion.LookRotation(player.transform.position - targetUp.transform.position, Vector3.up);
    5.            
    6.             Player.transform.rotation = Quaternion.Slerp(Player.transform.rotation, target, Time.deltaTime *smooth);
    7.         }
     
  2. shaderop

    shaderop

    Joined:
    Nov 24, 2010
    Posts:
    942
    First of all, this is question is better placed in the Scripting sub-forum, not in support.

    And by "look another in Axis Y" do you mean that the object should only rotate around the Y axis when looking at other objects? And if that is the case, do you mean the object's local Y axis or the world's Y axis?
     
    Last edited: Jan 20, 2013
  3. marcelobr

    marcelobr

    Joined:
    Sep 10, 2012
    Posts:
    12
    the object's local Y axis
    no the worlds y
    sorry :(
     
  4. shaderop

    shaderop

    Joined:
    Nov 24, 2010
    Posts:
    942
    What you want to do is to project the target's position on the xz plane of the object, then use that projected point to calculate the rotation. I believe there are a few ways to go about doing this projection, but here's one possible method that comes to mind:
    1. Find the target's position relative to the object's local coordinate system using Transform.InverseTransformPoint.
    2. Set the y-coordinates of the relative position to project the point on the object's xz plane.
    3. Translate the position back to world coordinates using Transform.TransformPoint.
    4. Now calculate the needed rotation to look at this new point using the code you posted above.
    5. PROFIT! (just kidding)
    Or, in code:
    Code (csharp):
    1. var relativeTargetPosition = this.transform.InverseTransformPoint(target.transform.position);
    2. relativeTargetPosition.y = 0;
    3. var pointToLookAt = this.transform.TransformPoint(relativeTargetPosition);
    4. // Do your looking at here using pointToLookAt
    I haven't tested this code, but it should at least get you started.

    Good luck.