I guys, i have a problem with a gravity simulation script
this is my script:
using UnityEngine;
using System.Collections;
public class gravity : MonoBehaviour {
public float gravitationalAcceleration; // on surface
public float gravityRadius;
public bool useExternalMass;
public float distanceVariation = 0; // variation between the gravity on surface and the gravity at gravityRadius(i.e. 0,5 is half gravity). 0 is no change
float gravityRadiusInUnit;
float unitDistanceVariation;
SphereCollider gravitySphere;
Vector3 position;
// Use this for initialization
void Start() {
gravitySphere = gameObject.AddComponent<SphereCollider>();
gravitySphere.isTrigger = true;
gravitySphere.radius = gravityRadius;
position = transform.position;
gravityRadiusInUnit = gravitySphere.radius * transform.localScale.x;
unitDistanceVariation = distanceVariation / ( gravityRadiusInUnit + transform.localScale.x );
}
// Update is called once per frame
void Update() {
position = transform.position;
}
void OnTriggerStay(Collider other) {
if( other.attachedRigidbody ) {
Vector3 otherPosition = other.transform.position;
Vector3 direction = ( position - otherPosition ).normalized;
float otherMass = 1;
if( useExternalMass ) {
otherMass = other.attachedRigidbody.mass;
}
other.attachedRigidbody.AddForce(direction * GravitationAccelerationAtPosition(otherPosition) * otherMass * Time.deltaTime, ForceMode.Acceleration);
}
}
float GravitationAccelerationAtPosition(Vector3 otherPosition) {
float distanceFromSurface/* */ = ( otherPosition - position ).magnitude - ( transform.localScale.x / 2 );
return ( 1 - ( unitDistanceVariation * distanceFromSurface ) ) * gravitationalAcceleration;
}
}
The parameters:
gravitationalAcceleration: the gravitational acceleration on the surface
gravityRadius: the radius of the gravity
useExternalMass: if true each gameobject react to gravity according to its mass
distanceVariation: variation between the gravity on surface and the gravity at gravityRadius(i.e. 0,5 is half gravity). 0 is no change
The script must be applied to a sphere.
The script creates a trigger sphere collider that applies a force to each gameobject inside it.
The script works correctly but after the “landing” the object start to “vibrate”, how can I fix this?
P.S.: Sorry for my poor english…