Как получить координаты с шестнадцатеричной карты на клик в Unity - PullRequest
1 голос
/ 25 апреля 2019

Я делаю настольную игру, известную как Hex. Когда я нажимаю на плитку, она меняется на синий или желтый, но мне также нужно знать, каковы координаты этой плитки.

Я не могу использовать ...

rend.transform.position;

... потому что координаты, которые я хочу получить, выглядят примерно так: (0,0) слева внизу и (0,1) над ним: enter image description here

Координаты в консоли - это те, которые мне нужно получить.

enter image description here

Я распечатал их, используя переменные столбца и строки при генерации шестнадцатеричной карты:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class HexMap : MonoBehaviour
{
 // Use this for initialization
 void Start()
 {
    GenerateMap();
 }

public GameObject HexPrefab;

public void GenerateMap()
{
    for (int column = 0; column < 11; column++)
    {
        for (int row = 0; row < 11; row++)
        {
            // Instantiate a Hex
            Hex h = new Hex(column, row);

            Instantiate(HexPrefab, h.Position(), Quaternion.identity, this.transform);

            Debug.Log(column + "," + row);
        }
    }
}
}

Я хочу иметь возможность получить координаты, когда я щелкаю плитку с шестигранной головкой с помощью этого сценария здесь:

using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using UnityEngine;
using UnityEngine.Networking;

public class ColorChange : MonoBehaviour {

public Color[]colors; // allows input of material colors in a set sized array
public SpriteRenderer rend;  // what are we rendering? the hex

public enum Player {ONE, TWO};
public static Player currentPlayer = Player.ONE;

// Use this for initialization
void Start () {
    rend = GetComponent<SpriteRenderer> (); // gives functionality for the renderer
}

void NextPlayer() {

   if( currentPlayer == Player.ONE ) {
      currentPlayer = Player.TWO;
   }
   else if( currentPlayer == Player.TWO) {
      currentPlayer = Player.ONE;
   }
}

// Update is called once per frame
void OnMouseDown () {
    // if there are no colors present nothing happens
    if (colors.Length == 0)
        return;

    if (currentPlayer == Player.ONE)
        rend.color = colors [0];
    else if (currentPlayer == Player.TWO)
        rend.color = colors [1];

    NextPlayer();
}

Вот скрипт, который я использую, чтобы определить, где должны быть шестигранные плитки:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Hex{

public Hex (int q, int r){
    this.Q = q;
    this.R = r;
}

public readonly int Q; // x
public readonly int R;  // y

static readonly float WIDTH_MULTIPLIER = Mathf.Sqrt(3) / 2;

public Vector2 Position(){
    float radius = 0.513f;
    float height = radius * 2;
    float width = WIDTH_MULTIPLIER * height;

    float vert = height * 0.75f;
    float horiz = width;

    return new Vector2(horiz * (this.Q - this.R/2f), vert * this.R);
}
}

Я думал, что должен быть в состоянии назначить каждой шестнадцатеричной модели значение столбца и строки, когда она создается, но я не уверен, как это сделать. Я попробовал несколько решений, которые нашел в Интернете, а также с помощью GetComponent, но я не смог заставить их работать. Если у кого-то есть идея о том, как это возможно, я буду очень признателен!

1 Ответ

1 голос
/ 25 апреля 2019

Причина, по которой GetComponent не работает в вашем случае, заключается в том, что скрипт Coordinates находится на дочернем объекте шестнадцатеричного префаба.Вы можете получить доступ к компоненту дочернего объекта, вызвав GetComponentInChildren.Это будет выглядеть примерно так:

// Instantiate a Hex
Hex h = new Hex(column, row);

// Instantiate the prefab
GameObject instance = Instantiate(HexPrefab, h.Position(), Quaternion.identity, this.transform);

// Let's find the coorinates component on the hex prefab instance.
Coordinates coordinates = instance.GetComponentInChildren<Coordinates>();

// now you may assign the column and row values to it
// ...

Существует много возможных подходов к этой проблеме.Но имейте в виду, где в сборной иерархии находятся компоненты, и у вас все будет хорошо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...