Замедлить объект?

У меня есть объект сферы, падающий сверху экрана (позиция сферы y = 5). И у меня есть куб с «isTrigger = true» и «Mesh renderer = false» и положение с «y = 0,5» (0,5 = центр куба). Вы не можете видеть куб.

Теперь Сфера падает. Теперь я хочу, чтобы когда сфера касается куба, сфера замедлялась до нуля (без реверса). Я хочу затухание / демпфирование.

Я попробовал этот пример без успеха: 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;
}
}

Скрипт прилагается к кубу.


person Johnny    schedule 26.02.2014    source источник
comment
сфера имеет жесткое тело?   -  person Hamdullah shah    schedule 26.02.2014


Ответы (1)


Вы можете попробовать этот подход:

// 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;
}

Я предполагаю, что у вас есть Rigidbody, прикрепленный к вашей сфере, и он падает под действием «естественной» гравитации (если нет — просто добавьте компонент Rigidbody к вашей сфере, никаких дополнительных настроек не требуется), и вы знакомы с сопрограммами, если нет — возьмите взгляните на это руководство: http://docs.unity3d.com/Documentation/Manual/Coroutines.html

Корутины могут быть весьма полезными, если их использовать с умом :)

person Shironecko    schedule 27.02.2014