Search Unity

  1. Get the latest news, tutorials and offers directly to your inbox with our newsletters. Sign up now.
    Dismiss Notice

Help Wanted Attraction of objects

Discussion in 'Scripting' started by AnSupp, Apr 22, 2021.

  1. AnSupp

    AnSupp

    Joined:
    Apr 12, 2021
    Posts:
    4
    Hello everyone! There is a script for the attraction of two objects - spheres.
    Faced several problems in it at once


    Code (CSharp):
    1. private HashSet<Rigidbody> affectedBodies = new HashSet<Rigidbody>();
    2.     private Rigidbody componentRigidbody;
    3.     // Start is called before the first frame update
    4.     void Start()
    5.     {
    6.         componentRigidbody = GetComponent<Rigidbody>();
    7.     }
    8.     private void OnTriggerEnter(Collider other)
    9.     {
    10.         if ((other.attachedRigidbody != null))
    11.             {
    12.                 affectedBodies.Add(other.attachedRigidbody);
    13.             }
    14.     }
    15.     private void OnTriggerExit(Collider other)
    16.     {
    17.         if (other.attachedRigidbody != null)
    18.         {
    19.             affectedBodies.Remove(other.attachedRigidbody);
    20.         }
    21.     }
    22.     // Update is called once per frame
    23.     void Update()
    24.     {
    25.         foreach (Rigidbody body in affectedBodies)
    26.         {
    27.             Vector3 directionToSphere = (transform.position - body.position).normalized;
    28.             float distance = (transform.position - body.position).magnitude;
    29.             float strength = body.mass * componentRigidbody.mass / distance;
    30.             body.AddForce(directionToSphere * strength);
    31.         }
    32.     }
    Because of this part of the script, the balls behave inadequately: when launched, instead of being attracted to each other, they jump up, and then they start to wind in different directions


    Code (CSharp):
    1. Vector3 directionToSphere = (transform.position - body.position).normalized;
    2.             float distance = (transform.position - body.position).magnitude;
    3.             float strength = body.mass * componentRigidbody.mass / distance;
    4.             body.AddForce(directionToSphere * strength);

    But, if you replace "strength" with a constant, then this will not happen.

    And still it is not possible to refer to the object by the tag - objects with tag "11" don't react

    Code (CSharp):
    1. private void OnTriggerEnter(Collider other)
    2.     {
    3.        if (other.gameObject.CompareTag("11"))
    4.        {
    5.             if ((other.attachedRigidbody != null))
    6.             {
    7.                 affectedBodies.Add(other.attachedRigidbody);
    8.             }
    9.        }
    10.     }
     
  2. AnSupp

    AnSupp

    Joined:
    Apr 12, 2021
    Posts:
    4
    "distance" gives strange values
     
unityunity