2014-02-26 112 views
0

我有一個Sphere對象從屏幕頂部向下傾斜(球體位置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; 
} 
} 

腳本連接到多維數據集。

+0

領域有一個剛體? –

回答

2

你可以試試這個方法:

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

我這裏假設你有一個剛體atached到您的球體,它的墜落到「自然」重力(如果不是 - 只需剛體組件添加到你的球,沒有進一步的調整需要),你所熟悉的協程,如果不是 - 看看本手冊:http://docs.unity3d.com/Documentation/Manual/Coroutines.html

協程可以說是相當有幫助的,明智地使用時:)