I've been trying to get my head around this for hours now, I hope one of you is able to help.
I'm trying to make a small game (2D using sprites) that allows you to place blocks (tiles). That is pretty simple in itself, I use ScreenToWorldPoint and mouse position to place the block (no snapping to grid yet).
Now, what I need to do is ensure that the player places blocks on either side of the block that was just placed, and not just some random place on the screen.
A block is just a 1x1 sprite in this case.
For example. Player placed a single block on the screen:
can place here
|
can place here - [#] - can place here
|
can place here
Player then places another block next to the already placed block:
can place here
| |
can place here - [#][#] - can place here
| |
can place here
As you see, there is always room to place 1 block around each block placed (using the word block too much!). This is in 2D space.
So in the end, the player might make this:
can place here
| | |
can place here - [#] | [#] - can place here
can place here - [#][#][#][#][#] - can place here
As you also see here, there is always room for 1 block to be placed around the already placed blocks - obviously not when there's already a block placed next to it.
Hope it makes sense.
I guess what I'm after is just: How would I go about creating a grid around a single game object (2D sprite) - I can then use Ray's to figure out if player has pressed one of the grids around it.
Thanks a lot!
EDIT:
So, I managed to get something working. I made a game object with 4 parents (1x1 sprites: top, right, left, bottom) - clicking on one of these parents, "replaces" (destroys) the object and inserts another tile with 4 parents.
This seems like a really bad implementation, so please suggest alternative ways of doing this.
Code:
using UnityEngine;
using System.Collections;
public class GameManager : MonoBehaviour {
public Transform boatObject;
public GameObject tile;
public GameObject boatPlank;
private Vector2 mousePosition;
void Start ()
{
Vector3 position = new Vector3 (boatObject.transform.position.x, boatObject.transform.position.y, 0);
GameObject gridTile = Instantiate (tile, position, Quaternion.identity) as GameObject;
gridTile.transform.SetParent (boatObject.transform);
}
void Update ()
{
// Mouse button 1
if (Input.GetMouseButton (0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast (ray.origin, ray.direction);
if (hit.collider.gameObject.tag == "GridItem")
{
Vector3 position = new Vector3 (hit.collider.transform.position.x, hit.collider.transform.position.y, 0);
GameObject gridTile = Instantiate (tile, position, Quaternion.identity) as GameObject;
gridTile.GetComponent<SpriteRenderer> ().sortingOrder = 10;
gridTile.transform.SetParent (boatObject.transform);
// Destroy the grid item that was clicked
Destroy (hit.collider.gameObject);
Debug.Log ("Hit something: " + hit.collider.gameObject.tag);
}
}
}
}