Reputation: 612
I have a Sphere Object falling down from the top of the screen (Sphere position y = 5). And I have a Cube with "isTrigger = true" and "Mesh renderer = false" and the position with "y = 0.5" (0.5 = center of the cube). You can't see the cube.
The Sphere is now falling. Now I want, when the sphere touches the cube, that the sphere is slowing down to zero (without reverse). I want a attenuation/damping.
I tried this example without success: http://docs.unity3d.com/Documentation/ScriptReference/Vector3.SmoothDamp.html
// target = sphere object
public Transform target;
public float smoothTime = 0.3F;
private Vector3 velocity = Vector3.zero;
private bool slowDown = false;
void Update () {
if (slowDown) {
Vector3 targetPosition = target.TransformPoint(new Vector3(0, 0, 0));
transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, smoothTime);
}
}
void OnTriggerEnter(Collider other) {
if (other.name == "Sphere") {
slowDown = true;
}
}
The script is attached to the cube.
Upvotes: 0
Views: 3649
Reputation: 36
You may want to try this approach:
// We will multiply our sphere velocity by this number with each frame, thus dumping it
public float dampingFactor = 0.98f;
// After our velocity will reach this threshold, we will simply set it to zero and stop damping
public float dampingThreshold = 0.1f;
void OnTriggerEnter(Collider other)
{
if (other.name == "Sphere")
{
// Transfer rigidbody of the sphere to the damping coroutine
StartCoroutine(DampVelocity(other.rigidbody));
}
}
IEnumerator DampVelocity(Rigidbody target)
{
// Disable gravity for the sphere, so it will no longer be accelerated towards the earth, but will retain it's momentum
target.useGravity = false;
do
{
// Here we are damping (simply multiplying) velocity of the sphere whith each frame, until it reaches our threshold
target.velocity *= dampingFactor;
yield return new WaitForEndOfFrame();
} while (target.velocity.magnitude > dampingThreshold);
// Completely stop sphere's momentum
target.velocity = Vector3.zero;
}
I am assuming here that your have a Rigidbody atached to your sphere and it's falling to the 'natural' gravity (if not - simply add Rigidbody component to your sphere, no further tweaking required) and you are familiar with coroutines, if not - take a look at this manual: http://docs.unity3d.com/Documentation/Manual/Coroutines.html
Coroutines can be quite helpful, when used wisely :)
Upvotes: 2