Search Unity

Moving object in random position in scence Like Fly.

Discussion in 'Scripting' started by sharpg, May 25, 2015.

  1. sharpg

    sharpg

    Joined:
    Mar 10, 2015
    Posts:
    150
    Dear all i am working on a small 2D game.My one Object is a Fly i want to move Fly continuously in scene in random positions during game play.
    I am now using this code to move but its move less and shake the fly more.I just need to move fly from one point to another point.Please Healp
    Code (csharp):
    1.  
    2. voidUpdate()
    3. {
    4. Vector3randompoint = newVector3(Random.Range(-10,10),Random.Range(-7,7 ));
    5.  
    6. gameObject.transform.position=Vector3.Lerp(gameObject.transform.position,randompoint,Time.deltaTime*1f);
    7.  
    8. }
    9.  
     
    Last edited: May 25, 2015
  2. sluice

    sluice

    Joined:
    Jan 31, 2014
    Posts:
    416
    It shakes because you are changing your random point in every update.

    You need to wait until your object is done moving to that point.

    Or you could wait a few seconds until changing your random point.
    To make it less predictable, I would use a random (say from 1.0 to 4.0 second) there to determine when to change direction. Careful not to change the amount of second in every update as you will encounter weird behaviour again.
     
    krougeau likes this.
  3. sharpg

    sharpg

    Joined:
    Mar 10, 2015
    Posts:
    150
    Can You please help me with code?I am a beginer.Thanks in anticipation.
     
  4. sluice

    sluice

    Joined:
    Jan 31, 2014
    Posts:
    416
    @sharpg,

    Does that give the wanted effect?

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class FlyScript : MonoBehaviour
    5. {
    6.     public float speed = 1.5f;
    7.     public float rotateSpeed = 5.0f;
    8.  
    9.     Vector3 newPosition;
    10.  
    11.     void Start ()
    12.     {
    13.         PositionChange();
    14.     }
    15.  
    16.     void PositionChange()
    17.     {
    18.         newPosition = new Vector2(Random.Range(-5.0f, 5.0f), Random.Range(-5.0f, 5.0f));
    19.     }
    20.    
    21.     void Update ()
    22.     {
    23.         if(Vector2.Distance(transform.position, newPosition) < 1)
    24.             PositionChange();
    25.  
    26.         transform.position=Vector3.Lerp(transform.position,newPosition,Time.deltaTime*speed);
    27.  
    28.         LookAt2D(newPosition);
    29.     }
    30.  
    31.     void LookAt2D(Vector3 lookAtPosition)
    32.     {
    33.         float distanceX = lookAtPosition.x - transform.position.x;
    34.         float distanceY = lookAtPosition.y - transform.position.y;
    35.         float angle = Mathf.Atan2(distanceX, distanceY) * Mathf.Rad2Deg;
    36.        
    37.         Quaternion endRotation = Quaternion.AngleAxis(angle, Vector3.back);
    38.         transform.rotation = Quaternion.Slerp(transform.rotation, endRotation, Time.deltaTime * rotateSpeed);
    39.     }
    40. }
    EDIT: added rotation
     
    Last edited: May 25, 2015
    User-966790, slokAR-VR and sharpg like this.
  5. sharpg

    sharpg

    Joined:
    Mar 10, 2015
    Posts:
    150
    Yes Sir Its Working Fine.Thank you Very much Sir :)
     
  6. sharpg

    sharpg

    Joined:
    Mar 10, 2015
    Posts:
    150
    Sir i am facing one more problem.Now fly moves but after some time its stop moving for one or two second and then start flying again.I want it to move continuously without stopping.Please guide.
     
  7. sluice

    sluice

    Joined:
    Jan 31, 2014
    Posts:
    416
    That's weird, I don't see what could cause that. After how long does this happens? (I let mine run for the last 5 minutes and no problem.) You could have a memory leak problem caused by another script?

    Do you have any other scripts running somewhere else?
    To quickly test that this issue is not caused by the FlyScript: deactivate every other gameobjects and scripts, so you only have your fly and the FlyScript running. See if the issue still occurs.
     
  8. sharpg

    sharpg

    Joined:
    Mar 10, 2015
    Posts:
    150
    yes sir i have deactivate every script and test only one fly.it move slow and stay for a while in new position.i want to change position quickly don't need wait.
     
  9. sluice

    sluice

    Joined:
    Jan 31, 2014
    Posts:
    416
    There is nothing in my script that would cause such a thing, so I'm thinking this might be cause elsewhere.

    Just for fun, create an new empty project, add only a sprite(image) on the scene and put my script on the sprite.. Test.

    For the speed, play with the speed variable. But careless of that variable value, the fly should never stay in place, because as soon as it's close to the newPosition, we ask for a new Position.
     
  10. Bradamante

    Bradamante

    Joined:
    Sep 27, 2012
    Posts:
    300
    What you are talking about is commonly known as Steering, Wandering, Flocking or Swarming. It's basic AI behavior that you don't have to come up with yourself. Look at UnitySteer. It's a big package and might overwhelm you as a beginner. But if you are starting with Unity reading code is a good way to learn ... You could try to come up with your own system, but it would be a even more frustrating experience.
     
    blizzy likes this.
  11. sharpg

    sharpg

    Joined:
    Mar 10, 2015
    Posts:
    150
    OK Sir Thanks :)
     
  12. sluice

    sluice

    Joined:
    Jan 31, 2014
    Posts:
    416
    @Bradamante, I think that might be overkill for the simplicity of what he seeks.
     
  13. sharpg

    sharpg

    Joined:
    Mar 10, 2015
    Posts:
    150
    Sir how can i make fly to move its mouth towards direction which its moving.right now fly keep its mouth only one side no matters in which direction its moving right or left.
     
  14. sluice

    sluice

    Joined:
    Jan 31, 2014
    Posts:
    416
    There is a LookAt function that works well in 3D space. Unfortunately, it works like shizzle in 2D.

    Remember the Trigonometry you've learned in Math Class? It can come useful now. :)

    First, I would create a new function like so:
    Code (csharp):
    1. void LookAt2D(Vector3 lookAtPosition)
    2. {
    3.     float distanceX = lookAtPosition.x - transform.position.x;
    4.     float distanceY = lookAtPosition.y - transform.position.y;
    5.     float angle = Mathf.Atan2(distanceX, distanceY) * Mathf.Rad2Deg;
    6.  
    7.     Quaternion endRotation = Quaternion.AngleAxis(angle, Vector3.back);
    8.     transform.rotation = Quaternion.Slerp(transform.rotation, endRotation, Time.deltaTime * rotateSpeed);
    9. }
    10.  
    Then call this function like so, in the end of your Update Method:
    Code (csharp):
    1. void Update ()
    2. {
    3.     if(Vector2.Distance(transform.position, newPosition) < 1)
    4.         PositionChange();
    5.  
    6.     transform.position=Vector3.Lerp(transform.position,newPosition,Time.deltaTime*speed);
    7.  
    8.     LookAt2D(newPosition);
    9. }
    10.  

    Note: I have created a variable for the rotation speed (rotateSpeed) that I putted right under the variable speed. You will need to play around with these two variables in the inspector to find something that feels natural.

    Personally, I find that these value works well:
    Code (csharp):
    1. public float speed = 1.5f;
    2. public float rotateSpeed = 5.0f;
    PS: I have edited my post above with the complete code.
     
    Last edited: May 25, 2015
  15. sharpg

    sharpg

    Joined:
    Mar 10, 2015
    Posts:
    150
    Sir its rotating the fly while moving but fly still not facing the direction its moving.
     
  16. sluice

    sluice

    Joined:
    Jan 31, 2014
    Posts:
    416
    Play with the speed and rotateSpeed values. The rotationSpeed should be higher than the speed.

    Or to fix this issue completely, you could make sure the object is rotated before moving torwards it.
    I would use a coroutine instead.
     
  17. sluice

    sluice

    Joined:
    Jan 31, 2014
    Posts:
    416
    @sharpg

    I normally would prefer to see this inside a Coroutine, but simply modifying the current script we had to this, does the trick easily:

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class FlyScript : MonoBehaviour
    5. {
    6.     public float speed = 1.5f;
    7.     public float rotateSpeed = 5.0f;
    8.  
    9.     Vector3 newPosition;
    10.     bool isMoving = false;
    11.  
    12.     void Start ()
    13.     {
    14.         PositionChange();
    15.     }
    16.  
    17.     void PositionChange()
    18.     {
    19.         newPosition = new Vector2(Random.Range(-5.0f, 5.0f), Random.Range(-5.0f, 5.0f));
    20.     }
    21.    
    22.     void Update ()
    23.     {
    24.         if(Vector2.Distance(transform.position, newPosition) < 1)
    25.             PositionChange();
    26.  
    27.         if(LookAt2D(newPosition))
    28.             transform.position=Vector3.Lerp(transform.position,newPosition,Time.deltaTime*speed);
    29.     }
    30.  
    31.     bool LookAt2D(Vector3 lookAtPosition)
    32.     {
    33.         float distanceX = lookAtPosition.x - transform.position.x;
    34.         float distanceY = lookAtPosition.y - transform.position.y;
    35.         float angle = Mathf.Atan2(distanceX, distanceY) * Mathf.Rad2Deg;
    36.        
    37.         Quaternion endRotation = Quaternion.AngleAxis(angle, Vector3.back);
    38.         transform.rotation = Quaternion.Slerp(transform.rotation, endRotation, Time.deltaTime * rotateSpeed);
    39.  
    40.         if(Quaternion.Angle(transform.rotation, endRotation) < 1f)
    41.             return true;
    42.  
    43.         return false;
    44.     }
    45. }
     
    naveed2040 and sharpg like this.
  18. sharpg

    sharpg

    Joined:
    Mar 10, 2015
    Posts:
    150
    Dear sir,I have try this script bur fly not flip exactly toward the position its moving.its flip randomly.i
    have also tried this
    Code (csharp):
    1.  
    2. Quaternion endRotation = Quaternion.AngleAxis(angle, Vector3.Forward);
    3. Quaternion endRotation = Quaternion.AngleAxis(angle, Vector3.Up);
    4. Quaternion endRotation = Quaternion.AngleAxis(angle, Vector3.Down);
    5.  
    But didn't get required result.I just want to flip the fly exactly towards its current moving direction .
    Thanks.
     
  19. sluice

    sluice

    Joined:
    Jan 31, 2014
    Posts:
    416
    sharpg likes this.
  20. sharpg

    sharpg

    Joined:
    Mar 10, 2015
    Posts:
    150
    sluice likes this.
  21. sharpg

    sharpg

    Joined:
    Mar 10, 2015
    Posts:
    150
    Dear Sir, i am using this sprite.Please have a look, thanks.At this sprite this code give unexpected result.
     

    Attached Files:

  22. sluice

    sluice

    Joined:
    Jan 31, 2014
    Posts:
    416
    It's not unexpected. Your sprite is a view of the side, while my script and example are of top view.

    Firstly, rotate your sprite 90 degree clockwise in any image editor (so it looks like the bee is looking up). This will fix half of the problem.

    After you have modified the image, a weird behaviour you will encounter is when your bee is moving to the right: it will be upside down. You can change the orientation of your bee pretty easily.. just by changing the X scale value from 1 to -1, and vice versa.

    Code (csharp):
    1. //Change the PositionChange method for this.
    2. void PositionChange()
    3. {
    4.     newPosition = new Vector2(Random.Range(-5.0f, 5.0f), Random.Range(-5.0f, 5.0f));
    5.  
    6.     //This check if the new position is to the right of the flying object.
    7.     if(newPosition.x > transform.position.x)
    8.         transform.localScale = new Vector3(-1, 1, 1);
    9.     else
    10.         transform.localScale = Vector3.one;
    11. }
    12.  
     
  23. Abhijit-Mukherjee

    Abhijit-Mukherjee

    Joined:
    Jan 9, 2015
    Posts:
    193
    This post is very helpful to me .... Thank you ..
     
  24. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    Dude, don't necro unless you have something to add
     
  25. Naayte

    Naayte

    Joined:
    Jan 15, 2015
    Posts:
    2
    Quit piggybacking off the necropost, bro... ;p Kidding. Anyways...

    For anyone still finding this useful, I got a much better result for my project personally by replacing Lerp with MoveTowards.

    Also, by replacing the contents of LookAt2D() to the below, I got a good result for my 2.5D enemies who only ever look left and right.


    Code (CSharp):
    1. // rend is simply the enemy objects SpriteRenderer.
    2. // you may need to play around with the "<" or ">" depending on your Sprites initial direction.
    3.  
    4.     void LookAt2D(Vector2 lookAtPosition)
    5.     {
    6.  
    7.         if (transform.position.x < lookAtPosition.x)
    8.         {
    9.             rend.flipX = true;
    10.         }
    11.         else
    12.         {
    13.             rend.flipX = false;
    14.         }
    15.  
    16.     }
    17.  
     
    Last edited: Oct 2, 2018
  26. naveed2040

    naveed2040

    Joined:
    Feb 16, 2021
    Posts:
    1
    This was an awesome help, thank you.