• 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 studlets · Oct 20, 2017 at 05:45 PM · velocitysidescrollergroundedflightenergy

3d Side Scroller - Cutting of velocity when characters energy hits zero..

I am building a sidescroller game with a dragon that I want to fly. But instead of allowing the player to just constantly fly around the map, the dragon needs to be constrained to energy usage. I have the UI Slider reacting to his flight but when the value hits zero I want velocity to be cut off until the energy bar has enough energy to take flight again. So I have built a separate script to control the flight, energy usage, what happens when the energy hits zero and when he is on the ground to regain that energy slowly. I am pretty sure I am approaching this correctly however the code structure is incorrect and I would very much appreciate if someone can take a look and tell me what I need to change please.

 public class Flight : MonoBehaviour
 {
     public KeyCode jumpButton;                                                       
 
     public float jumpForce;                                                          
 
     public UnityEngine.UI.Slider slider;                                             
 
     public float energyDecay;                                                        
     public float energyRestore;                                                      
     float energy;                                                                    
     const float maxEnergy = 100;                                                     
     bool grounded;                                                                   
 
     Rigidbody rb;                                                                    
 
     void Start()                                                                     
     {
         energy = slider.value;                                                       
         slider.maxValue = maxEnergy;                                                  
         slider.value = maxEnergy;                                                     
         rb = GetComponent<Rigidbody>();                                              
     }
 
     void Update()                                                                    
     {
         
         if (Input.GetKey(jumpButton) && energy <= maxEnergy)                         
         {
             Jump();
                                                
         }
         else if (energy <= 5f)
         {
             GetComponent<Rigidbody>().velocity = Vector3.zero;
         }           
     }
 
     private void FixedUpdate()
     {
         if (grounded)                                                           
         {
             slider.value += Time.deltaTime * energyRestore;                           
         }              
     }
 
     void Jump()
     {
         if (Input.GetKey(jumpButton))                                                                          
         {
             rb.velocity = Vector3.up;
             rb.AddForce(new Vector3(0, jumpForce));
             slider.value -= Time.deltaTime * energyDecay;                                                        
         }       
     }   
 
     void OnCollisionEnter(Collision col)                                                                                
     {
         if (col.collider.tag == "Ground")                                            
         {                                               
            grounded = true;
         }
     }
 
     void OnCollisionExit(Collision col)                                                                                      
     {
         if (col.collider.tag == "Ground")                                           
         {
             grounded = false;            
         }
     }    
 }

  
Comment
Add comment · Show 4
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 AmirSavand · Oct 20, 2017 at 05:52 PM 0
Share

It's bad practice to get value from sliders, it's the slider that should get its value from component/controller.

avatar image studlets AmirSavand · Oct 20, 2017 at 05:57 PM 0
Share

So me declaring energy equal to the slider's value is whats needs to be changed?

avatar image AmirSavand studlets · Oct 20, 2017 at 06:00 PM 0
Share

No that was not an answer to your question, it's just best practice.

Show more comments

1 Reply

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by AmirSavand · Oct 20, 2017 at 06:02 PM

I'm confused with your jump condition.

In the Update() you check this: if (Input.GetKey(jumpButton) && energy <= maxEnergy) and in your jump function you check if (Input.GetKey(jumpButton)).

Why are you checking for key down twice? and why the second time you don't check the energy? Is the Jump function being called from somewhere else too? (Other than Update())

Also, the second condition else if (energy <= 5f) will never be called since energy is always less than maxEnergy.

If you want to stop player form Jump()ing when energy is not enough you should do this:

if (Input.GetKey(jumpButton) && energy >= requiredEnergyToJump)

requiredEnergyToJump is the minimum energy for Jump()ing. (you should set that).

OLD ANSWER

If you want to stop an object (velocity) check this answer out: http://answers.unity3d.com/questions/12878/how-do-i-zero-out-the-velocity-of-an-object.html

And here's how to slow down an object (velocity) till it stops: http://answers.unity3d.com/questions/336009/how-do-i-make-an-object-slow-down-to-a-stop.html

Comment
Add comment · Show 3 · 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 studlets · Oct 20, 2017 at 08:07 PM 0
Share

lol... ya i am just getting to know the community. As it turns out the code to stop the velocity did exactly as intended and I was able to get it to respond accordingly thank you.

Now it's just down to restoring the energy when i hit anything tagged ground.

avatar image AmirSavand studlets · Oct 20, 2017 at 08:35 PM 0
Share

@studlets Awesome! Restoring energy would be a piece of cake using TriggerEnter/Exit. BTW don't forget to mark my answer as solution and upvote ;)

avatar image studlets AmirSavand · Oct 23, 2017 at 05:43 PM 1
Share

So after many hours of playing around with my script I was able to get the results I needed. This Script designated to a single $$anonymous$$ey that you set through the inspector. You can also set the energy decay rate and the energy restore rate. The script will also look for an energy slider that will have to be dropped in the inspector. Thank you @amirm3hdi for re$$anonymous$$ding me to follow best coding practices. It's important to learn best practices as a beginner and I thank you for speaking out. This is the finalized Script that solved all my issues.`

using System.Collections; using System.Collections.Generic; using UnityEngine;

public class Flight : $$anonymous$$onoBehaviour {

 public $$anonymous$$eyCode jumpButton;                                                       

 public float jumpForce;                                                          

 public UnityEngine.UI.Slider slider;                                             

 public float energyDecay;                                                        
 public float energyRestore;  

 float energy;                                                                    
 const float maxEnergy = 100;                                                             

 Rigidbody rb;                                                                    

 void Start()                                                                     
 {        
     energy = maxEnergy;                                                     
     rb = GetComponent<Rigidbody>();                                              
 }

 void Update()                                                                    
 {
     if (Input.Get$$anonymous$$ey(jumpButton))
     {
         Jump();
     }
 } 
 
 public void Jump()
 {   
     if (energy >= 15f)
     {
         rb.velocity = Vector3.up;
         rb.AddForce(new Vector3(0, jumpForce));
         energy -= energyDecay * Time.deltaTime;
         UpdateUIslider();
     }

     if (energy <= 0f)
     {
         jumpForce = 0f;
         rb.velocity = Vector3.zero;
         rb.angularVelocity = Vector3.zero;        
     }        
 }

 public void Energyregen()
 {
     energy += energyRestore * Time.deltaTime;
     UpdateUIslider();
 }

 public void UpdateUIslider()
 {
     slider.maxValue = maxEnergy;                                                  
     slider.value = energy;        
 }    

 void OnCollisionStay(Collision col)                                                                                
 {
     
     if (col.collider.tag == "Ground")                                            
     {            
         Energyregen();
     }
 }    

}`

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

71 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

Related Questions

Velocity powered rigidbody on a moving platform without parenting. 3 Answers

how can I make a character fly when holding down the jump button? 1 Answer

2D character can't jump off of platform floating in water 0 Answers

Add/remove Gravity with code 1 Answer

InvokeRepeating faster if the rigidBody is moving faster? 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