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 timelord · Jan 12, 2014 at 05:41 AM · rigidbodyaddforceontriggerenterrocketconstantforce

How to disable constant force over time? Rocket game

Hello, I have a rocket prefab with a rigidbody and box collider that needs to collect coins (fuel) in order to keep moving up. I would like the rocket to stop moving up (run out of fuel) if you stop collections coins and fall to the ground. My current code after hitting a box trigger is this.

function OnTriggerEnter(fuel: Collider){

     if(fuel.gameObject.tag == "fuel"){
     Debug.Log("We hit a fuel box!");
     constantForce.force = Vector3.up * 50;
     }
 }

I am not sure how to disable the constant Force code above or make it dissipate over time. So I used a force function

rigidbody.AddForce (0, 10, 0);

This only launched me up into the air exponentially for a brief time but at least I ended up crashing back into the ground.

Any help would be appreciated.

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

2 Replies

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

Answer by robertbu · Jan 12, 2014 at 11:36 AM

Here is one way to approach your problem. Get rid of the ConstantForce component. Just have a Rigidbody with gravity enabled. The attach this script:

 #pragma strict
 
 var fuel = 200.0;
 var burnRate = 50.0;  // Units per second
 var velocity = 0.5;
 
 function FixedUpdate() {
     fuel -= burnRate * Time.fixedDeltaTime;
     if (fuel < 0.0) 
         fuel = 0.0;
         
     if (fuel > 0.0001) 
         rigidbody.velocity = Vector3(0.0, velocity, 0.0);
     else
         rigidbody.velocity = Vector3.zero;
 }
 
 function OnTriggerEnter(col: Collider){
     if (col.tag == "fuel"){
         fuel += 150.0;
     }
 }

Each time a 'fule' is triggered, you increase the amount of fuel. Each frame you burn some of that fuel. If the ship runs out of fuel, the velocity is set to 0 and gravity will pull it down. You can adjust how much fuel you get on a trigger and how fast you burn fuel. Right now the ship starts with 4 seconds of fuel and each trigger event gives the ship an addition 3 seconds of flight.

Comment
Add comment · Show 4 · 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 timelord · Jan 12, 2014 at 04:30 PM 0
Share

Hey thanks! I cant up vote you but do you have a Bitcoin Adress? Post it here ;)

avatar image robertbu · Jan 12, 2014 at 04:35 PM 0
Share

If this answer answers your question, then click on the checkmark at the top left of the answer. No Bitcoin Address, but thanks for the thought.

avatar image timelord · Jan 12, 2014 at 04:53 PM 0
Share

Is there anyway to do this with a Fixedupdate? I get an error actor must be (non-kinemactic) dynamic!. $$anonymous$$aybe somehow use transform ins$$anonymous$$d of velocity?

avatar image timelord · Jan 12, 2014 at 05:04 PM 0
Share

$$anonymous$$aybe a yield new WaitForFixedUpdate (); will work?

avatar image
0
Wiki

Answer by timelord · Jan 12, 2014 at 06:10 PM

