Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Getting LookAt forward Vector3 without rotating

Discussion in 'Scripting' started by Admiral-Skye, Mar 30, 2013.

  1. Admiral-Skye

    Admiral-Skye

    Joined:
    Feb 10, 2013
    Posts:
    32
    I'm using the Tile Based Map Nav asset for a board game. It doesn't have a sample with melee units so I have to make it without reference. I'm trying to make the unit walk up to it's target without going to it's target center. I assigned the units a radius float, so the unit stops without going inside the other one. The problem I'm having is getting the angle between both units in a Vector3 regardless of the direction the target is facing. This is my code so far:

    Code (csharp):
    1.  
    2. Vector3 attackDirection = transform.position - target.transform.position;
    3. float attackSide = Vector3.Dot(Vector3.right,attackDirection);
    4. float targetAngle = Vector3.Angle(Vector3.forward,attackDirection);
    5. Quaternion rot = Quaternion.AngleAxis(targetAngle*attackSide,Vector3.up);
    6. Vector3 attackPos = rot * Vector3.forward;
    7.  
    8. iTween.MoveTo(gameObject, iTween.Hash("position",attackPos,
    9. "speed", ((moveSpeedMulti * followMaxMoves) + 1f) * moveSpeed,
    10. "orienttopath", true,
    11. "easetype", "linear"));
    The attacker seems to stop at the correct distance, but he is a few angles off, and sometimes in the completely wrong angle. What exactly am I doing wrong in my code?
     
  2. Admiral-Skye

    Admiral-Skye

    Joined:
    Feb 10, 2013
    Posts:
    32
    OK, I managed to fix it, I had to change

    Code (csharp):
    1. float attackSide = Vector3.Dot(Vector3.right,attackDirection);
    to

    Code (csharp):
    1. float attackSide = Vector3.Dot(Vector3.right,attackDirection.normalized);
    2.         if(attackSide > 0){
    3.             attackSide = 1;
    4.         } else if(attackSide < 0){
    5.             attackSide = -1;
    6.         }