- Home /
using Tilemap for 3D RTS game
Hello, I want to try to make my first RTS game and wanted to ask if Tilemaps can be used as a grid for placing buildings in real time (meaning, when I click a building from UI selection, the tilemap shows up and after I place the building it snaps to the tile) or do I have to create my own grid system for this?
thanks a bunch
Comment
Best Answer
Answer by andrew-lukasik · Oct 09, 2021 at 10:53 PM
Create your own little grid system, it's not that complicated
LetsBuildAGrid.cs
using System.Collections.Generic;
using UnityEngine;
public class LetsBuildAGrid : MonoBehaviour
{
[SerializeField] Vector3 _gridOrigin = Vector3.zero;
[SerializeField] Vector2 _gridCellSize = new Vector2( 3f , 3f );
[SerializeField] Camera _camera = null;
Vector2Int _cursorCoord;
[SerializeField] Mesh _gridCellMesh = null;
[SerializeField] Vector3 _gridCellMeshScale = Vector3.one;
[SerializeField] Vector3 _gridCellMeshRotation = Vector3.zero;
[SerializeField] Material _gridCellMaterial = null;
Matrix4x4[] _gridCellsToRender = new Matrix4x4[1];
[SerializeField] GameObject _prefabToSpawn = null;
Dictionary<Vector2Int,GameObject> _prefabInstances = new Dictionary<Vector2Int,GameObject>();
void Update ()
{
var gridPlane = new Plane( Vector3.up , _gridOrigin );
var ray = _camera.ScreenPointToRay( Input.mousePosition );
if( gridPlane.Raycast( ray , out float rayHitDist ) )
{
Vector3 cursorPos = ray.origin + ray.direction*rayHitDist;
Vector2Int cursorGridCoord = new Vector2Int(
Mathf.FloorToInt( cursorPos.x/_gridCellSize.x ) ,
Mathf.FloorToInt( cursorPos.z/_gridCellSize.y )
);
_cursorCoord = cursorGridCoord;
}
Vector3 gridCellCenter = CoordToCenter( _cursorCoord );
_gridCellMaterial.SetPass(0);
_gridCellsToRender[0] = Matrix4x4.TRS( gridCellCenter , Quaternion.Euler(_gridCellMeshRotation) , _gridCellMeshScale );
Graphics.DrawMeshInstanced( _gridCellMesh , 0 , _gridCellMaterial , _gridCellsToRender );
if( Input.GetMouseButtonDown(0) )
if( !_prefabInstances.ContainsKey(_cursorCoord) )
{
var instance = GameObject.Instantiate( _prefabToSpawn , gridCellCenter , Quaternion.identity );
_prefabInstances.Add( _cursorCoord , instance );
}
}
#if UNITY_EDITOR
void OnDrawGizmos ()
{
Gizmos.DrawWireCube( CoordToCenter(_cursorCoord) , new Vector3( _gridCellSize.x , 0 , _gridCellSize.y ) );
}
#endif
Vector3 CoordToCorner ( Vector2Int coord ) => new Vector3( coord.x*_gridCellSize.x , _gridOrigin.y , coord.y*_gridCellSize.y );
Vector3 CoordToCenter ( Vector2Int coord ) => CoordToCorner(coord) + new Vector3( _gridCellSize.x , 0 , _gridCellSize.y )*0.5f;
}
w5uhiugehw390tewfujhhoh3wr908iu.gif
(158.9 kB)