Here is all of my code in player.js...... // Player.js // // Takes care of everything to do with controlling the player (including animations) and checks for death // // // -------------------------------------------------------------------------------

 // if you want to change how high (or low) the player jumps, change this value
 public var jumpPower : float = 35.0;
 
 // this chunk o variables are just boring variables that the functions use to function
 private var theZ : float;
 private var jumpEnabled : boolean;
 private var canMove : boolean;
 private var hit : RaycastHit;
 private var mousePos : float;
 private var xVel : float=0.0;
 private var xPos : float=0.0;
 private var yVel : float=0.0;
 private var gameEnding : boolean;
 private var didGroundHitSound : boolean;
 
 // rocket fuel, burn rate, and velocity
 private var fuel = 200.0;
 private var burnRate = 50.0; // Units per second
 private var velocity = 0.5;
 
 private var jumpSound : GameObject;
 private var fallingSound : GameObject;
 private var groundHitSound : GameObject;
 
 // we store a reference to the gameController so that we can send it important messages like when the
 // player falls too fast (game over) or when the player hits the ground (game over)
 private var gameControl : GameController;
 
 // theTransformHit stores a reference to the last transform that the player jumped on so that we can
 // destroy it if all the conditions are met to start a jump
 private var theTransformHit : Transform;
 
 // we need to make sure we're grounded before starting a new jump
 public var grounded : boolean;
 
 // to use an animated character, we parent it to the player object. so that we can still talk to it and
 // play animations, the player object needs to know where the animated character is, so we store a reference
 // to its gameobject here (accessible through the editor)
 //public var animatedCharacter : GameObject;
 
 // change this to change the players movement speed on the x
 public var maxMoveSpeed : float = 0.4;
 
 // the width of the play area (used to keep the player within the play area - if you make the game wider, change the value in gameController.js since that's where we get its value from)
 private var gameWidth : float;
 
 function Start() {
     // set gravity here
     Physics.gravity = new Vector3(0, -45, 0);
     
     // grab default position data for the z position (to fix it wherever the player starts) and to
     // get a starting point for our xPos variable, which holds the players x position
     xPos=transform.position.x;
     theZ=transform.position.z;
 
     // we use this to freeze the player at the beginning or end of the game
     jumpEnabled=false;
     
     // we use this to freeze player movement at the end of the game
     canMove=false;
     
     // grab a reference to our game controller script
     gameControl=GameObject.FindObjectOfType(GameController);
     
     // grab the game width from the gameController.js instance
     gameWidth=gameControl.gameWidth;
     
     // grab a reference to a gameObject that has audio attached to it. we use this to make a sound when
     // we bounce off a platform
     jumpSound=GameObject.Find("SOUNDFX_platform_hit");
     fallingSound=GameObject.Find("SOUNDFX_falling_down");
     groundHitSound=GameObject.Find("SOUNDFX_ground_hit");
         
     // set our game ending flag to false
     gameEnding=false;
     didGroundHitSound=false;
     
     // fix our player on the spot when the game first starts (until gameController calls our gameStart function)
     rigidbody.isKinematic=true;
     
     
     
 }
     
 
 function FixedUpdate () {
     
     
     // always assume we're NOT grounded every step (and expect to be proved wrong by raycasting etc.)
     grounded=false;
     
             
     // check to see if we're on top of a platform - here we cast two rays, one on each side of the player
     // LEFT:
     if (Physics.Raycast (transform.position- Vector3.up * 0.5 + Vector3.right * 0.5, -Vector3.up, hit, 1, 1<<9)) {
         // we found ground, so set our grounded flag to true, so that the player will jump
         grounded=true;
         if(rigidbody.velocity.y<0){
             theTransformHit=hit.transform;
         }
 
     }
     // RIGHT:
     if (Physics.Raycast (transform.position- Vector3.up * 0.5 - Vector3.right * 0.5, -Vector3.up, hit, 1, 1<<9)) {
         // we found ground, so set our grounded flag to true, so that the player will jump
         grounded=true;
         if(rigidbody.velocity.y<0){
             theTransformHit=hit.transform;
         }
     }
         
     // do jumping, if we're on top of a platform
     if(jumpEnabled){
         if(grounded && rigidbody.velocity.y<0){
             doJump();
             // send a message to the platform to tell it to destroy itself
             theTransformHit.gameObject.SendMessage("hitPlatform");
             
         }
     }
     
     // grab the mouse position and take off the width of the screen /2 so that moving the
     // mouse to the left of the window will produce a negative number and moving it to the right of
     // the window will produce a positive number
     
     mousePos = (Screen.width/2)-Input.mousePosition.x;
     
     xVel=0;
     
     // now we check the mouse position and move our player accordingly
     if(mousePos>1 || mousePos<-1){
         xVel+=(mousePos*0.02);        
     }
         
     if(canMove){
         
         // add x velocity to our position
         xPos=transform.position.x;
         
             
         if(xVel>maxMoveSpeed)
             xVel=maxMoveSpeed;
     
         if(xVel<-maxMoveSpeed)
             xVel=-maxMoveSpeed;
             
         if(xPos>gameWidth){
             xPos=gameWidth;
             rigidbody.MovePosition(Vector3(gameWidth,transform.position.y,transform.position.z));
             if(xVel>0){
                 xVel=0;
                 rigidbody.velocity.x=0;
             }
         }
         
         if(xPos<-gameWidth){
             xPos=-gameWidth;
             rigidbody.MovePosition(Vector3(-gameWidth,transform.position.y,transform.position.z));
             if(xVel<0){
                 xVel=0;
                 rigidbody.velocity.x=0;
             }
         }
         
         // set our movement velocity
         rigidbody.velocity.x=xVel*5;    
 
         // lean our player some
         transform.eulerAngles.z=-(mousePos*0.2);
     
     }
         
     fuel -= burnRate * Time.fixedDeltaTime;
     
     if (fuel < 0.0)
        fuel = 0.0;
  
     if (fuel > 0.0001)
            rigidbody.velocity = Vector3(0.0, 10, 0.0);
     else
            rigidbody.velocity = Vector3.zero;
            
         
     // if we're falling too fast, we're falling from high up and it must be game over, so we tell
     // gameController to endGame()
     if(rigidbody.velocity.y<-20 && !gameEnding){
         
         // comment this line out if you don't want the player to go upside down when he falls
         transform.eulerAngles.z=180;
         // play falling sound
         fallingSound.audio.Play();
         // tell gameController.js to end the game
         gameControl.endGame();
         gameEnding=true;
     }
 
     if(gameEnding){
         // as we fall from the sky, we move the player back toward the center of the play area. we do this
         // simply so that we know where he is going to land and theres no chance of him landing on an
         // awkward bit of scenery!
         if(transform.position.x>0)
             rigidbody.velocity.x=-5;
         if(transform.position.x<0)
             rigidbody.velocity.x=5;
     }
     
     // if we fall below the ground at the bottom (which may happen when the physics body is falling super
     // fast), we correct it and hold the player in place.
     if(transform.position.y<-4.5){
         transform.position.y=-4.5;
         rigidbody.velocity.y=0;
         rigidbody.velocity.x=0;
         
         if(!didGroundHitSound){
             groundHitSound.audio.Play();
             didGroundHitSound=true;
         }
             
         // comment this out if you don't want the player to end up upside down when it gets stuck in
         // the ground at the end of the game
         transform.eulerAngles.z=180;
         
     }
     
     transform.position.z=theZ;
     
 
 }
 
 
 function doJump(){
     // force velocity change to our 'jumpPower' value
     rigidbody.velocity.y=jumpPower;
     // play character animations
 //    animatedCharacter.animation.Rewind("jump");
 //    animatedCharacter.animation.Play("jump");
     // disable jumping temporarily (to allow the character to move away from the platform)
     jumpEnabled=false;
     // schedule jumping to be re-enabled in 0.2 seconds, once we're clear of the platform
     Invoke("enableJump",0.2);
     // play a sound
     jumpSound.audio.Play();
 }
 
 function enableJump(){
     jumpEnabled=true;
 }
 
 public function gameStart(){
     // until gameStart is called, the player is frozen in place. once this function is called, we release
     // any holds we have over it
     jumpEnabled=true;
     canMove=true;
     rigidbody.isKinematic=false;
     // start the game ... with a jump!
     doJump();
 }
 
 function OnTriggerEnter(fule: Collider){
 
     if(fule.gameObject.tag == "fule"){
     Debug.Log("We hit a fule box!");
     fuel += 150.0;
     }
 }
 
 public function gameEnd(){
     // it's game over, so we stop any jumping from happening and lock out the movement controls with canMove=false
     jumpEnabled=false;
     canMove=false;
 }
 
Comment
Add comment · 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

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

18 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

Related Questions

OnTriggerEnter AddForce 1 Answer

Adding Force to a Rigidbody through OnTriggerEnter 1 Answer

iOS game: Physics with ConstantForce 1 Answer

How do I add force in the on trigger 1 Answer

Increase Speed 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