Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • 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 haiderInUnity · Jun 10, 2015 at 07:45 PM · shootinginvokerepeatingstartcoroutine

Shooting Projectiles With controlling attackSpeed

Hi I Have two Scripts ProjectileMotion and FSMArcherTower. I will brief you on how it works then ill tell you the problem. I Have attached both scripts to this tower and it shoots a projectile. Right now I have managed it to work almost the way i want but the code is a bit confusing. I have created a FSM in FSMArcherTower where In my update method I have Switch cases for different states of the tower. However I cannot call InvokeRepeating or StartCoroutine in update as it is called every frame. Thus I have called StartCoroutine In Start and created a while loop in the Co routine. The PROBLEM is that the code in public IEnumerator States() is not clean as attackSpeed variable is actually the input for yield waitForSeconds which if the value of attackSpeed is less causes to be actually More attack Speed. I just want a better way to use coroutines and Invoke and update in this situation. Any Insight will be helpfull. Thank you

 public class FSMArcherTower : MonoBehaviour {
 
     public enum ArcherTowerState
     {
         Idle,
         Attacking,
         Destroyed
     }
     
     public ArcherTowerState currentArcherTowerState;
 
     // Less is more speed
     // so 0.1f is faster attackSpeed than 0.9f
     public float attackSpeed = 0.5f;
     private bool canShoot;
     
     void awake()
     {
 
     }
 
     // Use this for initialization
     void Start () 
     {
         currentArcherTowerState = ArcherTowerState.Idle;
 
         StartCoroutine (States());
 
     }
     
     // Update is called once per frame
     void Update () 
     {
         switch (currentArcherTowerState)
         {
         case ArcherTowerState.Attacking:
             // logic for attacking
             canShoot=true;
             Debug.Log("Attacking");
             break;
 
         case ArcherTowerState.Idle:
             // what to do when idle
             canShoot = false;
             Debug.Log("Idle");
             break;
 
         case ArcherTowerState.Destroyed:
             // what happens when destroyed
 
             Debug.Log("Destroyed");
             break;
         }
     }
     
     public IEnumerator States()
     {
         while (true) {
             Debug.Log("True");
             if (canShoot)
             {
                 Invoke("callAttack",0.0001f);
             }
                 
             if (!canShoot)
             {
                 // what to do when idle
                 CancelInvoke("callAttack");
             }
 
 //            }
             yield return new WaitForSeconds (attackSpeed);
         }
     }
 
 
     public void callAttack()
     {
         GetComponent<ProjectileMotion>().attack();
     }
 }

ProjectileMotion only create the projectile and its motion towards the target

 public class ProjectileMotion : MonoBehaviour {
     
     public GameObject Target;
     public float firingAngle = 45.0f;
     public float gravity = 9.8f;
     public GameObject Projectile;      
     private Transform myTransform;
 
 
     void Awake()
     {
         myTransform = transform;
         Target = (GameObject)Instantiate (Target, transform.position + new Vector3(10,-3,0), Quaternion.identity);
         Target.name = "Capsule";
     }
     
     void Start()
     {
 
     }
 
     public void attack()
     {
         StartCoroutine(SimulateProjectile());
     }
     
     public IEnumerator SimulateProjectile()
     {
         // Instantiate projectile
         GameObject projectile = (GameObject)Instantiate (Projectile,myTransform.position, Quaternion.identity);
         Debug.Log ("Projectile initiated");
         
         // Calculate distance to target
         float target_Distance = Vector3.Distance(projectile.transform.position, Target.transform.position);
         
         // Calculate the velocity needed to throw the object to the target at specified angle.
         float projectile_Velocity = target_Distance / (Mathf.Sin(2 * firingAngle * Mathf.Deg2Rad) / gravity);
         
         // Extract the X  Y componenent of the velocity
         float Vx = Mathf.Sqrt(projectile_Velocity) * Mathf.Cos(firingAngle * Mathf.Deg2Rad);
         float Vy = Mathf.Sqrt(projectile_Velocity) * Mathf.Sin(firingAngle * Mathf.Deg2Rad);
         
         // Calculate flight time.
         float flightDuration = target_Distance / Vx;
         
         // Rotate projectile to face the target.
         projectile.transform.rotation = Quaternion.LookRotation(Target.transform.position - projectile.transform.position);
         
         float elapse_time = 0;
 
         while (elapse_time < flightDuration)
         {
 
             projectile.transform.Translate(0, (Vy - (gravity * elapse_time)) * Time.deltaTime, Vx * Time.deltaTime);
             
             elapse_time += Time.deltaTime;
             
             yield return null;
         }
 
         StartCoroutine (DestroyAfterWait (projectile));
     }  
 
     public IEnumerator DestroyAfterWait(GameObject projectile)
     {
         // destroy projectile after 0.5 sec
         yield return new WaitForSeconds (0.5f);
         if (projectile != null)
         {
             Destroy (projectile);
         }
         
     }
 
     void Update ()
     {
 
     }
     
     
 
 }
 

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.

Follow this Question

Answers Answers and Comments

2 People are following this question.

avatar image avatar image

Related Questions

I can't get InvokeRepeating to work in my script 1 Answer

Invoke repeating and StartCoroutine 1 Answer

What is the best between StartCoroutine or InvokeRepeating. 5 Answers

,Enemy AI rapidfires and invokerepeating doesn't do anything. c# 1 Answer

Invoke is not working properly. 0 Answers


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