昨天完成了小鳥的基本控制,今天就要來設置障礙物啦,先從最基本的水管開始,讓水管能夠從右側出現,慢慢往左移動,最後離開遊戲畫面後自動消失,之後再依我自己的想法進行改造。
這裡主要需要做到兩件事情:
using UnityEngine;
public class PipeMove : MonoBehaviour
{
[Header("移動設定")]
[Tooltip("水管向左移動的速度")]
public float moveSpeed = 4f;
[Tooltip("超過這個 X 軸座標時自動銷毀(預設 -10)")]
public float deadZone = -10f;
void Update()
{
transform.position += Vector3.left * moveSpeed * Time.deltaTime;
if (transform.position.x < deadZone)
{
Destroy(gameObject);
}
}
}
移動搞好了,接下來就是讓水管生成出來。
因為只用一張圖片套兩個碰撞框,所以只需要改變生成時的高度就好。
為了增加樂趣性,請Gemini教我如何每30秒增加速度。
這裡主要需要做到兩件事情:
using UnityEngine;
public class PipeSpawner : MonoBehaviour
{
[Header("生成設定")]
[Tooltip("包含上下水管單圖的 Prefab")]
public GameObject pipePrefab;
[Tooltip("生成時間間隔(秒)")]
public float spawnRate = 2f;
[Tooltip("上下隨機偏移範圍")]
public float heightOffset = 1.5f;
[Header("動態加速設定")]
[Tooltip("當前水管移動速度")]
public float currentSpeed = 4f;
[Tooltip("每次加速增加的數值")]
public float speedIncreaseAmount = 0.8f;
[Tooltip("加速的時間間隔(預設 30 秒)")]
public float speedUpInterval = 30f;
private float spawnTimer = 0f;
private float speedTimer = 0f;
void Start()
{
SpawnPipe();
}
void Update()
{
// 1. 生成水管計時器
spawnTimer += Time.deltaTime;
if (spawnTimer >= spawnRate)
{
SpawnPipe();
spawnTimer = 0f;
}
// 2. 每 30 秒動態加速計時器
speedTimer += Time.deltaTime;
if (speedTimer >= speedUpInterval)
{
currentSpeed += speedIncreaseAmount;
// 可以稍微縮短生成時間間隔,讓水管密度保持合理
if (spawnRate > 1.0f)
{
spawnRate -= 0.1f;
}
speedTimer = 0f;
Debug.Log($"【難度提升】30秒已到!目前水管速度加快至:{currentSpeed},生成間隔:{spawnRate} 秒");
}
}
void SpawnPipe()
{
float lowestPoint = transform.position.y - heightOffset;
float highestPoint = transform.position.y + heightOffset;
Vector3 spawnPosition = new Vector3(
transform.position.x,
Random.Range(lowestPoint, highestPoint),
0
);
// 生成水管
GameObject newPipe = Instantiate(pipePrefab, spawnPosition, transform.rotation);
// 將目前最新的速度傳給剛產生的水管
PipeMove pipeMove = newPipe.GetComponent<PipeMove>();
if (pipeMove != null)
{
pipeMove.moveSpeed = currentSpeed;
}
}
}
明天大概會以更改障礙物,讓障礙物分別改為上下分開生成,並且新增道具生成。
今天主要是讓昨天只有小鳥的遊戲開始出現障礙物。
從一開始只有小鳥受到重力影響,到現在已經能夠自動生成並移動水管,遊戲也開始有了一點實際遊玩的感覺。
這次依然是先將自己想完成的功能告訴 Gemini,再讓 Gemini 協助產生程式碼,最後放進 Unity 中測試與修改。
目前遊戲還在很早期的階段,接下來會繼續一步一步完成,先把基本玩法建立起來,再看看有哪些功能可以加入。