Search Unity

Look At for One Axis

Discussion in 'Scripting' started by aksh2143, Feb 3, 2016.

?

How to use LookAt for only one axis?

  1. Can't be done

    0 vote(s)
    0.0%
  2. possible but with other ways

    100.0%
  1. aksh2143

    aksh2143

    Joined:
    Jul 6, 2015
    Posts:
    10
    How to use LookAt for only one axis?
    I want to rotate my target(gameobject) towards my tank(gameobject) and for that i am using LookAt. my target is a simple gameobject which has a barrier(rectangular line) which comes between tank and target so the target can't be shooted directly. So, whenever the target changes its position, the barrier should also change the position and set between target and tank. according to Image No. 1. But when i use below code what happens is instead of changing only Z axis rotation, it also changes X&Y axis and gets screwed up like shown in Image No2. Now how to rotate target in only Z axis ?

    my code is:

    Vector3 lp = Tank.transform.position; //Tank position to look at


    transform.LookAt(lp); // LookAt
    @Adam Buckner sir???
    used 1.JPG 2.JPG
     
  2. Andy-Touch

    Andy-Touch

    A Moon Shaped Bool Unity Legend

    Joined:
    May 5, 2014
    Posts:
    1,483
    aksh2143 likes this.
  3. aksh2143

    aksh2143

    Joined:
    Jul 6, 2015
    Posts:
    10
    i tried that but didn't find the result i'm looking for.


    For now i've been trying this



    void _Test()
    {
    barrier = gameObject.transform.FindChild("Barrier").gameObject;

    Vector3 targetDir = Tank.transform.position - transform.position;

    Vector3 newDir = Vector3.RotateTowards(transform.forward, targetDir, 1f, 1f);
    newDir = Vector3.RotateTowards(transform.forward, targetDir, 2, 2f);


    transform.rotation = Quaternion.LookRotation(newDir);
    barrier.transform.localScale = new Vector3(1f, barrier.transform.localScale.y, barrier.transform.localScale.z);
    }

    ive used the same code in OnEnable and invoked this method from there too.
    but for this code to make work, i have to disable => enable the script manually.

    and i'm still working on code to find proper sollution.
    My solln. is temperory.
     
  4. aksh2143

    aksh2143

    Joined:
    Jul 6, 2015
    Posts:
    10
  5. BluHornet

    BluHornet

    Joined:
    Feb 23, 2015
    Posts:
    40
    store the current rotation to a Vector3 for 3d and a Vector 2 for 2d. have the object lookat whatever. store that second to a Vector3 or Vector2. Use the appropriate axis in a third Vector that then the object is set to.