1 回答

TA貢獻2011條經驗 獲得超2個贊
主要問題
主要問題是您的for 循環。它只能用于更新 UI - 不能多次調用您的移動和場景重新加載!您應該提前關閉for循環。
for (int i = 0; i < hearts.Length; i++)
{
? ? // you can also reduce these to single lines
? ? hearts[i].enabled = i < numOfHearts;
? ? if(i < numOfHearts) hearts[i].sprite = i < health ? heartFull : heartEmpty;? ??
} // <-- ALREADY CLOSE IT HERE
if(health <= 0) ...
...
位置夾緊
你對位置的夾緊極不安全!想象一下當前位置是?3.1
?仍然是?< maxHeight
,因此您添加?Yincrement
?一次,結果是最大可能高度 < /span>6.3
!這不是你想要的。
您應該直接鉗位targetPosition
,而不是鉗位當前transform.position
。例如,您可以使用?Mathf.Clamp
?確保?targetPos.y
?始終保持在給定范圍內。
此外,由于這兩種情況都執行非常相似的操作,因此我會使用簡單的?int
?變量來設置方向,將其減少為僅一次移動:
...
transform.position = Vector2.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
var move = 0;
var targetPosY = targePos.y;
if (Input.GetKeyDown(KeyCode.UpArrow) && targetPosY < maxHeight)
{
? ? move = 1;
}
else if (Input.GetKeyDown(KeyCode.DownArrow) && targetPosY > minHeigth)
{
? ? move = -1;
}
// Handle the movement according to the direction
// in one single code block for both directions
if(move != 0)
{
? ? Instantiate(effect, transform.position, Quaternion.identity);
? ? // increase/decrease the targetPosY according to the move direction
? ? targetPosY += move * Yincrement;
? ? // Now make sure it is within the range
? ? targetPosY = Mathf.Clamp(targetPosY, minHeight, maxHeight);
? ? // finally assign the new target position
? ? targetPos = new Vector2(transform.position.x, targetPosY);
}
- 1 回答
- 0 關注
- 145 瀏覽
添加回答
舉報