• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
Question by mhanbai · Oct 27, 2016 at 10:22 PM · c#2dmovementphysics2d

How do I create a 2D movement script that will cause prefabs to drift around the screen?

Hi all, I'm having a lot of trouble attempting to create a carefree, drifting sort of movement for my game. The idea is that I spawn 5 - 50 'stars' on screen, and they drift from place to place until the user 'collects' them. I've tried multiple different solutions already, my first attempt was this:

 void Update() 
     {
         if (onList == true){
             transform.position = Vector3.MoveTowards(transform.position, wayPoint, startSpeed * Time.deltaTime);
         }
         if((transform.position - wayPoint).magnitude < 3)
         {
             Wandering();
         }
     }
 
     void Wandering() { 
         startSpeed = UnityEngine.Random.Range(minSpeed, maxSpeed);
         wayPoint = new Vector3 (UnityEngine.Random.Range(-5, 5), UnityEngine.Random.Range(-9, 9), -1);
     }

But the movement was extremely jerky and the stars tended to cluster around the center of the screen, which wasn't what I needed.

I then tried ripping a flocking mechanism from a MIT licensed project, however I couldn't find a way to make the stars travel around, only avoid each other when moved by the player (you may have noticed by this point I'm not terribly good at programming physics).

 void FixedUpdate () {
         bool dangerZone = false;
         Vector2 safeDistance = new Vector2();
 
         myPosition = new Vector2 (transform.position.x, transform.position.y);
 
         for (int i = 0; i < waypoints.Length; i++) { 
             if (myPosition == waypoints[i]) {
                 FindNewWaypoint ();
             } else {
                 //Vector3.MoveTowards (transform.position, myTarget, speed * Time.deltaTime);
                 Flock();
             }
         }
         transform.Rotate (rotation);
     }
 
     public virtual void Flock()
     {
 
         Vector3 newVelocity = Vector3.zero;
 
         CalculateVelocities();
 
         //transform.forward = _alignment;
         newVelocity += _separation * separationWeight;
         newVelocity += _destination * destinationWeight;
         newVelocity = newVelocity * speed;
         newVelocity = new Vector3(GetComponent<Rigidbody2D>().velocity.x, GetComponent<Rigidbody2D>().velocity.y, -1) + newVelocity; // head towards the velocity defined here
         newVelocity.z = 0f;
 
         GetComponent<Rigidbody2D>().velocity = Limit(newVelocity, maxSpeed);
     }
 
     protected virtual void CalculateVelocities()
     {
         // the general procedure is that we add up velocities based on the neighbors in our radius for a particular influence (cohesion, separation, etc.) 
         // and divide the sum by the total number of drones in our neighbor radius
         // this produces an evened-out velocity that is aligned with its neighbors to apply to the target drone        
         Vector3 separationSum = Vector3.zero;
         Vector3 destinationSum = Vector3.zero;
 
         int separationCount = 0;
         int destinationCount = 0;
 
         for (int i = 0; i < mrmanager.masterList.Count; i++)
         {
             if (mrmanager.masterList[i] == null) continue;
 
             float distance = Vector3.Distance(transform.position, mrmanager.masterList[i].transform.position);
 
             // separation
             // calculate separation influence velocity for this drone, based on its preference to keep distance between itself and neighboring drones
             if (distance > 0 && distance < desiredSeparation)
             {
                 // calculate vector headed away from myself
                 Vector3 direction = transform.position - mrmanager.masterList[i].transform.position;    
                 direction.Normalize();
                 direction = direction / distance; // weight by distance
                 separationSum += direction;
                 separationCount++;
             }
 
 
             // calculate vector headed away from myself
             /*Vector3 destDirection = transform.position + new Vector3(myTarget.x, myTarget.y, -1);    
             destDirection.Normalize();
             destinationSum += destDirection;
             destinationCount++;*/
             //rigidbody2D.velocity = Vector
 
         }
 
         // end
         _separation = separationCount > 0 ? separationSum / separationCount : separationSum;
         //_destination = destinationCount > 0 ? Limit(destinationSum / destinationCount, maxSteer) : destinationSum;
     }
 
     protected virtual Vector3 Steer(Vector3 target, bool slowDown)
     {
         // the steering vector
         Vector3 steer = Vector3.zero;
         Vector3 targetDirection = target - transform.position;
         float targetDistance = targetDirection.magnitude;
 
         if (targetDistance > 0)
         {
             // move towards the target
             targetDirection.Normalize();
 
             // we have two options for speed
             if (slowDown && targetDistance < 100f * speed)
             {
                 targetDirection *= (maxSpeed * targetDistance / (100f * speed));
                 targetDirection *= speed;
             }
             else
             {
                 targetDirection *= maxSpeed;
             }
 
             // set steering vector
             steer = targetDirection - new Vector3(GetComponent<Rigidbody2D>().velocity.x, GetComponent<Rigidbody2D>().velocity.y, -1);
             steer = Limit(steer, maxSteer);
         }
 
         return steer;
     }
 
     protected virtual Vector3 Limit(Vector3 v, float max)
     {
         if (v.magnitude > max)
         {
             return v.normalized * max;
         }
         else
         {
             return v;
         }
     }

Finally I tried creating way-points around the screen and making the stars lerp up and down while moving between them. Without the lerping it was way too rigid, and the lerping sorta broke, sending the stars 10000 points off into the distance.

 void Update () {
         myPosition = new Vector2 (transform.position.x, transform.position.y);
 
         directionVector = new Vector3(myTarget.x + myTarget.y, -1) - transform.position;
         directionVector = directionVector.normalized;
 
         crossProd = Vector3.Cross (Vector3.forward, directionVector);
         forwardVector = Vector3.MoveTowards (transform.position, myTarget, -1);
         lerpVector = Vector3.Lerp ((new Vector3(0, 0, 0) + crossProd * 0.01f), (new Vector3(0, 0, 0) - crossProd * 0.01f), 0.01f);
     
         for (int i = 0; i < waypoints.Length; i++) { 
             if (Vector3.Distance(waypoints[i], transform.position) < 0.4){
                 wp = i;
                 FindNewWaypoint ();
             } else {
                 transform.position = Vector3.MoveTowards (transform.position, myTarget, -1) + lerpVector;
             }
         }
     }
 

So seriously, I'm stuck and I need help. If anyone has any suggestions for fixing one of my previous three attempts, I'd love to hear it. Or, if anyone can think of a different solution, I'd love to hear that too. Thanks.

Comment

People who like this

0 Show 0
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

0 Replies

· Add your reply
  • Sort: 

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Update about the future of Unity Answers

Unity Answers content will be migrated to a new Community platform and we are aiming to launch a public beta later in June. Please note, we are aiming to set Unity Answers to read-only mode on the 31st of May in order to prepare for the final data migration.

For more information, please read our full announcement.

Follow this Question

Answers Answers and Comments

273 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Forcibly halt movement of slow rigidbodies, but not falling ones. (2D) 1 Answer

Player loses momentum when landing 0 Answers

Isometric movement for MoveTowards 0 Answers

Snake movement from Snake VS Block 0 Answers

Player won't stop moving when key is released 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges