Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Resolved HOW TO QUATERNION?

Discussion in 'Scripting' started by enesbagci2332, Aug 26, 2023.

  1. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82
    FELLAS, IS IT SURPRISING TO FIND OUT THAT I AM AN IDIOT?

    The problem:

    So, I have a game object (enemy) and I want it to follow the player but not with LookAt. But with rotating. I tried using Quaternion.RotateTowards with my homing rockets And they work pretty well! BUT IT DOESN'T WORK BETWEEN PLANES, Why?

    Can you guys explain Quaternion methods? I tried watching videos and reading the API. But I'm still stuck.

    PLANE CODE FOR ROTATING


    private void Update()
    {
    //yes
    Quaternion lookRotation = Quaternion.LookRotation(player.transform.position - transform.position);
    //lookRotation = Quaternion.Euler(lookRotation.eulerAngles.x, lookRotation.eulerAngles.y, lookRotation.eulerAngles.z);
    //Debug.Log(lookRotation);
    //transform.rotation = lookRotation;
    transform.rotation = Quaternion.RotateTowards(transform.rotation, lookRotation, speed * Time.deltaTime);
    //transform.Rotate(lookRotation.x, lookRotation.y, lookRotation.z, Space.World);





    ROCKET CODE FOR ROTATING (WORKS)


    Quaternion lookRotation = Quaternion.LookRotation(player.transform.position - transform.position);
    //transform.rotation = lookRotation;
    transform.rotation = Quaternion.RotateTowards(transform.rotation, lookRotation, 10 * Time.deltaTime);
    //transform.Rotate(lookRotation.x, lookRotation.y, lookRotation.z, Space.World);





    Enemy starts rotating around the player in a circle motion, with each frame circle gets bigger.

    I'm sorry for asking for help so much. I hope I can finish this project with your help and go on to start making more easier to code games.

    Edit: I deleted the other rotation!
     
    Last edited: Aug 26, 2023
  2. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    I just played around with how to make the plane/rocket to spin perfectly around a target, regardless if on left or right side of it. Was that you're question?
    Code (CSharp):
    1. void Update()
    2.     {
    3.         Vector3 targetDirection = (target.transform.position - transform.position).normalized;
    4.         Vector3 myFocusDirection = Vector3.zero;
    5.            
    6.         float maintainDistance = 10.0f;
    7.         float distanceVariable = 0;
    8.         float actualDistance = Vector3.Distance(transform.position, target.transform.position);
    9.  
    10.         float sideDirection = Vector3.Dot((Vector3.Cross(transform.forward,
    11.             target.transform.position - transform.position)), Vector3.up);
    12.  
    13.         if (sideDirection > 0)
    14.         {
    15.             myFocusDirection = transform.right;
    16.             distanceVariable = actualDistance - maintainDistance;
    17.         }
    18.         if (sideDirection < 0)
    19.         {
    20.             myFocusDirection = -transform.right;
    21.             distanceVariable = maintainDistance - actualDistance;
    22.         }
    23.  
    24.         if (targetDirection != myFocusDirection)
    25.         {
    26.             Quaternion myOffsetRotation = Quaternion.LookRotation(myFocusDirection - targetDirection);
    27.             //Debug.DrawRay(transform.position, targetDirection * 20f, Color.green, 1000.0f);
    28.             transform.rotation = myOffsetRotation;
    29.         }
    30.         transform.Translate(distanceVariable, 0, moveSpeed);
    31.     }
     
    enesbagci2332 likes this.
  3. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,769
    Just sounds like they aren't rotating fast enough.
     
    enesbagci2332 likes this.
  4. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    The problem I had while setting the rotation, was the direction and speed value. Because I couldn't find a way to get proper distance of "nextMovement" per se, to be able to calculate more or less rotation, since multiplying the forward * speed would give a wrong distance, per frame.

    So like I've done before I just maintain the distance from target, and let rotation do what ever it wants to, lol
     
    enesbagci2332 likes this.
  5. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,769
    You can just get the angle between the rocket/plane's forward direction, and the direction to the player. Vector3.Angle always returns a positive value, so you could easily generated a rotation speed with falloff with that alone.

    Probably easiest to just use an AnimationCurve to author this falloff in the inspector, then calculate the percentage of the current angle with respect to some maximum angle. Thus, the greater the angle, the greater the rotation speed, that should taper off as it aims towards the player.
     
    enesbagci2332 likes this.
  6. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    For all intents and purposes, it looks fine with debug:
    RotateAround.jpg

    But you are true, one day I'd like to find out where the math can change(without too much headache), to get it to rotate properly
     
    enesbagci2332 likes this.
  7. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,769
    The only maths in my suggestion is working out a percentage. It's not super difficult:
    Code (CSharp):
    1. public class RocketExample : MonoBehaviour
    2. {
    3.     #region Inspector Fields
    4.  
    5.     [SerializeField]
    6.     private Transform _target;
    7.  
    8.     [SerializeField]
    9.     private float _movementSpeed = 5f;
    10.  
    11.     [SerializeField]
    12.     private float _maxRotationSpeed = 90f;
    13.  
    14.     [SerializeField]
    15.     private float _maxRotationAngle = 90f;
    16.  
    17.     [SerializeField]
    18.     private AnimationCurve _rotationSpeedFalloff;
    19.  
    20.     #endregion
    21.  
    22.     #region Unity Callbacks
    23.  
    24.     private void Awake()
    25.     {
    26.         if (!_target)
    27.         {
    28.             this.enabled = false;
    29.         }
    30.     }
    31.  
    32.     private void Update()
    33.     {
    34.         Vector3 direction = (_target.position - transform.position).normalized;
    35.         Vector3 forward = transform.forward;
    36.  
    37.         float angleToTarget = Vector3.Angle(forward, direction);
    38.         float t = angleToTarget / _maxRotationAngle;
    39.         t = Mathf.Clamp01(t);
    40.  
    41.         float rotDelta = _maxRotationSpeed * _rotationSpeedFalloff.Evaluate(t) * Time.deltaTime;
    42.         Quaternion lookRotation = Quaternion.LookRotation(direction);
    43.         Quaternion rotateTowards = Quaternion.RotateTowards(transform.rotation, lookRotation, rotDelta);
    44.         transform.rotation = rotateTowards;
    45.  
    46.         float moveDelta = _movementSpeed * Time.deltaTime;
    47.         forward = transform.forward; //update forwards direction
    48.         transform.position += forward * moveDelta;
    49.     }
    50.  
    51.     #endregion
    52. }
    Just set the animation curve up like so:
    upload_2023-8-26_23-43-38.png

    And it works a treat.

    Mind you, OP never stated what was the desired behaviour for the planes.
     
  8. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    All about Euler angles and rotations, by StarManta:

    https://starmanta.gitbooks.io/unitytipsredux/content/second-question.html

    Generally it's not necessary to understand the internals.

    To create new rotations out of angles and vectors use Quaternion.AxisAngle() or else Quaternion.Euler()

    Keep in mind it may be useful to only set the
    transform.localRotation
    of a complex object, such as the rotating turret on a tank or large ship.
     
    enesbagci2332 likes this.
  9. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    lol, true, but his "circling while getting further away" reminded me of another problem, so I attempted with both in mind.

    But, once you find how to make something do a perfect rotation around something else, it's just a simple modification to make it get closer, or back to further away again.

    And, help with understanding the quaternion issue(a little better I hope)..
     
    enesbagci2332 likes this.
  10. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    Actually he did, but not sure it was about wanting them to rotate around player:
    So I think the question was how to get the enemy to go in a general direction, not necessarily turn directly towards, but near the player?
     
    enesbagci2332 likes this.
  11. zulo3d

    zulo3d

    Joined:
    Feb 18, 2023
    Posts:
    510
    It's because you forgot to comment out one of the transform.rotations in the rocket code. So you have two transform.rotations present. This means the rocket will rotate much faster than the plane.
     
    enesbagci2332 likes this.
  12. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82

    There are two states for rocket there was an if between I deleted the if but not the other rotation. Sorry!
     
  13. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82
    So to explain clear misunderstandings; I want the enemy plane to always try to get behind the player. The enemy plane may crash into the player if it means killing the player. There are two states for the enemy. one is chase which is when the enemy plane is far away from the player so it tries its best to get close to the player. And there is the following state where when the enemy is close enough to the player to start firing rockers and bullets.
     
  14. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82
    I tried multiplying the speed by 2 million, the problem is nothing about speed.



    It spins it around the player. pretty cool! and code is more reliable than mine! I would maybe use it in another game! It didn't work but thanks!

    Thanks! I will read the link you sent!



    HELLO! YOU AGAIN! I'm gonna start calling you my pal' now, you always help me.

    But I want the enemy player to follow the player's tail, let's say the player is in front of them, they should rotate around and try to get behind the enemy. Kinda like a dog fight!
     
  15. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    That would be more like a LookAt() situation, and the player should have a "trailVector" as I would call it. Which is basically a negative forward times however far back:
    Vector3 trailVector = -(player.transform.forward * 5.0f);

    And the enemy would focus on going to that spot. However it would be best to add in a threshold(within distance) check, to change the state to "Engage" so that once it gets close enough, it will no longer focus on the trail, but the player itself.
     
    enesbagci2332 likes this.
  16. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82

    At first, I was using lookAt but it just makes the enemy plane turn instantly. And it is not quite possible in real life to turn that quickly.
     
  17. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    oof, right... I thought lookAt was a quaternion method, that's just a Vector3 set. I mean to say another LookRotation().
     
    enesbagci2332 likes this.
  18. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    I read "plane" as in a very flat object, not a flying thing chasing you!

    Are you looking for agents chasing each other around by turning and chasing them??

    If so... I have a missile chasing you around... enclosed is the full package.

    Everything takes place in the X/Y plane.
     

    Attached Files:

  19. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82
    I will learn more about LookRotation(), thanks!



    I will check your package, thanks!
     
  20. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,043
    Me too. I got confused big time. Words.
     
    enesbagci2332 likes this.
  21. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82

    The script that came with your package looks pretty cool! But I haven't tried it yet but I think you should also add a audioSource that makes a boom sound in sync with particle system.
     
  22. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82
    we should call Plane (flying one) Plane and the other one a flat thingy.
     
  23. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82
    I was already using that. Thanks tho!


    It looks pretty great! I will try to learn from it.
     
  24. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82

    Your package didn't work for me, I'm trying in XYZ still thanks! Thanks to your script I understand Mathf much better.

    I kinda of ruined it, so I restarted the code from where I was started (RotateTowards),
     
  25. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82
    I FOUND A WAY!


    private void rotate()
    {
    //Vector3 direction = player.transform.position - transform.position;
    float xRotate = (player.transform.position.x - transform.position.x);
    float yRotate = (player.transform.position.y - transform.position.y);
    float zRotate = (player.transform.position.z - transform.position.z);
    Quaternion lookHere = new Quaternion(xRotate, yRotate, zRotate, transform.rotation.w);
    transform.rotation = lookHere;
    }


    But there is still a problem.

    How can I ensure that the enemy plane's FRONT is looking at the player? And not the back of the plane.

    Edit: LookAt is not working correctly in my case.
     
    Last edited: Aug 29, 2023
  26. arkano22

    arkano22

    Joined:
    Sep 20, 2012
    Posts:
    1,630
    "Front" in Unity is positive Z axis. So if your plane model is oriented the other way, either rotate it and re-export or negate the direction it should be looking at.
     
    enesbagci2332 likes this.
  27. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82
    Code (CSharp):
    1. //Vector3 direction = player.transform.position - transform.position;
    2.  
    3. float xRotate = (player.transform.position.x - transform.position.x);
    4.  
    5. //float xRotatee = (player.transform.position.x - transform.right.x);
    6.  
    7. //float yRotate = (player.transform.position.y - transform.position.y);
    8.  
    9. float yRotatee = (player.transform.position.y - transform.up.y);
    10.  
    11. float zRotate = (player.transform.position.z - transform.position.z);
    12.  
    13. //float zRotatee = (player.transform.position.z - transform.forward.z);
    14.  
    15. Quaternion lookHere = new Quaternion(xRotate, yRotatee, zRotate, transform.rotation.w);
    16.  
    17. transform.rotation = lookHere;

    This fixed it! Thanks tho! I am trying to fix the x and z axis now!
     
  28. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    Quaternions shouldn't have to be handled by each of it's 4 values, as:
    https://docs.unity3d.com/ScriptReference/Quaternion.html
    states:
    "They are based on complex numbers and are not easy to understand intuitively. You almost never access or modify individual Quaternion components (x,y,z,w); most often you would just take existing rotations (e.g. from the Transform) and use them to construct new rotations (e.g. to smoothly interpolate between two rotations). The Quaternion functions that you use 99% of the time are:
    Quaternion.LookRotation, Quaternion.Angle, Quaternion.Euler, Quaternion.Slerp, Quaternion.FromToRotation, and Quaternion.identity. (The other functions are only for exotic uses.)
    ".

    However, if you can modify the 4 values, and nothing breaks? Then, kudos! But as the documentation states, there's always a way to do it correctly. :)
     
    enesbagci2332 likes this.
  29. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82




    IF IT IS WORKING, IT IS NOT BROKEN.
     
  30. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    you mis-worded that,
    "IF IT IS WORKING FOR NOW, IT IS NOT BROKEN YET."

    lol, but have you tested for gimbal lock issues yet?
     
    arkano22, Bunny83 and enesbagci2332 like this.
  31. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82


    I guess. Now I have to fix the X or Z, the plane goes upside down. Any ideas on how can I fix that?
     
  32. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    But like I wrote here:
    Code (CSharp):
    1. float sideDirection = Vector3.Dot((Vector3.Cross(transform.forward,
    2.             target.transform.position - transform.position)), Vector3.up);
    Was a way to get your right side value and calculate that as your forward. If I remember correctly
    Vector3.Dot()
    is the way to determine on which side(forward, left, right, back) something is from your forward, as values return 1 = forward, 0 = sides, and -1 = back.

    Or maybe that's
    Vector3.Cross()
    that does that. My memory sucks something terrible, and I only "learn" it for the situation I need at that moment. Then I make a function that handles that issue, and always forget to write it down in my notes to why or how it works.. lmao

    yeah.. Vectors > Quaternions is hard. :(
     
    enesbagci2332 likes this.
  33. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82

    Thanks for telling me about Vector3 Dot I will check it out! Have a good day! And thanks for everything dude you are always so helpful!
     
    wideeyenow_unity likes this.
  34. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    Good! you learn it and explain it to me!

    lmao, yup no problem, I try to help where I can(if at all). :confused:
     
    enesbagci2332 likes this.
  35. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82
    Update:

    I am not sure you know (I may have posted about this problem in the unity forum) @wideeyenow_unity but one of the problems I had many weeks before was that my plane wasn't aligned when I exported it from Blender. So to make it go forward I was using rb.addrelativeforce and Vector3.right


    Sorry for bothering everyone. :( I didn't want to fix it because like I could use left and nobody would know! But unity knows. I have to re-export it now! Thanks for everything friends!
     
  36. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82

    Sorry about not paying attention to your post. :(
     
  37. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82
    It's fixed I'm using


    private void moveAndRotate()
    {
    rb.AddRelativeForce(Vector3.forward * speed);
    Vector3 directionToPlayer = player.transform.position - transform.position;
    Quaternion targetRotation = Quaternion.LookRotation(directionToPlayer, Vector3.up);
    rb.rotation = Quaternion.RotateTowards(rb.rotation, targetRotation, Time.deltaTime * rotationSpeed);
    }


    It works! Thanks for everything!
    lmao I tried but I'm dumb, I don't understand it. I'm sorry but I can't explain. :(
     
  38. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82
    I DID IT! HERE IS THE NEW CODE: (I ADDED COMMENTS TO EXPLAIN MY FRIENDS, THEY HELPED A LOT! (also with vector3.dot I got chatgpt assistance!)


    Code (CSharp):
    1.  
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. public class CheckFront : MonoBehaviour
    5. {
    6.     public GameObject realEnemy;
    7.     public GameObject lockedEnemy;
    8.     //public Canvas canvas;
    9.     public GameObject cube;
    10.     public float waitTime;
    11.     private void Update()
    12.     {
    13.         float smallestDistance = Mathf.Infinity;
    14.         // Get the position of the player
    15.         Vector3 playerPosition = transform.position;
    16.         // Find all objects in the scene with the specified tag
    17.         GameObject[] taggedObjects = GameObject.FindGameObjectsWithTag("Enemy");
    18.         // Iterate through all objects with the tag
    19.         foreach (GameObject obj in taggedObjects)
    20.         {
    21.             // Get the position of the current object
    22.             Vector3 objPosition = obj.transform.position;
    23.             // Calculate the distance between the player and the current object
    24.             float distance = Vector3.Distance(playerPosition, objPosition);
    25.             Vector3 toObject = obj.transform.position - transform.position;
    26.             // Check if this distance is smaller than the smallest distance found so far
    27.             if (distance < smallestDistance)
    28.             {
    29.                 if (Vector3.Dot(toObject.normalized, transform.forward.normalized) > 0 && toObject.magnitude < smallestDistance)
    30.                 {
    31.                     smallestDistance = toObject.magnitude;
    32.                     realEnemy = obj;
    33.                     cube.transform.position = realEnemy.transform.position;
    34.                 }
    35.             }
    36.             if (realEnemy != null)
    37.             {
    38.             }
    39.         }
    40.         //LOCKED ENEMY'I ATAMAK İÇİN BELİRLİ BİR SÜRE KOY EĞER O SÜRE BOYUNCA ÖNÜMDEKİ VE EN YAKINIMDAKİ DÜŞMAN HEDEF DEĞİŞMEDİYSE LOCKED ENEMY'İ O YAP
    41.     }
    42. }
    43.  
    At the last part I'm also going to add some type of timer to know if the enemy has changed for 2-3 second idk if it didn't then I will lock that enemy!


    edit: Cube is there to show what enemy is locked!



    THANKS TO EVERYONE FOR HELPING
     
    Last edited: Sep 7, 2023
  39. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    I'm just gonna let my arguments on this, go... lol, but you're getting there, absolutely! Just keep progressing!

    I expect a finalized demo of this within the week... (lol, bad boss humor, ignore!)
     
    enesbagci2332 likes this.
  40. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82

    my friend said do this way to me, blame them, boss!
     
    wideeyenow_unity likes this.
  41. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    Ohh I will............
     
    enesbagci2332 likes this.
  42. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    lol, but in all reality, it's not an issue yet.. But later you'll find referencing the classes is way better than the gameObjects.. for a number of reasons, but again, no problem yet..

    It's just something you'll come across eventually, it really is nit-picking at this point in time. Ignore me, please :D
     
    enesbagci2332 likes this.
  43. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82

    WHAT HAVE I DONE
     
    wideeyenow_unity likes this.
  44. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82

    Thanks! I will hopefully remember this when everything in my game goes rogue!
     
    wideeyenow_unity likes this.
  45. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    Ohh yes.. the glory days when you load up your project and it's doing everything other than what you coded it to do... good times.. lol

    But the point is, to build up your confidence. Every little project you make that turns into a playable game, will boost your confidence.. And you need that, early on, that's why it's best to start small and work your way up..

    However I never learned this, and attacked the worst projects imaginable, and am working my way down till I find a suitable project to declare done.. Don't do that, confidence and coder's block are real, only gain territory once you've defended the old territory(Confucius or Sun Tzu?)..
     
  46. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82
    Just to clarify:
    Dude I realized right now, I forgot to say that the code that I posted is for detecting and locking enemies, I remembered that I already solved this scripting question.

    Thanks for the tips!

    You sound like you know a lot dude thanks for everything, have a good day.