首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

WPF/Silverlight 遊戲開發教程(三十七之二):地圖切片自適應區域載入核心邏輯

     編輯:關於C語言

主角始終在視窗正中(左 400、頂 300),依邊緣法計算主角所在切片代號。例:主角在 2_3.jpg,需載入周圍 9 片:1_2、2_2、3_2、1_3、2_3、3_3、1_4、2_4、3_4。切片填充必須自適應,即時依主角位置換片。

核心代碼實現

修改地圖 Surface 初始化

Canvas MapSurface;
int mapSectionWidth, mapSectionHeight, mapSectionXNum, mapSectionYNum;

private void InitMapSurface(XElement args)
{
    MapSurface = new Canvas() { Width = Convert.ToDouble(args.Attribute("Width").Value), Height = Convert.ToDouble(args.Attribute("Height").Value) };
    Add(MapSurface);
    mapSectionWidth = Convert.ToInt32(args.Attribute("SectionWidth").Value);
    mapSectionHeight = Convert.ToInt32(args.Attribute("SectionHeight").Value);
    mapSectionXNum = (int)(MapSurface.Width / mapSectionWidth);
    mapSectionYNum = (int)(MapSurface.Height / mapSectionHeight);
}

切片定位變數與觸發機制

int _leaderSectionX;
public int leaderSectionX { get { return _leaderSectionX; } set { if (_leaderSectionX != value) { _leaderSectionX = value; ChangeMapSection(); } } }
int _leaderSectionY;
public int leaderSectionY { get { return _leaderSectionY; } set { if (_leaderSectionY != value) { _leaderSectionY = value; ChangeMapSection(); } } }

ChangeMapSection 更新呈現切片

Image mapSection;
int startSectionX, startSectionY, endSectionX, endSectionY;

private void ChangeMapSection()
{
    MapSurface.Children.Clear();
    if (leaderSectionX == 0) { startSectionX = 0; endSectionX = 2; }
    else if (leaderSectionX == mapSectionXNum - 1) { startSectionX = leaderSectionX - 2; endSectionX = leaderSectionX; }
    else { startSectionX = leaderSectionX - 1; endSectionX = leaderSectionX + 1; }
    if (leaderSectionY == 0) { startSectionY = 0; endSectionY = 2; }
    else if (leaderSectionY == mapSectionYNum - 1) { startSectionY = leaderSectionY - 2; endSectionY = leaderSectionY; }
    else { startSectionY = leaderSectionY - 1; endSectionY = leaderSectionY + 1; }
    for (int x = startSectionX; x <= endSectionX; x++)
        for (int y = startSectionY; y <= endSectionY; y++)
        {
            mapSection = new Image()
            {
                Source = Super.getImage(string.Format("Map/{0}/Surface/{1}_{2}.jpg", mapCode.ToString(), x, y)),
                Width = mapSectionWidth, Height = mapSectionHeight, Stretch = Stretch.Fill,
            };
            MapSurface.Children.Add(mapSection);
            Canvas.SetLeft(mapSection, x * mapSectionWidth);
            Canvas.SetTop(mapSection, y * mapSectionHeight);
        }
}

邊界處理確保不越界,動態構建 3×3 切片矩陣填滿視窗。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved