我决定开发一种gomoku游戏,其原理非常简单:您必须在瓷砖地图中放置圆形或十字形,目标是对齐5个项目。为此,我选择在2D中使用统一性,并使用带有瓷砖图像的预制件来创建地图。我遇到的问题是,在我的脚本GameManager中,当我用光线投射鼠标单击位置时,单击位置与我生成的板的图块不同,因此无法在地图上放置项目。
BoardGenerator.cs
public float startX;
public float startY;
public Transform tiles;
public int BOARD_SIZE = 19;
void Start()
{
CreateBoard();
}
void Update()
{
}
void CreateBoard()
{
float tileX = tiles.GetComponent<SpriteRenderer>().bounds.size.x;
float tileY = tiles.GetComponent<SpriteRenderer>().bounds.size.y;
float yCor = Camera.main.ScreenToWorldPoint(new Vector3(0, startY, 0f)).y;
int count = 0;
for (int i = 0; i < BOARD_SIZE; i++)
{
float xCor = Camera.main.ScreenToWorldPoint(new Vector3(startX, 0, 0f)).x;
for (int j = 0; j < BOARD_SIZE; j++)
{
Vector3 tilesPos = new Vector3(xCor, yCor, 0f);
Transform tile = Instantiate(tiles, tilesPos, Quaternion.identity);
tile.gameObject.name = "Tile" + count;
count++;
xCor += tileX;
}
yCor -= tileY;
}
}
GameManager.cs
public int firstPlayer;
private PlayerTurn playerTurn;
public Sprite xSprite;
public Sprite oSprite;
public enum PlayerTurn
{
PLAYER1,
PLAYER2,
BOT
}
void Start()
{
if (firstPlayer == 1)
playerTurn = PlayerTurn.PLAYER1;
else
playerTurn = PlayerTurn.PLAYER2;
}
void Update()
{
Play();
}
void Play()
{
if (Input.GetMouseButtonDown(0))
{
float xCor = Camera.main.ScreenToWorldPoint(Input.mousePosition).x;
float yCor = Camera.main.ScreenToWorldPoint(Input.mousePosition).y;
Vector2 origin = new Vector2(xCor, yCor);
RaycastHit2D hit = Physics2D.Raycast(origin, Vector2.zero, 0);
Debug.Log("mouse = " + origin);
Debug.Log("first tile = " + (Vector2)GameObject.Find("Tile0").transform.position);
if (hit.collider != null && hit.transform.gameObject.tag.Equals("Tile"))
{
Debug.Log("hit");
if (this.playerTurn == PlayerTurn.PLAYER1)
{
hit.transform.gameObject.GetComponent<SpriteRenderer>().sprite = xSprite;
hit.transform.tag = "crossTile";
playerTurn = PlayerTurn.PLAYER2;
}
else if (this.playerTurn == PlayerTurn.PLAYER2)
{
hit.transform.gameObject.GetComponent<SpriteRenderer>().sprite = oSprite;
hit.transform.tag = "roundTile";
playerTurn = PlayerTurn.PLAYER1;
}
}
}
}
答案 0 :(得分:0)
您可以利用Raycast的不同重载来返回命中对象,如下所示:
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics2D.Raycast(ray, out hit, rayDist)){
GameObject obj = hit.transform.gameObject;
// Do something with obj
}
在上面的示例中,“ obj”将是被Raycast击中的GameObject,因此您可以通过引用以下内容来获取其位置:
obj.transform.position
原因:
GameObject obj = hit.transform.gameObject;
是“ hit.gameObject”将返回带有刚体的父对象(如果有)。当使用更复杂的对象结构时,这可能会导致很多混乱,因此,抓取“ hit.transform.gameObject”是一个好习惯,这将始终返回与Raycast命中器相撞的GameObject。