using UnityEngine;
using TMPro;
public class CubeController : MonoBehaviour
{
[SerializeField] float jumpForce = 8f;
[SerializeField] float rotationSpeed = 100f;
[SerializeField] float raycastDistance = 0.8f;
[SerializeField] LayerMask groundLayer;
[SerializeField] int step = 5;
[SerializeField] int maxCubes = 300;
Rigidbody2D rb;
SpriteRenderer sr;
TextMeshPro txt;
int number;
int birthFrame;
static int cubeCount;
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
static void ResetCount() { cubeCount = 0; }
void Awake()
{
rb = GetComponent<Rigidbody2D>();
sr = GetComponent<SpriteRenderer>();
txt = GetComponentInChildren<TextMeshPro>();
birthFrame = Time.frameCount;
cubeCount++;
RandomizeColors();
UpdateText();
}
void OnDestroy() { cubeCount--; }
void Update()
{
// новый кубик в кадр своего появления не прыгает
if (Time.frameCount == birthFrame) return;
if (Input.GetKeyDown(KeyCode.Space) && IsGrounded())
{
Jump();
}
}
void FixedUpdate()
{
// кубик крутится постоянно
rb.angularVelocity = rotationSpeed;
}
bool IsGrounded()
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down, raycastDistance, groundLayer);
return hit.collider != null;
}
void Jump()
{
rb.linearVelocity = new Vector2(rb.linearVelocity.x, 0f);
rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
number += step;
RandomizeColors();
UpdateText();
SpawnClone();
}
void SpawnClone()
{
if (cubeCount >= maxCubes) return;
// случайная точка в пределах камеры (верхняя часть экрана)
Vector3 pos = Camera.main.ViewportToWorldPoint(
new Vector3(Random.Range(0.05f, 0.95f), Random.Range(0.5f, 0.95f), 10f));
pos.z = 0f;
GameObject clone = Instantiate(gameObject, pos, Quaternion.identity);
clone.GetComponent<CubeController>().Init(number);
}
public void Init(int startNumber)
{
number = startNumber;
RandomizeColors();
UpdateText();
}
void RandomizeColors()
{
sr.color = Random.ColorHSV(0f, 1f, 0.7f, 1f, 0.8f, 1f);
txt.color = Random.ColorHSV(0f, 1f, 0.7f, 1f, 0.8f, 1f);
}
void UpdateText()
{
txt.text = number.ToString();
}
}