我有一个奇怪的错误,我不明白它为什么会发生,也许有人可以提供帮助。
我正在制作一个蛇游戏,我正在做网格atm。 我根据游戏对象大小实例化网格,但是当网格实例化时存在偏移。它与我指定的游戏对象大小不同(黑框如下图所示)。
这是我的经理所在的网站
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GridManager : MonoBehaviour {
[SerializeField] private GridTile gridTilePrefab;
[SerializeField] private Transform playArea;
[SerializeField] private int gridSize = 10;
public int GridSize {
get { return gridSize; }
}
private Vector3 startPoint;
public Vector3 StartPoint {
get { return startPoint; }
}
private int width;
private int height;
private Transform[,] grid;
public void InitializeGrid()
{
// Grid Size
width = Mathf.RoundToInt (playArea.localScale.x * gridSize);
height = Mathf.RoundToInt (playArea.transform.localScale.y * gridSize);
grid = new Transform[width,height];
// get the left bottom as start point
startPoint = playArea.GetComponent<Renderer>().bounds.min;
CreateGridTiles ();
}
private void CreateGridTiles()
{
if (gridTilePrefab == null)
return;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
// Get world pos of grid location
Vector3 worldPos = GetWorldPos(x,y);
GridTile gridTile;
gridTile = Instantiate (gridTilePrefab, worldPos , Quaternion.identity);
gridTile.name = string.Format ("Tile({0},{1})" , x , y );
grid [x, y] = gridTile.transform;
}
}
}
private Vector3 GetWorldPos (int x, int y)
{
float xf = x;
float yf = y;
return new Vector3 (startPoint.x + (xf / gridSize) ,startPoint.y + (yf / gridSize) ,startPoint.z);
}
// Use this for initialization
void Start () {
InitializeGrid ();
}
}
答案 0 :(得分:2)
错误不是代码,而是使用了瓷砖的精灵。我改变了它从中心到左下方的枢轴。因为在代码中我的startPoint = playArea.GetComponent<Renderer>().bounds.min;
所以它会占据对象的左下角。