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 01:32 PM · triggergravitymeshcolliderfauxgravity

My Planet Gravity system not working? C#

I have a system setup to try and detect when a player is in a specific planets gravity, but for some reason its not working. I will have my code below I have empty game objects with mesh colliders and rigidbodys on them to emulate the atmosphere and when they enter a certain one, they need to be pulled in. Here is the code i have: Thank you

using UnityEngine; using System.Collections;

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

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

}

using UnityEngine; using System.Collections;

public class PlanetGravityEnter : MonoBehaviour {

 public float gravity = -10f;

 public void OnTriggerStay (Collider body)
 {
     Attract (transform);
 }

 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;

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);
 }

}

Comment
Add comment · Show 31
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 kbaloch · Feb 20, 2015 at 01:39 PM 0
Share

what not working ? is it not attracting game object ? or can you mention where is problem in code?

avatar image siaran · Feb 20, 2015 at 02:17 PM 0
Share

Why do so few people write comments in their code :( it's hard to understand other peoples code if there are no comments.

Anyway I'm not entirely sure how you are trying to accomplish what I think you want but since it seems fairly simple I'll just write some code on how I'd do it...

 using UnityEngine;
 using System.Collections.Generic;
             
 public class Attract : $$anonymous$$onoBehaviour {
             
  public List<Rigidbody> inGravityWell = new List<Rigidbody>();
             
  public float gravity;
         
  void OnTriggerEnter(Collider c){
              inGravityWell.Add(c.rigidbody);
         }
         
  void OnTriggerExit(Collider c){
             inGravityWell.Remove(c.rigidbody);
         }
         
  void FixedUpdate(){
          for(int i = 0; i < inGravityWell.Count; i++){
            Vector3 force = (transform.position-inGravityWell[i].position).normalized * gravity;
            inGravityWell[i].AddForce(force, Force$$anonymous$$ode.Force); 
          }
  }   
 }

No guarantees that this works, I just wrote it without any testing, but attaching that script to any planet should make it pull in any rigidbodies that enter it's trigger area.

avatar image Jaidan · Feb 20, 2015 at 03:05 PM 0
Share

The code does not work, what do i need to do, such as do i need to modify my other scripts?

avatar image siaran · Feb 20, 2015 at 03:12 PM 0
Share

Does the code not do what you expect or does it generate errors? some things that could be going wrong with what I wrote: 1) OnTriggerEnter is not called. Are rigidbodies added to the list?

2) The gravity is too low to have any noticable effect.

3) I should have used a different Force$$anonymous$$ode.

avatar image Jaidan · Feb 20, 2015 at 03:30 PM 0
Share

I have the script :

using UnityEngine; using System.Collections.Generic;

public class Attractor : $$anonymous$$onoBehaviour {

 public List <Rigidbody> inGravityWell = new List <Rigidbody> ();

 public float gravity = -10f;

 void OnTriggerEnter (Collider c){

     inGravityWell.Add (c.rigidbody);
 }

 void OnTriggerExit (Collider c){

     inGravityWell.Remove (c.rigidbody);
 }

 void FixedUpdate(){

     for (int i = 0; 1 < inGravityWell.Count; i++) {

         Vector3 force = (transform.position - inGravityWell [i].position).normalized * gravity;
         inGravityWell [i].AddForce(force, Force$$anonymous$$ode.Force);
     } 
 }

}

and:

using UnityEngine; using System.Collections;

public class Body : $$anonymous$$onoBehaviour {

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

}

alt text

untitled-2.png (180.8 kB)
Show more comments

1 Reply

· Add your reply
  • Sort: 
avatar image
1

Answer by MonkeyHood · Feb 20, 2015 at 03:13 PM

 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);
  }

I think your problem is in your target dir. To correctly generate direction vectors, the calculation is heads - tails or (destination - currentPosition). If you want to attract towards the planet, you must do

 Vector3 targetDir = (transform.position - body.position).normalized;

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

23 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

Related Questions

Mesh Collider Does Not Working 1 Answer

Apply gravity to parents 1 Answer

Implementing FPS view into locomotion planet walk 1 Answer

First Person Controler and Water wont effect gravity 1 Answer

faux gravity in 2d game 3 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