I have used processing a lot for my college projects and I want to achieve something like this where the objects don’t collide.
http://natureofcode.com/book/chapter-2-forces/#chapter02_example6
So I wrote the exact same code in Unity the force seemed to work but the objects tend to stick to one an other.
This is my code:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Gravity : MonoBehaviour {
public static float range = 100;
public GameObject parent;
public float maxDistance = 25.0f;
public float minDistance = 5.0f;
// gravitational constant
public float G = 0.4f;
void Update()
{
Vector3 force = transform.position - parent.transform.position;
float distance = force.magnitude;
// constrain the distance between
if(distance < minDistance)
distance = minDistance;
else if(distance > maxDistance)
distance = maxDistance;
// calculate the direction of the force
force.Normalize();
// calculate the strength of the force
float strength = (G * rigidbody.mass * parent.rigidbody.mass) / distance * distance;
// multiply the direction of the force with the strength
force = force * strength * -1;
// adding the force to the rigidbody
rigidbody.AddForce(force);
Debug.Log("Force: " + force);
}
Thanks in advance.