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 BilboStabbins · Aug 16, 2012 at 02:11 PM · updateshootingfixedupdategetkeydown

Placing Input.GetkeyDown() inside FixedUpdate() slows down the rate I can fire at

Hello all,

As the title suggests, if I place Input.GetKeyDown() inside FixedUpdate() to fire a Rigidbody, then the rate I can fire at becomes intermittent, no matter how fast I press the key. Now this makes sense as FixedUpdate updates less often than Update, but if this is the case then how can I work around it to shoot when I'd like?

Thanks

//----

 // Public variables are also shown in the Unity UI and can be changed in the Inspector
     public Rigidbody bulletPrefab;        // holds a reference to the bullet Rigidbody
 
     //    public Transform bulletPrefab;
 
     public float bulletPower = 1500f;        // used to set the power of the bullets
     //    public float casingPower = 1500f;        // used to set the power of the bullet casings expelled from side of gin
     //    public float moveSpeed = 2f;    
 
     // The general variable to hold the direction of the bullt - Enemy or Forward
     public Vector3 bulletDirection = Vector3.zero;
 
     // Variable to hold the direction of the enemy, assigned to the Instantiation, etc
     private Vector3 enemyDirection = Vector3.zero;
 
     // Used to reference the Player object
     private GameObject playerObj;
 
     // Used to reference the LockOnTriggerObject
     private GameObject lockOnTriggerObj;
 
     public float ShootDelay = 0.1F;
 
     private float Timer = 0.0F;
 
     // References the direction of the Player
     private Vector3 playerFwdDir = Vector3.zero;
 
     // Used to delay when the shooting begins after the Player is touched
     private bool delayFlag = true;
 
     // Used as a reference to check the PlayerTouch flag in MovementController
     private bool playerTouched;
 
     // Used as a reference to check the HoverFlag in MovementController script
     private bool hoverFlag;
 
     // The position of the spawner when hovering
     public Vector3 hoveringPosition = Vector3.zero;
 
     // The position of the spawner when running
     private Vector3 runningPosition = Vector3.zero;
 
     // Flag to let other scripts know if a bullet from the Right bullet_spawner has hit an object
     public bool R_Bullet = false;
 
     //-----------------------------------------------------
     void Start()
     {
         // Find the Player Object and then access its PlayerSounds script in order to player the sounds we need
         playerObj = GameObject.Find("Player");
 
         lockOnTriggerObj = GameObject.Find("PlayerLockOnTrigger");
 
         // The forward direction of the Player
         playerFwdDir = playerObj.transform.TransformDirection(Vector3.forward);
 
         hoveringPosition = new Vector3(4.28f, 8.35f, 4.66f);
 
         runningPosition = new Vector3(4.239313f, 7.397574f, 7.170765f);
     }
 
     //-----------------------------------------------------
     void Update()
     {
         // Gain access to the WeaponController script to check its playerTouched variable..
         playerTouched = playerObj.GetComponent<WeaponController>().playerTouched;
 
         if (playerTouched)
             Firing();
 
         // Check whether the Player is hovering or not. This is used so that we can re-position the 
         // BulletSpawner_R object to a position that appears to shoot out of the right gun.
         hoverFlag = playerObj.GetComponent<MovementController>().HoverFlag;
 
         if (hoverFlag)
             transform.localPosition = hoveringPosition;
         else
             transform.localPosition = runningPosition;
     }
 
     //-----------------------------------------------------
     void Firing()
     {
         // Access the CrosshairToggle script and check whether the we have an enemy targeted.
         // Ie. Has the ray we cast in the EnemyIntersect script hit an enemy, passed the 
         // Enemy's position to CrosshairToggle to place the crosshair onto the enemy.
         //            if (PlayerObj.GetComponent<CrosshairToggle>().EnemyTargetted)
         if (lockOnTriggerObj.GetComponent<ClosestEnemy>().EnemyTargetted)
         // && lockOnTriggerObj.GetComponent<ClosestEnemy>().EnemyDestroyed == false)
         {
             // Calculate the relative position of the Player to the Enemy ans store in bulletDirection
             bulletDirection = lockOnTriggerObj.GetComponent<ClosestEnemy>().EnemyPosition - transform.position;
         }
         else
         {
             bulletDirection = Vector3.forward;
         }
 
         // Make the Spawner rotation equal to the rotation of the bullet direction,
         // (towards an Enemy or straight ahead)
         transform.rotation = Quaternion.LookRotation(bulletDirection);
 
         // If touching the screen with LMB AND touching the Player is true..
         if (Input.GetMouseButton(0) && playerTouched)
         {
             Timer += Time.deltaTime;
 
             if (Timer >= ShootDelay)
             {
                 Timer = 0;
 
                 // Create a new variable named instance (of type Rigidbody - the bullet in this case) 
                 // Into this variable we are storing a reference to the creation of a new object that is of type Rigidbody (bullet).
                 // Requires three pieces of information namely, Instantiate(What to make, Where to make it, a rotation to give it);
                 Rigidbody newBullet = Instantiate(bulletPrefab, transform.position, transform.rotation) as Rigidbody;
 
                 //Rename the bullet instances to avoid the default '(Clone)' extension which Unity adds.
                 newBullet.name = "bullet";
 
                 /* we will apply the force by first referring to our variable that represents the newly created object—instance, 
                 then using the AddForce() command to add a force in the direction of the fwd variable—multiplied by the
                 public variable named power that we created earlier. */
                 newBullet.AddForce(transform.forward * bulletPower);
             }
         }
     }
 
     //-----------------------------------------------------
     // DELAYER
     // Used to delay the shooting of the bullets to give the animation enough time to raise the arm, etc
     IEnumerator Delayer()
     {
         if (delayFlag)
         {
             yield return new WaitForSeconds(0.2f);
         }
 
         delayFlag = false;
     }
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

