• 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 /
avatar image
0
Question by ThomasBT · Apr 23, 2018 at 07:43 AM · rotationtransformaiquaterniondisappearing

Boids for 2D

Hi I used the unity 4.x game AI programming to make some boids the only problem is the book makes them for 3D w$$anonymous$$le I am trying to do them in 2D, they work fine only problem is when they turn they rotate and disappear from view for bit until they end up flat again since they are only sprites.

Here's my code- using UnityEngine; using System.Collections;

 public class Flock : MonoBehaviour {
     public float minSpeed = 20.0f;
     public float turnSpeed = 20.0f;
     public float randomFreq = 20.0f;
     public float randomForce = 20.0f;
 
     //aligment varibles 
     public float toOriginForce = 50.0f;
     public float toOrginRange = 100.0f;
 
     public float gravity = 2.0f;
 
     //speration variables
     public float avoidanceRadius = 50.0f;
     public float avoidanceForce = 20.0f;
 
     //cohesion varibles
     public float followVelocity = 4.0f;
     public float followRadius = 40.0f;
 
     //Movment of boids variables
     private Transform origin;
     private Vector3 velocity;
     private Vector3 normalizedVelocity;
     private Vector3 randomPush;
     private Vector3 originPush;
     private Transform[] objects;
     private Flock[] otherFlocks;
     private Transform transformComponent;
 
 
     // Use t$$anonymous$$s for initialization
     void Start () {
         randomFreq = 1.0f;
         //Assign the parent as origin;
         origin = transform.parent;
 
         //Flock transform
         transformComponent = transform;
 
         //Temporary components
         Component[] tempFlocks = null;
 
         //Get all the flock components fromthe parent 
         //Transform in the group
         if (transform.parent) {
             tempFlocks = transform.parent.GetComponentsInC$$anonymous$$ldren <Flock> ();
         }
 
         //Assign and Store allthe flock objects in t$$anonymous$$s group
         objects = new Transform[tempFlocks.Length];
         otherFlocks = new Flock[tempFlocks.Length];
 
         for (int i = 0; i < tempFlocks.Length; i++) {
             objects [i] = tempFlocks [i].transform;
             otherFlocks [i] = (Flock)tempFlocks [i];
 
             //Null parent as the flock leader will be
             // FlockController object
             transform.parent = null;
 
             //Calculate random push depends on the random frequency provided
             StartCoroutine (UpdateRandom ());
         }
 
     }
         IEnumerator UpdateRandom() {
             w$$anonymous$$le (true) {
                 randomPush = Random.insideUnitSphere * randomForce; 
                 yield return new WaitForSeconds (randomFreq + Random.Range (-randomFreq / 2.0f, randomFreq / 20.0f));
             }
         }
     
     
     // Update is called once per frame
     void Update () {
     //Internal variables
         float speed = velocity.magnitude;
         Vector3 avgVelocity = Vector3.zero;
         Vector3 avgPosition = Vector3.zero;
         float count = 0;
         float f = 0.0f;
         float d = 0.0f;
         Vector3 myPosition = transformComponent.position;
         Vector3 forceV;
         Vector3 toAvg;
         Vector3 wantedVel;
         for (int i = 0; i <objects.Length;i++){
             Transform transform = objects[i];
             if (transform != transformComponent) {
                 Vector3 otherPosition = transform.position;
 
                 // Average Poition to calculate cohesion
                 avgPosition += otherPosition;
                 count++;
 
                 //Directional Vector from other flock to t$$anonymous$$s flock
                 forceV = myPosition - otherPosition;
 
                 //Magnitude of that directional vector(length)
                 d = forceV.magnitude;
 
                 //Add push vaule if the magnitude, the ; length of the vector, is less then followRadius to the leader
                 if (d < followRadius) {
                     //calculate the velocity, the speed of the object, based on the avoidance distance between flocks if the current magnitude is less than the specified avoidance radius
                     if (d < avoidanceRadius){
                         f = 1.0f - (d / avoidanceRadius);
                         if (d > 0) avgVelocity += (forceV / d) * f * avoidanceForce;
                         }
 
                     //just keep the current distance with the leader
                     f = d / followRadius;
                     Flock otherBoids = otherFlocks[i];
                     //We normalize the otherBoids velocity vector to get the direction of the movement, then we set a new velocity
                     avgVelocity += otherBoids.normalizedVelocity * f * followVelocity;
                 }
             }
         }
                 if (count > 0) {
                     //Calculate the aerage flock velocity(Alignment)
                     avgVelocity /= count;
                     //Calculate Cwnter value of the flock(Cohesion)
                     toAvg = (avgPosition / count) - myPosition;
                 }
                 else {
                     toAvg = Vector3.zero;
                 }
 
                 //Directional Vector to the leader
                 forceV = origin.position - myPosition;
                 d = forceV.magnitude;
                 f = d / toOrginRange;
 
                 //Calculate the velocity of the flock to the leader
                 if ( d > 0) //if t$$anonymous$$s void is not at the center of the flock
                 originPush = (forceV / d) * f * toOriginForce;
 
                 if (speed < minSpeed && speed > 0) {
                     velocity = (velocity / speed) * minSpeed;
                 }
 
                 wantedVel = velocity;
 
                 //Calculate final velocity
                 wantedVel -= wantedVel * Time.deltaTime;
                 wantedVel += randomPush * Time.deltaTime;
                 wantedVel += originPush * Time.deltaTime;
                 wantedVel += avgVelocity * Time.deltaTime;
                 wantedVel += toAvg.normalized * gravity * Time.deltaTime;
 
                 //Final Velocity to rotate the flock into
                 velocity = Vector3.RotateTowards(velocity, wantedVel, turnSpeed * Time.deltaTime, 100.00f);
 
                 transformComponent.rotation = Quaternion.LookRotation(velocity);
 
                 //Move the flock based on the calculated Velocity
                 transformComponent.Translate(velocity * Time.deltaTime, Space.World);
 
                 //nomralise the velocity
                 normalizedVelocity = velocity.normalized;
     }
 }
 

I also a have flock controller, but I didn't t$$anonymous$$nk it was needed to fix t$$anonymous$$s if it is then tell me and I shell put it up. I tried changing it, but doesn't work since Quaternion has to take all four axis x,y,z and w. How can I change t$$anonymous$$s code so my sprites won't rotate to the point they aren't visible anymore. If you answer can you specify what to do and what I need to get rid of or change and where to put it in my code please.

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

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

173 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

Related Questions

How can I multiply the rotation of a mirrored object? 1 Answer

How to instantiate on custom rotation? 1 Answer

Ball Rolling Animation Not Working Properly 0 Answers

Rotating an object towards target on a single axis 2 Answers

Basic AI Locked Axis 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