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 Jaidan · Feb 20, 2015 at 09:58 AM · gravityplanetsfauxgravity

Unity3D PlanetGravity system? C#

alt text

So as you can soo from the diagram i drew above, i want to emulate a sort of gravity with more than one planet into my game. I have check out Sebastians video about making the correct gravity, found here: https://www.youtube.com/watch?v=TicipSVT-T8

But the problem is, i am going to have more than one planet in my game. I already have all the scripts and i have one planet set up, like the "Planet" in the diagram. It works so that where ever the player is, they will always be sucked into the planet (the one on the right) But i want to have another planet aswell, but if i ust added this, the the game would mess up

As first i was confused but then i made this diagram to explain. When the playr is at point 1, i want it to be sucked into the "Planet" and when it is at point 2, i want it to be sucked into the "NewPlanet".

Would i do this: Have two variables such as:

 float playerToPlanet = Vector3.Distance (Transform.position, planetGrass.transform.position);
 float playerToNewPlanet = Vector3.Distance (Transform.position, planetIce.transform.position);

and then check for:

If the distance from "Planet" to player is smaller than the distance from the "NewPlanet" to player, then use the "planet" gravity - ust like in the bottom part of the diargram And then the same this but vice versa for the if the player was closer to the "NewPlanet"

I am a beginner a unity and i dont really know alot of stuff, so if someone could fully explain what to do, with examples, that would be greatly appreciated

My code:

using UnityEngine; using System.Collections;

public class GravityAttractor : MonoBehaviour {

 public float gravity = -10f;
 
 public void Attract(Transform body)
 {
     Vector3 targetDir = (body.position - transform.position).normalized;
     Vector3 bodyUp = body.up;

     body.rotation = Quaternion.FromToRotation (bodyUp, targetDir) * body.rotation;
     body.rigidbody.AddForce (targetDir * gravity);
 }

}

using UnityEngine; using System.Collections;

[RequireComponent (typeof (Rigidbody))] public class GravityBody : MonoBehaviour {

 GravityAttractor planet;
 
 void Awake () 
 {
     planet = GameObject.FindGameObjectWithTag("Planet").GetComponent<GravityAttractor>();
     rigidbody.useGravity = false;
     rigidbody.constraints = RigidbodyConstraints.FreezeRotation;
 }
 
 void FixedUpdate () 
 {
     planet.Attract (transform);
 }

}

using UnityEngine; using System.Collections;

public class FirstPersonController : MonoBehaviour {

 public float mouseSensitivityX = 250f;
 public float mouseSensitivityY = 250f;
 public float walkSpeed;
 public float runSpeed;
 public float jumpForce;
 public LayerMask groundedMask;

 Transform cameraT;
 float verticalLookRotation;

 Vector3 moveAmount;
 Vector3 smoothMoveVelocity;

 bool grounded;
 bool doubleJump = false;

 void Start () 
 {
     Screen.showCursor = false;
     cameraT = Camera.main.transform;
 }

 void Update () 
 {
     transform.Rotate (Vector3.up * Input.GetAxis ("Mouse X") * Time.deltaTime * mouseSensitivityX);
     verticalLookRotation += Input.GetAxis("Mouse Y") * Time.deltaTime * mouseSensitivityY;
     verticalLookRotation = Mathf.Clamp (verticalLookRotation, -80, 80);
     cameraT.localEulerAngles = Vector3.left * verticalLookRotation;

     Vector3 moveDir = new Vector3 (Input.GetAxisRaw ("Horizontal"), 0, Input.GetAxisRaw ("Vertical")).normalized;
     Vector3 targetMoveAmount = moveDir * walkSpeed;


     if (Input.GetKey(KeyCode.LeftShift) && grounded)
     {
         targetMoveAmount = moveDir * runSpeed;
     }

     moveAmount = Vector3.SmoothDamp (moveAmount, targetMoveAmount, ref smoothMoveVelocity, 0.15f);


     if (Input.GetButtonDown ("Jump") && (grounded || !doubleJump)){
         {
             rigidbody.AddForce(transform.up * jumpForce);

             if(!doubleJump && !grounded)
                 doubleJump = true;
         }
     }

     if (grounded)
         doubleJump = false;


     grounded = false;
     Ray ray = new Ray (transform.position, -transform.up);
     RaycastHit hit;

     if (Physics.Raycast (ray, out hit, 1 + 0.1f,  groundedMask)) 
     {
         grounded = true;
     }
 }

 void FixedUpdate()
 {
     rigidbody.MovePosition (rigidbody.position + transform.TransformDirection (moveAmount) * Time.fixedDeltaTime);
 }

}

dia.png (50.7 kB)
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
0

Answer by Alexander Jurow · Apr 10, 2015 at 12:26 PM

do in Planet Sphere Collider Is Trigger on (then Scale this), and Add Component Mesh Colleder then add Code in "GravityBody.cs":

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

[RequireComponent(typeof(Rigidbody))] public class GravityBody : MonoBehaviour { public List target; public GravityAttractor selectedTarget;

 void Awake()
 {
     target = new List<GravityAttractor>();
     selectedTarget = null;

     AddPlanets();
     
     GetComponent<Rigidbody>().useGravity = false;
     GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeRotation;
 }

 void FixedUpdate()
 {
     selectPlanet();
     if (selectedTarget != null)
     {
         selectedTarget.Attract(transform);
        Debug.Log("Hallo !!!");
     }
 }


 public void AddPlanets()
 {
     GameObject[] go = GameObject.FindGameObjectsWithTag("Planet");

     foreach (GameObject planet in go)
        target.Add(planet.GetComponent<GravityAttractor>());
 }

 public void selectPlanet()
 {
     for (int i = 0; i <target.Count; i++)
     {
         if (target[i].inAtmosfhere)
         {
             selectedTarget = target[i];
             return;
         }
         else
             selectedTarget = null;
     }
 }

}

and in Code "GravityAttracor.cs":

using UnityEngine; using System.Collections;

public class GravityAttractor : MonoBehaviour { public bool inAtmosfhere = false;

 public float gravity = -10f;

 void OnTriggerEnter(Collider col)
 {
     inAtmosfhere = true;
 }


 void OnTriggerStay(Collider col)
 {
     inAtmosfhere = true;
 }

 void OnTriggerExit(Collider col)
 {
     inAtmosfhere = false;
 }


 public void Attract(Transform body)
 {
     
   Vector3 targetDir = (body.position - transform.position).normalized;
     Vector3 bodyUp = body.up;

     body.rotation = Quaternion.FromToRotation(bodyUp, targetDir) * body.rotation;
     body.GetComponent<Rigidbody>().AddForce(targetDir * gravity);

  }

}

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

21 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

Related Questions

Faux Gravity, spinning at bottom of sphere 0 Answers

Rigidbody gravity between planets 1 Answer

Implementing FPS view into locomotion planet walk 1 Answer

faux gravity in 2d game 3 Answers

Custom gravity based on normal vector and rigidbody.addForce 2 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