1 Reply

· Add your reply
  • Sort: 
avatar image
1

Answer by Meltdown · Aug 16, 2012 at 02:12 PM

You should be putting Input.GetKeyDown() into your Update() method. FixedUpdate is for Physics specific related stuff.

Comment
Add comment · Show 5 · Share
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
avatar image BilboStabbins · Aug 16, 2012 at 06:37 PM 0
Share

Well the projectile I'm firing has a Rigidbody component and so I placed the Instantiation/AddForce related stuff into FixedUpdate() as you're saying. So in that case, how would I link the the Get$$anonymous$$eyDown() I woulf have inside Update to then carry out the stuff in FixedUpdate?

Thanks

avatar image Meltdown · Aug 16, 2012 at 06:45 PM 0
Share

No, you must call your instantiate method from Update(). eg. if(Input.Get$$anonymous$$eyDown()) GameObject.Instantiate(); Then AddForce, since it's a Physics based method, is called in FixedUpdate(). You may want to store each instantiated projectile into a List, then loop through the list in FixedUpdate and apply the force there.

avatar image Meltdown · Aug 16, 2012 at 07:08 PM 0
Share

For performance you should only be calling AddForce() once. So add a script to your projectile prefab that adds the force in your Start() method so it only fires once.

avatar image Eric5h5 · Aug 16, 2012 at 07:42 PM 0
Share

It's quite O$$anonymous$$ to put AddForce in Update. Since it's just being done once on $$anonymous$$eyDown and not continuously, there's no particular reason to use FixedUpdate.

avatar image BilboStabbins · Aug 20, 2012 at 11:56 AM 0
Share

Thanks for the replies, guys.

Well, right now it's adding the force using $$anonymous$$eyDown as it's being developed in Windows. However, the game will be for iOS and will have continuous shooting when its ported.

$$anonymous$$y script is attached to the bullet spawner object, I wonder if you might help me with it and where everything should be placed? I'll paste it above if you don't $$anonymous$$d.

Thanks

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

10 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

Related Questions

GetKeyDown Space doesn't work correctly with FixedUpdate 2 Answers

Checkibg Rigidbody2d and component problems 0 Answers

Fixedupdate rate stays at 90 instead of 60 1 Answer

Update/FixedUpdate motion stutter (Note: This is NOT a novice deltaTime question) 16 Answers

What's the difference between Update and FixedUpdate 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