在 C# Windows Forms 應用程式中,實作一個可透過滑鼠控制移動的飛機遊戲原型,是初學者熟悉事件驅動程式設計、繪圖機制與遊戲迴圈的絕佳練習。本文將完整說明如何建立專案、處理滑鼠事件、繪製飛機圖片,並提供可直接執行的程式碼範例。
DoubleBuffered = true 以減少閃爍。plane.png),加入專案資源或放置於執行目錄。public partial class Form1 : Form
{
private Image planeImg;
private Point planePos = new Point(200, 200);
private const int PlaneWidth = 60, PlaneHeight = 60;
public Form1()
{
InitializeComponent();
this.DoubleBuffered = true;
planeImg = Image.FromFile("plane.png"); // 或從 Resources 讀取
this.MouseMove += Form1_MouseMove;
this.Paint += Form1_Paint;
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
// 讓飛機中心對準滑鼠座標
planePos.X = e.X - PlaneWidth / 2;
planePos.Y = e.Y - PlaneHeight / 2;
this.Invalidate(); // 觸發重繪
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawImage(planeImg, planePos.X, planePos.Y, PlaneWidth, PlaneHeight);
}
}
Timer 控制遊戲主迴圈,實現自動發射子彈、敵機生成與碰撞偵測。KeyDown 事件支援鍵盤輔助控制。Q: 圖片不顯示? 確認檔案路徑正確,或改用 Properties.Resources.plane 讀取嵌入資源。
Q: 移動有延遲? 開啟 DoubleBuffered 並避免在 Paint 事件中執行複雜運算。
完整範例程式碼可參考 GitHub 專案:C# Mouse Controlled Plane Demo。