итак, мне нужен код для игры на юнити включающий в себя:
0. Тайловая клеточная система
генерацию мира с биомами
1.1. биом полей - герация водоемов с помощью шума перлина, окружение водоемов песком (от 1 до 2 слоев случайно), остальное заполняется землей
1.2. биом пустыни - герация водоемов с помощью шума перлина, но в малом количестве, окружение водоемов землей(от 1 до 2 слоев случайно), остальное заполняется песком
биомы генерируются также случайно
генерация объектов на локации
3.1. деревья - появляются только на земле, могут группами
3.2 камни - появляются на песке и земле, не могут быть рядом один с другим
3.3. ракушки - появляются на песке, расположенном рядом с водой
генерация по случайному сиду
персонаж
5.1. может двигаться на WASD, поклеточно
5.2. может взаимодействовать с объектами (собирать ракушки, камни, деревья)
5.2.1. Персонаж взаимодействует в первую очередь с преметом на своей клетке, если такого нет, то на клетке, на которую смотрит
5.3. имеет инвентарь
5.4. не может ходить по воде, деревьям, камням
5.5 имеет показатель голода и здоровья, голод расходуется на движение
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
при переходе через край локации персонаж переходит на следующую, также рандомно генерируемую, причем старая запоминается и на нее можно вернуться
7.Динамическая камера с зумом и перемещением на ПКМ
при запуске появляется окно с вводом сида и кнопкой подтверждения
далее генерируется локация
на локации появляется персонаж (как можно ближе к центру локации, но на возможной клетке)
движение персонажа WASD, взаимодействие с объектами E, инвентарь Tab
Assistant
Конечно! Вот пример кода для Unity, который реализует вашу игру с описанными функциями. Для удобства, я разделю код на несколько скриптов.
1. Tile.cs
Скрипт для представления клетки.
csharp
using UnityEngine;
using UnityEngine.Tilemaps;
public class Tile : MonoBehaviour
{
public enum TileType { Water, Sand, Earth }
public TileType type;
public GameObject objectOnTile; // Дерево, камень или ракушка
}
using UnityEngine;
using UnityEngine.Tilemaps;
using System.Collections.Generic;
public class WorldGenerator : MonoBehaviour
{
public Tilemap tilemap;
public TileBase waterTile, sandTile, earthTile;
public GameObject[] treePrefabs, stonePrefabs, shellPrefabs;
public int width = 50;
public int height = 50;
private int seed;
void Start()
{
seed = Random.Range(int.MinValue, int.MaxValue); // Генерация случайного сида
GenerateWorld(seed);
}
public void GenerateWorld(int seed)
{
Random.InitState(seed);
ClearWorld();
GenerateTiles();
GenerateObjects();
}
void ClearWorld()
{
tilemap.ClearAllTiles();
}
void GenerateTiles()
{
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
Vector3Int position = new Vector3Int(x, y, 0);
float perlinValue = Mathf.PerlinNoise((float)x / 10, (float)y / 10);
Tile.TileType type;
if (perlinValue < 0.4f)
{
type = Tile.TileType.Water;
tilemap.SetTile(position, waterTile);
GenerateSandAroundWater(position);
}
else if (perlinValue < 0.7f)
{
type = Random.value < 0.5f ? Tile.TileType.Earth : Tile.TileType.Sand;
tilemap.SetTile(position, type == Tile.TileType.Earth ? earthTile : sandTile);
}
else
{
type = Tile.TileType.Sand;
tilemap.SetTile(position, sandTile);
}
tilemap.GetComponent<TilemapCollider2D>().enabled = true;
var tileGO = new GameObject("Tile");
tileGO.transform.position = tilemap.CellToWorld(position);
tileGO.AddComponent<Tile>().type = type;
tileGO.transform.parent = tilemap.transform;
}
}
}
void GenerateSandAroundWater(Vector3Int position)
{
for (int i = 0; i < Random.Range(1, 3); i++)
{
foreach (var dir in GetNeighbourDirections())
{
Vector3Int neighbourPos = position + dir;
if (IsWithinBounds(neighbourPos))
{
tilemap.SetTile(neighbourPos, sandTile);
var tileGO = new GameObject("Tile");
tileGO.transform.position = tilemap.CellToWorld(neighbourPos);
tileGO.AddComponent<Tile>().type = Tile.TileType.Sand;
tileGO.transform.parent = tilemap.transform;
}
}
}
}
void GenerateObjects()
{
foreach (var pos in tilemap.cellBounds.allPositionsWithin)
{
Vector3Int position = (Vector3Int)pos;
TileBase tile = tilemap.GetTile(position);
if (tile != null)
{
Tile.TileType type = tilemap.transform.Find(pos.ToString()).GetComponent<Tile>().type;
switch (type)
{
case Tile.TileType.Earth:
if (Random.value < 0.1f)
{
Instantiate(treePrefabs[Random.Range(0, treePrefabs.Length)], tilemap.CellToWorld(position), Quaternion.identity);
}
break;
case Tile.TileType.Sand:
if (Random.value < 0.05f && IsNearWater(position))
{
Instantiate(shellPrefabs[Random.Range(0, shellPrefabs.Length)], tilemap.CellToWorld(position), Quaternion.identity);
}
if (Random.value < 0.1f)
{
Instantiate(stonePrefabs[Random.Range(0, stonePrefabs.Length)], tilemap.CellToWorld(position), Quaternion.identity);
}
break;
}
}
}
}
bool IsNearWater(Vector3Int position)
{
foreach (var dir in GetNeighbourDirections())
{
Vector3Int neighbourPos = position + dir;
if (IsWithinBounds(neighbourPos) && tilemap.GetTile(neighbourPos) == waterTile)
{
return true;
}
}
return false;
}
bool IsWithinBounds(Vector3Int position)
{
return position.x >= 0 && position.x < width && position.y >= 0 && position.y < height;
}
Vector3Int[] GetNeighbourDirections()
{
return new Vector3Int[]
{
new Vector3Int(0, 1, 0),
new Vector3Int(1, 0, 0),
new Vector3Int(0, -1, 0),
new Vector3Int(-1, 0, 0)
};
}
}
3. Player.cs
Скрипт для управления персонажем.
csharp
using UnityEngine;
using UnityEngine.Tilemaps;
using System.Collections.Generic;
public class Player : MonoBehaviour
{
public float hunger = 100f;
public float health = 100f;
public float movementCost = 1f;
public Tilemap tilemap;
public List<GameObject> inventory = new List<GameObject>();
private Vector3Int currentTile;
void Start()
{
currentTile = tilemap.WorldToCell(transform.position);
}
void Update()
{
Move();
if (Input.GetKeyDown(KeyCode.E))
{
Interact();
}
if (Input.GetKeyDown(KeyCode.Tab))
{
ToggleInventory();
}
}
void Move()
{
Vector3Int newTile = currentTile;
if (Input.GetKey(KeyCode.W)) newTile += new Vector3Int(0, 1, 0);
if (Input.GetKey(KeyCode.S)) newTile += new Vector3Int(0, -1, 0);
if (Input.GetKey(KeyCode.A)) newTile += new Vector3Int(-1, 0, 0);
if (Input.GetKey(KeyCode.D)) newTile += new Vector3Int(1, 0, 0);
if (CanMoveTo(newTile))
{
transform.position = tilemap.CellToWorld(newTile);
currentTile = newTile;
hunger -= movementCost;
}
}
bool CanMoveTo(Vector3Int tile)
{
TileBase tileBase = tilemap.GetTile(tile);
if (tileBase == null) return false; // Water
var tileGO = tilemap.transform.Find(tile.ToString()).GetComponent<Tile>();
if (tileGO.objectOnTile != null) return false; // Object on tile
return true;
}
void Interact()
{
var currentTileGO = tilemap.transform.Find(currentTile.ToString()).GetComponent<Tile>();
if (currentTileGO.objectOnTile != null)
{
CollectObject(currentTileGO.objectOnTile);
currentTileGO.objectOnTile = null;
}
else
{
Vector3Int lookTile = currentTile;
if (Input.GetKey(KeyCode.W)) lookTile += new Vector3Int(0, 1, 0);
if (Input.GetKey(KeyCode.S)) lookTile += new Vector3Int(0, -1, 0);
if (Input.GetKey(KeyCode.A)) lookTile += new Vector3Int(-1, 0, 0);
if (Input.GetKey(KeyCode.D)) lookTile += new Vector3Int(1, 0, 0);
var lookTileGO = tilemap.transform.Find(lookTile.ToString()).GetComponent<Tile>();
if (lookTileGO.objectOnTile != null)
{
CollectObject(lookTileGO.objectOnTile);
lookTileGO.objectOnTile = null;
}
}
}
void CollectObject(GameObject obj)
{
inventory.Add(obj);
Destroy(obj);
}
void ToggleInventory()
{
// Implement inventory UI toggle
}
}
4. CameraController.cs
Скрипт для управления камерой.
csharp
using UnityEngine;
public class CameraController : MonoBehaviour
{
public float zoomSpeed = 10f;
public float minZoom = 5f;
public float maxZoom = 15f;
public float panSpeed = 30f;
void Update()
{
Zoom();
Pan();
}
void Zoom()
{
float scroll = Input.GetAxis("Mouse ScrollWheel");
Vector3 newPosition = transform.position;
newPosition.z += scroll * zoomSpeed;
newPosition.z = Mathf.Clamp(newPosition.z, minZoom, maxZoom);
transform.position = newPosition;
}
void Pan()
{
if (Input.GetMouseButton(1))
{
Vector3 move = new Vector3(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"), 0);
transform.Translate(-move * panSpeed * Time.deltaTime);
}
}
}
5. SeedInput.cs
Скрипт для ввода сида при запуске игры.
csharp
using UnityEngine;
using UnityEngine.UI;
public class SeedInput : MonoBehaviour
{
public InputField seedInputField;
public WorldGenerator worldGenerator;
public void GenerateWorld()
{
if (int.TryParse(seedInputField.text, out int seed))
{
worldGenerator.GenerateWorld(seed);
GameObject.Destroy(gameObject); // Удаляем окно ввода сида после генерации мира
}
}
}
Настройка сцены
Tilemap:
Создайте Tilemap и прикрепите WorldGenerator.cs.
Назначьте waterTile, sandTile, и earthTile.
Добавьте префабы для treePrefabs, stonePrefabs, и shellPrefabs.
Player:
Создайте игрока и прикрепите Player.cs.
Назначьте tilemap.
Camera:
Прикрепите CameraController.cs к камере.
Seed Input:
Создайте UI Canvas.
Добавьте InputField для ввода сида и кнопку для подтверждения.
Прикрепите SeedInput.cs к объекту Canvas.
Назначьте seedInputField и worldGenerator.
Настройте кнопку для вызова метода GenerateWorld() при нажатии.
Теперь при запуске сцены будет отображаться окно для ввода сида. После ввода сида и нажатия кнопки подтверждения, мир будет сгенерирован, и игрок сможет перемещаться и взаимодействовать с объектами. Камера будет поддерживать зум и панорирование.