所以,我的这段代码有点问题。
private void ReDeal()
{
if (!userInput.first)
{
userInput.FirstSelected(GameObject.Find(bottoms[0][0]));
bottoms[0].Remove(userInput.slot1.name);
GameObject cardToDestroy = GameObject.Find(userInput.slot1.name);
//Move card down before destroy
Destroy(cardToDestroy);
bottoms[0].Add(deck.Last<string>());
deck.RemoveAt(deck.Count - 1);
}
}
目前,它的工作原理是这样的,游戏对象(cardToDestroy)被摧毁了。我想做的是将Gameobject按Y轴向下移动,使其从屏幕上 "滑落",然后将其销毁。尝试用while循环和Vector2.MoveTowards或Vector2.Lerp来实现,但没有成功。我似乎无法让MoveTowards在VOID中工作。
好吧,我实际上解决了这个问题,我用while循环创建了一个IEnumerator。
IEnumerator MoveCard(GameObject card, int cardIndex)
{
Vector2 startPosition = card.transform.position;
Vector3 stopPOsition = new Vector2(startPosition.x, startPosition.y - 4);
while(Vector2.Distance(card.transform.position, stopPOsition) > 0.1f)
{
float step = 10f * Time.deltaTime;
card.transform.position = Vector2.MoveTowards(card.transform.position, stopPOsition, step);
yield return null;
}
Destroy(card);
}
然后我在ReDeal()void中调用这个IEnumerator作为Coroutine。
private void ReDeal()
{
if (!userInput.first)
{
userInput.FirstSelected(GameObject.Find(bottoms[0][0]));
bottoms[0].Remove(userInput.slot1.name);
GameObject cardToDestroy = GameObject.Find(userInput.slot1.name);
StartCoroutine(MoveCard(cardToDestroy, 0));
}
}
你可以通过使用coroutine来实现这个效果。
private void ReDeal()
{
if (!userInput.first)
{
userInput.FirstSelected(GameObject.Find(bottoms[0][0]));
bottoms[0].Remove(userInput.slot1.name);
GameObject cardToDestroy = GameObject.Find(userInput.slot1.name);
//Move card down before destroy
StartCoroutine(Destroy());
bottoms[0].Add(deck.Last<string>());
deck.RemoveAt(deck.Count - 1);
}
}
private float movementFactor = 1.0f;
private float maximumDistance = 15f;
private IEnumerator Destroy(GameObject go, float distance)
{
float accumulatedDistance = 0;
float go_x = go.transform.position.x;
float go_z = go.transform.position.z;
if (accumulatedDistance < distance)
{
go.transform.position -= new Vector3(0,movementFactor,0);
yield return null;
}
Destroy(go);
}
对于这种事情,你最好的朋友就是Coroutine。
IEnumerator SlideAndDestroy(Card cardToDestroy)
{
float velocity = -1;
while(transform.position.y > offscreenDistance)
{
transform.position += new Vector3(0, velocity * Time.deltaTime, 0);
yield return new WaitForSeconds(Time.deltaTime);
}
Destroy(cardToDestroy);
yield return null;
}
然后在你想销毁你的卡的地方
StartCoroutine(SlideAndDestroy(cardToDestroy));