• 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
0
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
Add comment
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.

Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



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

Why won't my 2D Sprite Move? 1 Answer

How to move the player only 1 tile per buttonPress? 2 Answers

2D Object following the cursor without glitchyness at the center 0 Answers

Problems with raycasting 2D. Probelmas com raycasting 2D. 0 Answers

  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges