Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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 /
  • Help Room /
avatar image
1
Question by captmemory12 · Jun 10, 2017 at 06:29 PM · c#physicsrigidbodygravity

Adding Gravity to a game object to make a black hole sucking effect.

Hello, I was trying to make a black hole effect with this script I found. The only problem is that the rigid bodies it sucks in orbit around the object for a little bit but I want them to just directly go towards it. The game objects getting sucked in are moving in the scene so I know that that is one of the problems.

 using UnityEngine;
 
 namespace _Scripts
 {
     /// <summary>
     /// Gravity behavioura added to object
     /// </summary>
     public class WormHoleMaker : MonoBehaviour
     {
         public float PullRadius; // Radius to pull
         public float GravitationalPull; // Pull force
         public float MinRadius; // Minimum distance to pull from
         public float DistanceMultiplier; // Factor by which the distance affects force
 
         public LayerMask LayersToPull;
 
         // Function that runs on every physics frame
         void FixedUpdate()
         {
             Collider[] colliders = Physics.OverlapSphere(transform.position, PullRadius, LayersToPull);
 
             foreach (var collider in colliders)
             {
                 Rigidbody rb = collider.GetComponent<Rigidbody>();
 
                 if (rb == null) continue; // Can only pull objects with Rigidbody
 
                 Vector3 direction = transform.position - collider.transform.position;
 
                 if (direction.magnitude < MinRadius) continue;
 
                 float distance = direction.sqrMagnitude * DistanceMultiplier + 1; // The distance formula
 
                 // Object mass also affects the gravitational pull
                 rb.AddForce(direction.normalized * (GravitationalPull / distance) * rb.mass * Time.fixedDeltaTime);
             }
         }
 
     }
 }
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
1

Answer by DenisGLabrecque · Oct 17, 2018 at 01:58 AM

I think you may want to remove the part with direction.sqrMagnitude, as the script is getting the root of the distance to apply the force over. This is an exponential curve instead of a linear acceleration (which seems to be what you want).

I also have a script you may try. To use it, create an empty game object that represents where the black hole is, and add a sphere collider to that empty game object to represent the area of attraction of that black hole. Be sure to check IsTrigger on the sphere collider so the sphere collider acts as an area rather than a giant wall. Then add this script to the black hole game object:

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

   [RequireComponent(typeof(SphereCollider))]
   public class Gravity : MonoBehaviour {

      [SerializeField] public float GRAVITY_PULL = .78f;

      public static float m_GravityRadius = 1f;

      void Awake()
      {
         m_GravityRadius = GetComponent<SphereCollider>().radius;
      }

      /// <summary>
      /// Attract objects towards an area when they come within the bounds of a collider.
      /// This function is on the physics timer so it won't necessarily run every frame.
      /// </summary>
      /// <param name="other">Any object within reach of gravity's collider</param>
      void OnTriggerStay(Collider other)
      {
         if(other.attachedRigidbody)
         {
            float gravityIntensity = Vector3.Distance(transform.position, other.transform.position) / m_GravityRadius;

            other.attachedRigidbody.AddForce((transform.position - other.transform.position) * gravityIntensity * other.attachedRigidbody.mass * GRAVITY_PULL * Time.smoothDeltaTime);

            Debug.DrawRay(other.transform.position, transform.position - other.transform.position);
         }
      }
   }

For a stronger attraction, increase the GRAVITY_PULL constant.

Comment
Add comment · Show 2 · 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 tonyrobots · Apr 17, 2020 at 11:26 PM 0
Share

This is terrific, thanks @DenisGLabrecque. Very nearly what I was looking for, except I am working in 2D. In case anyone else stumbles upon this, and want something analogous but for 2d, this may save you a little time:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 [RequireComponent(typeof(CircleCollider2D))]
 
 
 public class Gravity : $$anonymous$$onoBehaviour
 {
     [SerializeField] public float GRAVITY_PULL = .78f;
     public static float m_GravityRadius = 1f;
     void Awake()
     {
         m_GravityRadius = GetComponent<CircleCollider2D>().radius;
     }
     /// <summary>
     /// Attract objects towards an area when they come within the bounds of a collider.
     /// This function is on the physics timer so it won't necessarily run every frame.
     /// </summary>
     /// <param name="other">Any object within reach of gravity's collider</param>
     void OnTriggerStay2D(Collider2D other)
     {
         if (other.attachedRigidbody)
         {
             float gravityIntensity = Vector3.Distance(transform.position, other.transform.position) / m_GravityRadius;
             other.attachedRigidbody.AddForce((transform.position - other.transform.position) * gravityIntensity * other.attachedRigidbody.mass * GRAVITY_PULL * Time.smoothDeltaTime);
             Debug.DrawRay(other.transform.position, transform.position - other.transform.position);
         }
     }
 }
avatar image DenisGLabrecque · Apr 18, 2020 at 12:01 AM 0
Share

@tonyrobots Great to see it used! There is a problem with it in that using more than one collider results in multiplying gravity by the number of colliders (1 collider = 1x gravity, 2 colliders = 2x gravity). If that works for you, then great!

Otherwise, the force must be added to a rigidbody individually. I do have an updated setup that uses the principle, but it's more inter-related with other scripts: https://github.com/DenisLabrecque/Warglobe/blob/master/Assets/Scripts/Gravity.cs

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

390 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 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 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 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 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 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

Why my gravity direction is rotating with transform.rotation? 1 Answer

Rigid body robot animation 0 Answers

GravityBody hides Rigidbody 1 Answer

Rigidbody doesn't seem to apply gravity 1 Answer

JointDriveMode is obsolete, any alternatives? 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