Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class ProceduralGridTerrain : MonoBehaviour
- {
- public GameObject terrainPrefab;
- [SerializeField] private int width = 24;
- [SerializeField] private int height = 32;
- private GameObject[,] terrainList;
- private bool isDirty = true;
- public float offsetX;
- public float offsetY;
- [SerializeField] private float step = 0.2f;
- void Awake()
- {
- Debug.Log( "Setting up Terrain" );
- terrainList = new GameObject[width, height];
- for( int x = 0; x < width; x++ )
- {
- for( int y = 0; y < height; y++ )
- {
- //Debug.Log( x + ", " + y );
- Vector3 pos = transform.position + new Vector3( x, 0, y );
- terrainList[x, y] = Instantiate( terrainPrefab, pos, transform.rotation, transform );
- terrainList[x, y].name = "Tile " + x + "," + y;
- }
- }
- //UpdateTerrainLoc();
- }
- // Update is called once per frame
- void Update()
- {
- if( Input.GetKeyDown( KeyCode.U ) )
- {
- offsetY += step;
- isDirty = true;
- }
- if( Input.GetKeyDown( KeyCode.H ) )
- {
- offsetX -= step;
- isDirty = true;
- }
- if( Input.GetKeyDown( KeyCode.J ) )
- {
- offsetY -= step;
- isDirty = true;
- }
- if( Input.GetKeyDown( KeyCode.K ) )
- {
- offsetX += step;
- isDirty = true;
- }
- if( isDirty )
- UpdateTerrainLoc();
- }
- void UpdateTerrainLoc()
- {
- for( int x = 0; x < width; x++ )
- {
- for( int y = 0; y < height; y++ )
- {
- float xDiff = x * .01f + offsetX;
- float yDiff = y * .01f + offsetY;
- float loc = Mathf.Round( Mathf.PerlinNoise( xDiff, yDiff ) * 20 );
- Debug.Log( xDiff + ", " + yDiff + ", " + loc);
- Vector3 pos = terrainList[x, y].transform.position;
- pos.y = loc;
- terrainList[x, y].transform.position = pos;
- }
- }
- isDirty = false;
- }
- public float getTerrainHeight( int x, int y )
- {
- return terrainList[x, y].transform.position.y;
- }
- public float getTerrainHeight( Vector2Int loc )
- {
- if( terrainList[loc[0], loc[1]] )
- {
- Debug.Log( terrainList[loc[0], loc[1]].transform.position );
- float y = terrainList[loc[0], loc[1]].transform.position.y;
- return y;
- }
- return -999;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement