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 TSI25 · Dec 07, 2013 at 02:54 AM · movementgravity2d-physicsunity 4.3

2d space gravity?

So I'm trying to make a 2d space game in which the player flies around by clicking on the screen. the ship automatically looks where ever the player has clicked and gains momentum in that direction for as long as the click is held down BUT if they have a lot of momentum to the left, and they merely tap right, they'll look right but still be traveling left. hopefully that makes sense.

THAT all works perfectly well, what is NOT working is gravity. The ship is flying in between a lot of planets, and the ship should be pulled toward those planets by a gravitational factor. For some reason, right now, the ship is completely unaffected by gravity. Can anyone help me figure out why? The code is in Javascript and here it is.

     if(Input.GetMouseButton(0) && refueling == false)
     {
      if(fuel < 0){
      burn = false; 
      } else { 
          
          for (var j = 0; j < 4; j++)
         {
             
         gravityVect.x = planets[j].transform.position.x - ship.transform.position.x;
         gravityVect.y = planets[j].transform.position.y - ship.transform.position.y;
         gravityVect.z = planets[j].transform.position.z - ship.transform.position.z;
         gravityVect = (gravityVect.normalized * gConstant / gravityVect.sqrMagnitude);
         sumVect.x += gravityVect.x;
         sumVect.y += gravityVect.y; 
         sumVect.z += gravityVect.z;
     }
     
         var pos = Input.mousePosition;
         pos.z = Camera.main.transform.position.y;
         pos = Camera.main.ScreenToWorldPoint(pos);
         var targetRotation = Quaternion.LookRotation(pos - transform.position);
         velocity += transform.forward * Time.deltaTime * force;
         fuel--;
         burn = true;
     
 } else {
     
     for (var k = 0; k < 4; k++)
         {
             
         gravityVect.x = planets[k].transform.position.x - ship.transform.position.x;
         gravityVect.y = planets[k].transform.position.y - ship.transform.position.y;
         gravityVect.z = planets[k].transform.position.z - ship.transform.position.z;
     
         gravityVect = (gravityVect.normalized * gConstant / gravityVect.sqrMagnitude);
     
         sumVect.x += gravityVect.x;
         sumVect.y += gravityVect.y; 
         sumVect.z += gravityVect.z;
     
     
     }
     }
     //actually moves the ship
 
     }
     sumVect = sumVect * Time.deltaTime;
     velocity.x = velocity.x + sumVect.x;
     velocity.y = velocity.y + sumVect.y;
     velocity.z = velocity.z + sumVect.z;
     transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
     
     transform.position += velocity * Time.deltaTime * 70.5;
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 robertbu · Dec 07, 2013 at 03:17 AM 1
Share

Are you sure you've cleanly dropped in the code? I don't think this will compile. As it stands, the match for 'if' statement on line 1 is the closing bracket at line 51. This leaves an unmatched 'else' on line 27. Note your lack of consistent indentation makes figuring out this code difficult. But I'm guessing that the 'if' on line 1 should be matched to the 'else' on line 27 so that the gravity of planets is applied regardless of whether the left mouse button is held down or not.

avatar image TSI25 · Dec 07, 2013 at 03:54 AM 0
Share

