我有一個網格系統佈局,可以讓我捕捉對象到網格,並且工作得很好,但這不是我在這種情況下尋找的行爲。我不能爲了我的生活把它寫成任何有意義的詞彙(可能是爲什麼我無法在我的頭上纏繞它......),所以我用當前的行爲和預期的行爲來描繪一幅圖畫,更好的工作:捕捉到特定的網格位置
的左側顯示了當前行爲(注:電網系統實際上是兩倍大,如上圖所示的白色網格線這允許放置在網格線對象,這是我正在尋找的預期行爲。)
右側是我希望對象如何對齊網格。我只想將對象放置在網格線上,而不是放置在網格節點(或空白中心節點)上。
在預期的行爲中,如果配對值與它相反,對象將始終對齊網格 - 如果X是ODD,則Y值必須是EVEN才能對齊或反之亦然(即[0 ,1],[1,0],[2,3])。對象不會捕捉到[0,0],[1,1],[4,2],因爲它們都是奇數或偶數。只是我注意到,這與我所尋找的行爲一致,但無法將其轉化爲有用的東西。
這裏的對齊網格代碼,在它的全部:
//Grab the mouse state
MouseState mouse = Mouse.GetState();
//TileX = (int)Math.Floor((float)(mouse.X/tileWidth)); //tileWidth = 80
//TileY = (int)Math.Floor((float)(mouse.Y/tileHeight)); //tileHeight = 80
//We want "snap to closest grid space" instead of "snap to next-lowest grid space",
//like the Math.Floor code does above. The ".ToInt()" extensions simply rounds a
//float to the closest integer. i.e. 2.2 = 2 2.5 = 3 3 = 3
TileX = ((float)mouse.X/tileWidth).ToInt();
TileY = ((float)mouse.Y/tileHeight).ToInt();
//Set the square to a whole tile coordinate
squarePosition.X = TileX * tileWidth;
squarePosition.Y = TileY * tileHeight;