youre right, the actual code from that line should be and is this...

 {
      if(fuel > 0){
      burn = false; 
      }
          if(fuel > 0.0f){ 


but still....

avatar image robertbu · Dec 07, 2013 at 05:29 AM 0
Share

If this change is the 'real' code, then the 'else' on line 32 matches it. That means that your planetary gravity code on lines 29 - 42 only get executed when fuel

I suggest you take the time to correctly format your code. Use proper indentation so you can see how everything is structured. If you are using $$anonymous$$onodevelop, then putting the cursor next to a brace will highlight the matching brace. Then if you are still having trouble, edit your question and paste in the newly formatted code.

avatar image TSI25 · Dec 07, 2013 at 05:42 AM 0
Share

where do you get fuel

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by robertbu · Dec 07, 2013 at 06:18 AM

With the addition of the line you specify, here is your code correctly indented:

 #pragma strict
 
 function Update()
 {
     if(Input.GetMouseButton(0) && refueling == false)
     {
         if(fuel < 0)
         {
             burn = false; 
         } 
         if(fuel > 0.0f)
         { 
             for (var j = 0; j < 4; j++)
             {
                    gravityVect.x = planets[j].transform.position.x - ship.transform.position.x;
                    gravityVect.y = planets[j].transform.position.y - ship.transform.position.y;
                    gravityVect.z = planets[j].transform.position.z - ship.transform.position.z;
                    gravityVect = (gravityVect.normalized * gConstant / gravityVect.sqrMagnitude);
                    sumVect.x += gravityVect.x;
                    sumVect.y += gravityVect.y; 
                    sumVect.z += gravityVect.z;
             }
      
            var pos = Input.mousePosition;
            pos.z = Camera.main.transform.position.y;
            pos = Camera.main.ScreenToWorldPoint(pos);
            var targetRotation = Quaternion.LookRotation(pos - transform.position);
            velocity += transform.forward * Time.deltaTime * force;
            fuel--;
            burn = true;
         }
         else // fuel <= 0.0
         {
             for (var k = 0; k < 4; k++)
             {
                gravityVect.x = planets[k].transform.position.x - ship.transform.position.x;
                gravityVect.y = planets[k].transform.position.y - ship.transform.position.y;
                gravityVect.z = planets[k].transform.position.z - ship.transform.position.z;
          
                 gravityVect = (gravityVect.normalized * gConstant / gravityVect.sqrMagnitude);
          
                sumVect.x += gravityVect.x;
                sumVect.y += gravityVect.y; 
                sumVect.z += gravityVect.z;
             }
         }
         //actually moves the ship
     }
     sumVect = sumVect * Time.deltaTime;
     velocity.x = velocity.x + sumVect.x;
     velocity.y = velocity.y + sumVect.y;
     velocity.z = velocity.z + sumVect.z;
     transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
  
     transform.position += velocity * Time.deltaTime * 70.5;
 }

As you can see, the 'else' that contains all of your planetary gravity code matches the 'if (fuel > 0.0)'. That means your planetary code will only be executed if fuel

Comment
Add comment · Show 1 · 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 TSI25 · Dec 07, 2013 at 03:14 PM 0
Share

Robertbu, you sir. You are a genius, I can't believe I didn't see that.

avatar image
0

Answer by TSI25 · Dec 07, 2013 at 07:33 PM

So, I made the changes recommended by robertbu but the gravity is STILL not affecting the movement of the ship. This is the code that i have currently, i tried to make it indented and i added comments to help you guys read it. Help?

 if(refueling == false)
     {//<!-----------ALPHA------------------!>
     
         if(Input.GetMouseButton(0) && fuel > 0.0f)
         
             {//<!-------------------BRAVO-----------------------------------------!>
             
             //This is the case where refueling is false, the player has fuel, and the mouse is clicked. The players movement
              //is determined by previous velocity, an input acceleration vector, and gravitational pull.                
                     for (var j = 0; j < 4; j++)
                     
                     {//<!---------------CHARLIE--------------!>
                     
                         //Collects the player's distance from each planet
                         gravityVect.x = planets[j].transform.position.x - ship.transform.position.x;
                         gravityVect.y = planets[j].transform.position.y - ship.transform.position.y;
                         gravityVect.z = planets[j].transform.position.z - ship.transform.position.z;
                         
                         //creates a gravity vector representing the planet's distance from the player
                         gravityVect = (gravityVect.normalized * gConstant / gravityVect.sqrMagnitude);
                         
                         //adds the gravity vector to a 'sum vector' representing the pull of all planets
                         sumVect.x += gravityVect.x;
                         sumVect.y += gravityVect.y;
                         sumVect.z += gravityVect.z;
                         
                     }//</ --------------------CHARLIE---------------->
                     
                  //detects where on the screen the player has clicked.
                 var pos = Input.mousePosition;
                 pos.z = Camera.main.transform.position.y;
                 pos = Camera.main.ScreenToWorldPoint(pos);
                 
                 //determines where the player's ship should rotate to look.
                 var targetRotation = Quaternion.LookRotation(pos - transform.position);
                 
                 // determines the players velocity based entirely on clicking
                 velocity += transform.forward * Time.deltaTime * force;
                 
                 //subtracts fuel every frame, and plays the 'burn' noise
                 fuel--;
                 burn = true;
                 
                 //makes the sumVect created earlier into an actual acceleration vector
                 sumVect = sumVect * Time.deltaTime;
                 
                 //adds the sumVect to the player's acceleration vector
                 velocity.x += sumVect.x;
                 velocity.y += sumVect.y;
                 velocity.z += sumVect.z;
                 
                 //this code actually moves the player through space, and allows the player to rotate.
                 transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
                 transform.position += velocity * Time.deltaTime * 70.5;
                 
                 
                 }//</ ------------BRAVO-----------------------------------------------------> 
                 
                 else {//<!-------------------DELTA------------------------------>
                 
                         //This is the case where refueling is false and the mouse is not clicked.
                         //The players movement is determined by previous velocity, and gravitational pulls alone.
                         for (var k = 0; k < 4; k++)
                         
                             {//<!---------------EPSILON----------------->
                             
                                //Collects the player's distance from each planet   
                                 gravityVect.x = planets[k].transform.position.x - ship.transform.position.x;
                                 gravityVect.y = planets[k].transform.position.y - ship.transform.position.y;
                                 gravityVect.z = planets[k].transform.position.z - ship.transform.position.z;
                                 
                                 //creates a gravity vector representing the planet's distance from the player
                                 gravityVect = (gravityVect.normalized * gConstant / gravityVect.sqrMagnitude);
                                 
                                 //adds the gravity vector to a 'sum vector' representing the pull of all planets
                                 sumVect.x += gravityVect.x;
                                 sumVect.y += gravityVect.y;
                                 sumVect.z += gravityVect.z;
                                 
                             }//</ ---------------EPSILON---------------->
                         
                         //makes the sumVect created earlier into an actual acceleration vector
                         sumVect = sumVect * Time.deltaTime;
                                     
                         //sets the player's current acceleration vector to the sumVect        
                         velocity.x = sumVect.x;
                         velocity.y = sumVect.y;
                         velocity.z = sumVect.z;
                         
                         //actually moves the player through space.
                         transform.position += velocity * Time.deltaTime * 70.5;
                         
                         }//</ ------------------DELTA-------------------------------->
 
     }//</ ---------------ALPHA-------------------->



I have literally no idea why gravity isn't taking effect at this point. The gConstant is 1000, and the ship moves just fine - there just isnt any gravity.

Comment
Add comment · Show 1 · 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 robertbu · Dec 08, 2013 at 05:53 AM 0
Share

Your new structure has the planets only being applied if the mouse is not down and there is fuel. Not sure if that is the way you want it. I would remove the 'else' and its brackets and delete line 54. That is planetary gravity should be applied every frame.

But that does not figure out why you are not seeing any effect. You need tp place a Debug.Log() around line 79 to take a look at the value of sumVect and velocity...make sure the ratio of the two is about what you would expect for different planetary distances.

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

16 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

Related Questions

How to walk on a circular object unity 2d 2 Answers

Object "crawling" over floor, how? 2 Answers

Limit speed on x axis when applying force with gravity 0 Answers

CharacterController.Move uses gravity even though it shouldn't 1 Answer

2D Objects interacting with colliders and gravity seemingly at random 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