First Commit

This commit is contained in:
bybohka committed 2026-11-19 23:24:44 +03:00
commit eed6b79efc
2836 files changed
+948481

No files matched your search

@@ -0,0 +1,386 @@
using UnityEngine;
using UnityEngine.UI;
using TMPro;
/// <summary>
/// Красивая 3D GPS-навигация и экранная метка пути до купленного или выбранного для встречи автомобиля.
/// Включает объемный луч-маяк в мире, экранную плашку с расстоянием, стрелку направления и оповещение о прибытии.
/// </summary>
public class MeetingWaypointHUD : MonoBehaviour
{
[Header("Ссылки")]
[SerializeField] private CarMarketManager marketManager;
[Header("Настройки метки")]
[SerializeField] private float heightAboveCar = 2.4f;
[SerializeField] private float arrivalDistance = 8f;
private Camera mainCam;
private GameObject beaconWorldRoot;
private GameObject beaconPillar;
private Transform activeTargetCar;
private CarListing currentListing;
private bool hasTriggeredArrival = false;
// UI элементы на Canvas
private GameObject hudContainer;
private RectTransform waypointRect;
private Image waypointBg;
private Image iconImage;
private TextMeshProUGUI titleText;
private TextMeshProUGUI distanceText;
private RectTransform arrowRect;
private Image arrowImage;
// Баннер прибытия
private GameObject arrivalBanner;
private CanvasGroup arrivalBannerGroup;
private float arrivalBannerTimer = 0f;
private void Awake()
{
if (marketManager == null)
marketManager = FindAnyObjectByType<CarMarketManager>();
CreateHUDHierarchy();
}
private void Start()
{
if (marketManager != null)
{
marketManager.OnMeetingArranged += HandleMeetingArranged;
marketManager.OnMeetingCleared += HandleMeetingCleared;
if (marketManager.ActiveMeetingListing != null)
HandleMeetingArranged(marketManager.ActiveMeetingListing);
}
}
private void OnDestroy()
{
if (marketManager != null)
{
marketManager.OnMeetingArranged -= HandleMeetingArranged;
marketManager.OnMeetingCleared -= HandleMeetingCleared;
}
if (beaconWorldRoot != null)
Destroy(beaconWorldRoot);
}
private void CreateHUDHierarchy()
{
Canvas canvas = FindAnyObjectByType<Canvas>();
if (canvas == null)
{
GameObject canvasObj = new GameObject("WaypointHUDCanvas");
canvas = canvasObj.AddComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
canvas.sortingOrder = 95;
CanvasScaler scaler = canvasObj.AddComponent<CanvasScaler>();
scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
scaler.referenceResolution = new Vector2(1920, 1080);
scaler.matchWidthOrHeight = 0.5f;
canvasObj.AddComponent<GraphicRaycaster>();
}
// Корневой контейнер
hudContainer = new GameObject("MeetingWaypointHUD");
hudContainer.transform.SetParent(canvas.transform, false);
hudContainer.SetActive(false);
// 1. Плашка путевой метки
GameObject wpObj = new GameObject("WaypointBadge");
wpObj.transform.SetParent(hudContainer.transform, false);
waypointRect = wpObj.AddComponent<RectTransform>();
waypointRect.sizeDelta = new Vector2(230f, 48f);
waypointRect.pivot = new Vector2(0.5f, 0.5f);
waypointBg = wpObj.AddComponent<Image>();
waypointBg.sprite = ProceduralUISprites.GetSlicedRoundedRect(new Color(0.08f, 0.10f, 0.14f, 0.92f), new Color(0.06f, 0.75f, 0.45f, 0.85f), 2f, 14);
waypointBg.type = Image.Type.Sliced;
waypointBg.raycastTarget = false;
// Иконка машинки / пина
GameObject iconObj = new GameObject("Icon");
iconObj.transform.SetParent(wpObj.transform, false);
RectTransform iconRt = iconObj.AddComponent<RectTransform>();
iconRt.anchorMin = new Vector2(0f, 0.5f);
iconRt.anchorMax = new Vector2(0f, 0.5f);
iconRt.pivot = new Vector2(0f, 0.5f);
iconRt.anchoredPosition = new Vector2(12f, 0f);
iconRt.sizeDelta = new Vector2(28f, 28f);
iconImage = iconObj.AddComponent<Image>();
iconImage.sprite = ProceduralUISprites.GetMapPinIcon(64, new Color(0.1f, 0.95f, 0.55f));
iconImage.raycastTarget = false;
// Название автомобиля
GameObject titleObj = new GameObject("CarTitle");
titleObj.transform.SetParent(wpObj.transform, false);
RectTransform titleRt = titleObj.AddComponent<RectTransform>();
titleRt.anchorMin = new Vector2(0f, 0.5f);
titleRt.anchorMax = new Vector2(1f, 1f);
titleRt.offsetMin = new Vector2(46f, 0f);
titleRt.offsetMax = new Vector2(-12f, -4f);
titleText = titleObj.AddComponent<TextMeshProUGUI>();
titleText.fontSize = 14f;
titleText.fontStyle = FontStyles.Bold;
titleText.color = Color.white;
titleText.alignment = TextAlignmentOptions.Left;
titleText.raycastTarget = false;
// Дистанция в метрах
GameObject distObj = new GameObject("Distance");
distObj.transform.SetParent(wpObj.transform, false);
RectTransform distRt = distObj.AddComponent<RectTransform>();
distRt.anchorMin = new Vector2(0f, 0f);
distRt.anchorMax = new Vector2(1f, 0.5f);
distRt.offsetMin = new Vector2(46f, 4f);
distRt.offsetMax = new Vector2(-12f, 0f);
distanceText = distObj.AddComponent<TextMeshProUGUI>();
distanceText.fontSize = 13f;
distanceText.fontStyle = FontStyles.Bold;
distanceText.color = new Color(0.2f, 0.95f, 0.5f);
distanceText.alignment = TextAlignmentOptions.Left;
distanceText.raycastTarget = false;
// Стрелка направления на краю экрана
GameObject arrowObj = new GameObject("DirectionArrow");
arrowObj.transform.SetParent(wpObj.transform, false);
arrowRect = arrowObj.AddComponent<RectTransform>();
arrowRect.sizeDelta = new Vector2(20f, 20f);
arrowRect.pivot = new Vector2(0.5f, 0.5f);
arrowImage = arrowObj.AddComponent<Image>();
arrowImage.sprite = ProceduralUISprites.GetPointerArrow(32, new Color(0.1f, 0.95f, 0.55f));
arrowImage.raycastTarget = false;
arrowObj.SetActive(false);
// 2. Всплывающий баннер прибытия на локацию
arrivalBanner = new GameObject("ArrivalBanner");
arrivalBanner.transform.SetParent(canvas.transform, false);
RectTransform bannerRt = arrivalBanner.AddComponent<RectTransform>();
bannerRt.anchorMin = new Vector2(0.5f, 1f);
bannerRt.anchorMax = new Vector2(0.5f, 1f);
bannerRt.pivot = new Vector2(0.5f, 1f);
bannerRt.anchoredPosition = new Vector2(0f, -40f);
bannerRt.sizeDelta = new Vector2(560f, 72f);
Image bannerBg = arrivalBanner.AddComponent<Image>();
bannerBg.sprite = ProceduralUISprites.GetSlicedRoundedRect(new Color(0.06f, 0.08f, 0.12f, 0.94f), new Color(0.10f, 0.85f, 0.45f, 0.9f), 2f, 16);
bannerBg.type = Image.Type.Sliced;
bannerBg.raycastTarget = false;
arrivalBannerGroup = arrivalBanner.AddComponent<CanvasGroup>();
arrivalBannerGroup.alpha = 0f;
GameObject bannerTextObj = new GameObject("BannerText");
bannerTextObj.transform.SetParent(arrivalBanner.transform, false);
RectTransform btRt = bannerTextObj.AddComponent<RectTransform>();
btRt.anchorMin = Vector2.zero;
btRt.anchorMax = Vector2.one;
btRt.offsetMin = new Vector2(20f, 8f);
btRt.offsetMax = new Vector2(-20f, -8f);
TextMeshProUGUI bText = bannerTextObj.AddComponent<TextMeshProUGUI>();
bText.fontSize = 15f;
bText.alignment = TextAlignmentOptions.Center;
bText.color = Color.white;
bText.text = "<color=#10b981><b>📍 ВЫ ПРИБЫЛИ НА МЕСТО ВСТРЕЧИ!</b></color>\nОсмотрите кузов, проверьте наличие деталей и состояние колес.";
bText.raycastTarget = false;
arrivalBanner.SetActive(false);
}
private void HandleMeetingArranged(CarListing listing)
{
currentListing = listing;
hasTriggeredArrival = false;
if (listing != null && listing.spawnedInstance != null)
{
activeTargetCar = listing.spawnedInstance.transform;
CreateWorldBeacon(activeTargetCar.position);
hudContainer.SetActive(true);
titleText.text = $"{listing.catalogItem.carTitle} ({listing.year})";
}
}
private void HandleMeetingCleared()
{
currentListing = null;
activeTargetCar = null;
if (beaconWorldRoot != null) beaconWorldRoot.SetActive(false);
if (hudContainer != null) hudContainer.SetActive(false);
}
private void CreateWorldBeacon(Vector3 pos)
{
if (beaconWorldRoot == null)
{
beaconWorldRoot = new GameObject("MeetingGPS_WorldBeacon");
// Вертикальный полупрозрачный столб света
GameObject pillar = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
Destroy(pillar.GetComponent<Collider>());
pillar.transform.SetParent(beaconWorldRoot.transform, false);
// Столб начинается над крышей машины и виден издалека; вблизи скрывается, чтобы не мешать осмотру
pillar.transform.localPosition = new Vector3(0f, 28f, 0f);
pillar.transform.localScale = new Vector3(0.35f, 24f, 0.35f);
beaconPillar = pillar;
Renderer r = pillar.GetComponent<Renderer>();
r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
r.sharedMaterial = PartCatalog.CreateUnlitMaterial(new Color(0.15f, 1f, 0.55f, 0.35f), true);
// Наземный круг
GameObject ring = GameObject.CreatePrimitive(PrimitiveType.Quad);
Destroy(ring.GetComponent<Collider>());
ring.transform.SetParent(beaconWorldRoot.transform, false);
ring.transform.localPosition = new Vector3(0f, 0.15f, 0f);
ring.transform.localRotation = Quaternion.Euler(90f, 0f, 0f);
ring.transform.localPosition = new Vector3(0f, 0.03f, 0f);
ring.transform.localScale = new Vector3(7f, 7f, 1f);
Renderer ringRend = ring.GetComponent<Renderer>();
ringRend.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
Material ringMat = PartCatalog.CreateUnlitMaterial(Color.white, true);
Texture2D ringTex = new Texture2D(128, 128, TextureFormat.RGBA32, false);
for (int y = 0; y < 128; y++)
for (int x = 0; x < 128; x++)
{
float d = Vector2.Distance(new Vector2(x, y), new Vector2(63.5f, 63.5f)) / 64f;
float a = Mathf.Clamp01(1f - Mathf.Abs(d - 0.85f) * 12f) * 0.8f;
ringTex.SetPixel(x, y, new Color(0.2f, 1f, 0.55f, a));
}
ringTex.Apply();
ringMat.mainTexture = ringTex;
if (ringMat.HasProperty("_BaseMap")) ringMat.SetTexture("_BaseMap", ringTex);
ringRend.sharedMaterial = ringMat;
}
beaconWorldRoot.transform.position = pos;
beaconWorldRoot.SetActive(true);
}
private void Update()
{
UpdateArrivalBanner();
if (activeTargetCar == null)
{
if (hudContainer != null && hudContainer.activeSelf)
hudContainer.SetActive(false);
if (beaconWorldRoot != null && beaconWorldRoot.activeSelf)
beaconWorldRoot.SetActive(false);
return;
}
if (beaconPillar != null && Camera.main != null)
{
bool far = Vector3.Distance(Camera.main.transform.position, activeTargetCar.position) > 18f;
if (beaconPillar.activeSelf != far) beaconPillar.SetActive(far);
}
if (beaconWorldRoot != null) beaconWorldRoot.transform.position = activeTargetCar.position;
// Если игрок уже сел внутрь машины — выключаем метку
VehicleInteraction vi = activeTargetCar.GetComponent<VehicleInteraction>();
if (vi != null && vi.isPlayerInside)
{
HandleMeetingCleared();
return;
}
if (mainCam == null || !mainCam.gameObject.activeInHierarchy)
mainCam = Camera.main ?? FindAnyObjectByType<Camera>();
if (mainCam == null) return;
Vector3 targetWorldPos = activeTargetCar.position + Vector3.up * heightAboveCar;
float dist = Vector3.Distance(mainCam.transform.position, targetWorldPos);
// Обновляем текст расстояния
if (dist >= 1000f)
distanceText.text = $"{(dist / 1000f):F1} км до авто";
else
distanceText.text = $"{dist:F0} м до встречи";
// Проверяем приближение
if (dist <= arrivalDistance && !hasTriggeredArrival)
{
hasTriggeredArrival = true;
ShowArrivalBanner();
}
// 3D -> 2D Screen Position
Vector3 screenPos = mainCam.WorldToScreenPoint(targetWorldPos);
bool isBehind = screenPos.z < 0f;
float marginX = 130f;
float marginY = 50f;
Vector2 screenCenter = new Vector2(Screen.width * 0.5f, Screen.height * 0.5f);
bool isOffscreen = isBehind || screenPos.x < marginX || screenPos.x > (Screen.width - marginX)
|| screenPos.y < marginY || screenPos.y > (Screen.height - marginY);
if (isOffscreen)
{
if (isBehind)
{
screenPos.x = Screen.width - screenPos.x;
screenPos.y = Screen.height - screenPos.y;
}
Vector2 fromCenter = (new Vector2(screenPos.x, screenPos.y) - screenCenter).normalized;
if (fromCenter == Vector2.zero) fromCenter = Vector2.up;
float clampedX = Mathf.Clamp(screenCenter.x + fromCenter.x * (screenCenter.x - marginX), marginX, Screen.width - marginX);
float clampedY = Mathf.Clamp(screenCenter.y + fromCenter.y * (screenCenter.y - marginY), marginY, Screen.height - marginY);
waypointRect.position = new Vector3(clampedX, clampedY, 0f);
// Поворачиваем стрелку в направлении машины
arrowRect.gameObject.SetActive(true);
float angle = Mathf.Atan2(fromCenter.y, fromCenter.x) * Mathf.Rad2Deg - 90f;
arrowRect.rotation = Quaternion.Euler(0f, 0f, angle);
arrowRect.anchoredPosition = new Vector2(fromCenter.x * 125f, fromCenter.y * 32f);
}
else
{
waypointRect.position = screenPos;
arrowRect.gameObject.SetActive(false);
}
// Мягкая пульсация иконки
float pulse = 1f + Mathf.Sin(Time.time * 4f) * 0.08f;
iconImage.transform.localScale = new Vector3(pulse, pulse, 1f);
}
private void ShowArrivalBanner()
{
if (arrivalBanner == null) return;
arrivalBanner.SetActive(true);
arrivalBannerTimer = 5f;
PhoneAudioFeedback.Instance.PlayArrival();
}
private void UpdateArrivalBanner()
{
if (arrivalBanner == null || !arrivalBanner.activeSelf) return;
if (arrivalBannerTimer > 0f)
{
arrivalBannerTimer -= Time.deltaTime;
arrivalBannerGroup.alpha = Mathf.MoveTowards(arrivalBannerGroup.alpha, 1f, Time.deltaTime * 3f);
}
else
{
arrivalBannerGroup.alpha = Mathf.MoveTowards(arrivalBannerGroup.alpha, 0f, Time.deltaTime * 2f);
if (arrivalBannerGroup.alpha <= 0.01f)
arrivalBanner.SetActive(false);
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 473faba97f2d6ef43a5dd40b38123be0
@@ -0,0 +1,164 @@
using UnityEngine;
/// <summary>
/// Генератор приятных процедурных звуковых эффектов для смартфона (разблокировка, клики, уведомления от продавца).
/// Не требует внешних .wav файлов.
/// </summary>
public class PhoneAudioFeedback : MonoBehaviour
{
private static PhoneAudioFeedback instance;
public static PhoneAudioFeedback Instance
{
get
{
if (instance == null)
{
GameObject obj = new GameObject("PhoneAudioFeedback");
instance = obj.AddComponent<PhoneAudioFeedback>();
if (Application.isPlaying) DontDestroyOnLoad(obj);
}
return instance;
}
}
private AudioSource audioSource;
private AudioClip tapClip;
private AudioClip unlockClip;
private AudioClip notificationClip;
private AudioClip arrivalClip;
private void Awake()
{
if (instance == null) instance = this;
else if (instance != this)
{
Destroy(gameObject);
return;
}
audioSource = gameObject.AddComponent<AudioSource>();
audioSource.playOnAwake = false;
audioSource.spatialBlend = 0f; // 2D UI sound
GenerateClips();
}
private void GenerateClips()
{
tapClip = CreateTone(1400f, 0.035f, 0.25f, true);
unlockClip = CreateUnlockJingle();
notificationClip = CreateNotificationDing();
arrivalClip = CreateArrivalChord();
}
public void PlayTap()
{
if (tapClip != null && audioSource != null)
audioSource.PlayOneShot(tapClip, 0.35f);
}
public void PlayUnlock()
{
if (unlockClip != null && audioSource != null)
audioSource.PlayOneShot(unlockClip, 0.45f);
}
public void PlayNotification()
{
if (notificationClip != null && audioSource != null)
audioSource.PlayOneShot(notificationClip, 0.6f);
}
public void PlayArrival()
{
if (arrivalClip != null && audioSource != null)
audioSource.PlayOneShot(arrivalClip, 0.7f);
}
private AudioClip CreateTone(float frequency, float duration, float volume, bool decay)
{
int sampleRate = 44100;
int sampleCount = Mathf.CeilToInt(sampleRate * duration);
float[] samples = new float[sampleCount];
for (int i = 0; i < sampleCount; i++)
{
float t = (float)i / sampleRate;
float env = decay ? Mathf.Exp(-t * 12f / duration) : 1f;
samples[i] = Mathf.Sin(2f * Mathf.PI * frequency * t) * volume * env;
}
AudioClip clip = AudioClip.Create("Phone_Tone", sampleCount, 1, sampleRate, false);
clip.SetData(samples, 0);
return clip;
}
private AudioClip CreateUnlockJingle()
{
int sampleRate = 44100;
float duration = 0.18f;
int sampleCount = Mathf.CeilToInt(sampleRate * duration);
float[] samples = new float[sampleCount];
for (int i = 0; i < sampleCount; i++)
{
float t = (float)i / sampleRate;
float freq = Mathf.Lerp(480f, 820f, t / duration);
float env = Mathf.Sin((t / duration) * Mathf.PI);
samples[i] = Mathf.Sin(2f * Mathf.PI * freq * t) * 0.35f * env;
}
AudioClip clip = AudioClip.Create("Phone_Unlock", sampleCount, 1, sampleRate, false);
clip.SetData(samples, 0);
return clip;
}
private AudioClip CreateNotificationDing()
{
int sampleRate = 44100;
float duration = 0.35f;
int sampleCount = Mathf.CeilToInt(sampleRate * duration);
float[] samples = new float[sampleCount];
for (int i = 0; i < sampleCount; i++)
{
float t = (float)i / sampleRate;
// Двухтональный звонок (880 Гц -> 1320 Гц)
float freq = (t < 0.1f) ? 880f : 1320f;
float subT = (t < 0.1f) ? t : (t - 0.1f);
float env = Mathf.Exp(-subT * 7f);
samples[i] = Mathf.Sin(2f * Mathf.PI * freq * t) * 0.45f * env;
}
AudioClip clip = AudioClip.Create("Phone_Notification", sampleCount, 1, sampleRate, false);
clip.SetData(samples, 0);
return clip;
}
private AudioClip CreateArrivalChord()
{
int sampleRate = 44100;
float duration = 0.65f;
int sampleCount = Mathf.CeilToInt(sampleRate * duration);
float[] samples = new float[sampleCount];
// Мажорный аккорд: C5 (523Hz), E5 (659Hz), G5 (784Hz)
float[] freqs = new float[] { 523.25f, 659.25f, 783.99f };
for (int i = 0; i < sampleCount; i++)
{
float t = (float)i / sampleRate;
float env = Mathf.Exp(-t * 4.5f);
float s = 0f;
for (int f = 0; f < freqs.Length; f++)
{
s += Mathf.Sin(2f * Mathf.PI * freqs[f] * t);
}
samples[i] = (s / freqs.Length) * 0.5f * env;
}
AudioClip clip = AudioClip.Create("Waypoint_Arrival", sampleCount, 1, sampleRate, false);
clip.SetData(samples, 0);
return clip;
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 040f8559420527c4e97c0735d735a886
@@ -0,0 +1,501 @@
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Процедурный генератор высококачественных сглаженных спрайтов для смартфона и интерфейса.
/// Позволяет создавать ультра-четкий современный UI без внешних тяжелых текстур.
/// </summary>
public static class ProceduralUISprites
{
private static readonly Dictionary<string, Sprite> spriteCache = new Dictionary<string, Sprite>();
/// <summary>
/// Создает 9-sliced скругленный прямоугольник с настраиваемым радиусом и рамкой.
/// </summary>
public static Sprite GetSlicedRoundedRect(Color fillColor, Color? borderColor = null, float borderWidth = 0f, int cornerRadius = 18)
{
int size = Mathf.Max(64, cornerRadius * 2 + 16);
string key = $"s_rr_{size}_{cornerRadius}_{fillColor}_{borderColor}_{borderWidth}";
if (spriteCache.TryGetValue(key, out Sprite cached) && cached != null)
return cached;
Texture2D tex = new Texture2D(size, size, TextureFormat.RGBA32, false)
{
filterMode = FilterMode.Bilinear,
wrapMode = TextureWrapMode.Clamp
};
Color border = borderColor ?? fillColor;
float half = size * 0.5f;
float r = cornerRadius;
float innerBoxHalf = half - r;
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
{
float px = x + 0.5f - half;
float py = y + 0.5f - half;
float qx = Mathf.Max(0f, Mathf.Abs(px) - innerBoxHalf);
float qy = Mathf.Max(0f, Mathf.Abs(py) - innerBoxHalf);
float dist = Mathf.Sqrt(qx * qx + qy * qy);
float outerAlpha = Mathf.Clamp01(r - dist + 0.6f);
if (outerAlpha <= 0.001f)
{
tex.SetPixel(x, y, Color.clear);
continue;
}
if (borderWidth > 0f)
{
float borderT = Mathf.Clamp01((r - borderWidth - dist + 0.6f));
Color pixelColor = Color.Lerp(border, fillColor, borderT);
pixelColor.a *= outerAlpha;
tex.SetPixel(x, y, pixelColor);
}
else
{
Color pixelColor = fillColor;
pixelColor.a *= outerAlpha;
tex.SetPixel(x, y, pixelColor);
}
}
}
tex.Apply();
Vector4 borderSlice = new Vector4(cornerRadius + 2, cornerRadius + 2, cornerRadius + 2, cornerRadius + 2);
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, size, size), new Vector2(0.5f, 0.5f), 100f, 0, SpriteMeshType.FullRect, borderSlice);
spriteCache[key] = sprite;
return sprite;
}
/// <summary>
/// Создает гладкий круг с опциональной обводкой.
/// </summary>
public static Sprite GetCircle(int size, Color fillColor, Color? borderColor = null, float borderWidth = 0f)
{
string key = $"circle_{size}_{fillColor}_{borderColor}_{borderWidth}";
if (spriteCache.TryGetValue(key, out Sprite cached) && cached != null)
return cached;
Texture2D tex = new Texture2D(size, size, TextureFormat.RGBA32, false)
{
filterMode = FilterMode.Bilinear,
wrapMode = TextureWrapMode.Clamp
};
Color border = borderColor ?? fillColor;
float center = (size - 1) * 0.5f;
float radius = size * 0.5f - 1f;
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
{
float dist = Vector2.Distance(new Vector2(x, y), new Vector2(center, center));
float alpha = Mathf.Clamp01(radius - dist + 0.6f);
if (alpha <= 0.001f)
{
tex.SetPixel(x, y, Color.clear);
continue;
}
if (borderWidth > 0f)
{
float borderT = Mathf.Clamp01(radius - borderWidth - dist + 0.6f);
Color col = Color.Lerp(border, fillColor, borderT);
col.a *= alpha;
tex.SetPixel(x, y, col);
}
else
{
Color col = fillColor;
col.a *= alpha;
tex.SetPixel(x, y, col);
}
}
}
tex.Apply();
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, size, size), new Vector2(0.5f, 0.5f));
spriteCache[key] = sprite;
return sprite;
}
/// <summary>
/// Создает стильный вертикальный градиент (например, для обоев рабочего стола телефона).
/// </summary>
public static Sprite GetGradient(int width, int height, Color topColor, Color bottomColor)
{
string key = $"grad_{width}_{height}_{topColor}_{bottomColor}";
if (spriteCache.TryGetValue(key, out Sprite cached) && cached != null)
return cached;
Texture2D tex = new Texture2D(width, height, TextureFormat.RGBA32, false)
{
filterMode = FilterMode.Bilinear,
wrapMode = TextureWrapMode.Clamp
};
for (int y = 0; y < height; y++)
{
float t = (float)y / Mathf.Max(1, height - 1);
Color col = Color.Lerp(bottomColor, topColor, t);
for (int x = 0; x < width; x++)
{
tex.SetPixel(x, y, col);
}
}
tex.Apply();
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, width, height), new Vector2(0.5f, 0.5f));
spriteCache[key] = sprite;
return sprite;
}
/// <summary>
/// Создает иконку Wi-Fi.
/// </summary>
public static Sprite GetWifiIcon(int size, Color color)
{
string key = $"wifi_{size}_{color}";
if (spriteCache.TryGetValue(key, out Sprite cached) && cached != null)
return cached;
Texture2D tex = new Texture2D(size, size, TextureFormat.RGBA32, false)
{
filterMode = FilterMode.Bilinear,
wrapMode = TextureWrapMode.Clamp
};
Vector2 center = new Vector2((size - 1) * 0.5f, size * 0.2f);
float[] radii = new float[] { size * 0.65f, size * 0.45f, size * 0.25f };
float arcHalfAngle = 42f;
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
{
Vector2 pos = new Vector2(x, y);
float dist = Vector2.Distance(pos, center);
Vector2 dir = pos - center;
float angle = Mathf.Atan2(dir.x, dir.y) * Mathf.Rad2Deg;
float alpha = 0f;
// Базовая точка внизу
if (dist <= size * 0.1f)
{
alpha = Mathf.Clamp01(size * 0.1f - dist + 0.6f);
}
else if (Mathf.Abs(angle) <= arcHalfAngle && dir.y > 0)
{
float angleFade = Mathf.Clamp01((arcHalfAngle - Mathf.Abs(angle)) / 6f);
foreach (float r in radii)
{
float ringDist = Mathf.Abs(dist - r);
float ringThickness = size * 0.05f;
if (ringDist <= ringThickness)
{
float ringAlpha = Mathf.Clamp01(ringThickness - ringDist + 0.5f) * angleFade;
alpha = Mathf.Max(alpha, ringAlpha);
}
}
}
Color c = color;
c.a *= alpha;
tex.SetPixel(x, y, c);
}
}
tex.Apply();
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, size, size), new Vector2(0.5f, 0.5f));
spriteCache[key] = sprite;
return sprite;
}
/// <summary>
/// Создает иконку полос мобильной сети (Cellular Signal Bars).
/// </summary>
public static Sprite GetSignalBarsIcon(int width, int height, Color activeColor, int activeBars = 4)
{
string key = $"bars_{width}_{height}_{activeColor}_{activeBars}";
if (spriteCache.TryGetValue(key, out Sprite cached) && cached != null)
return cached;
Texture2D tex = new Texture2D(width, height, TextureFormat.RGBA32, false)
{
filterMode = FilterMode.Point,
wrapMode = TextureWrapMode.Clamp
};
// Заполняем прозрачным
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
tex.SetPixel(x, y, Color.clear);
int totalBars = 4;
float barWidth = (width - (totalBars - 1) * 2f) / totalBars;
for (int b = 0; b < totalBars; b++)
{
float barHeight = height * ((b + 1f) / totalBars);
float startX = b * (barWidth + 2f);
Color barCol = (b < activeBars) ? activeColor : new Color(activeColor.r, activeColor.g, activeColor.b, 0.25f);
for (int y = 0; y < Mathf.RoundToInt(barHeight); y++)
{
for (int x = Mathf.RoundToInt(startX); x < Mathf.RoundToInt(startX + barWidth); x++)
{
if (x < width && y < height)
tex.SetPixel(x, y, barCol);
}
}
}
tex.Apply();
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, width, height), new Vector2(0.5f, 0.5f));
spriteCache[key] = sprite;
return sprite;
}
/// <summary>
/// Создает иконку батареи с уровнем заряда.
/// </summary>
public static Sprite GetBatteryIcon(int width, int height, Color bodyColor, Color levelColor, float percentage = 0.85f)
{
string key = $"batt_{width}_{height}_{bodyColor}_{levelColor}_{percentage:F2}";
if (spriteCache.TryGetValue(key, out Sprite cached) && cached != null)
return cached;
Texture2D tex = new Texture2D(width, height, TextureFormat.RGBA32, false)
{
filterMode = FilterMode.Bilinear,
wrapMode = TextureWrapMode.Clamp
};
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
tex.SetPixel(x, y, Color.clear);
int tipW = 3;
int mainW = width - tipW - 1;
int tipH = Mathf.RoundToInt(height * 0.45f);
int tipYStart = (height - tipH) / 2;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
// Пипка справа
if (x >= mainW && x < width && y >= tipYStart && y < tipYStart + tipH)
{
tex.SetPixel(x, y, bodyColor);
continue;
}
// Корпус батарейки
if (x < mainW)
{
bool isBorder = (x == 0 || x == mainW - 1 || y == 0 || y == height - 1);
if (isBorder)
{
tex.SetPixel(x, y, bodyColor);
}
else
{
// Заполнение уровня заряда внутри (с отступом 2 пикселя)
float innerFillW = (mainW - 4) * Mathf.Clamp01(percentage);
if (x >= 2 && x < 2 + innerFillW && y >= 2 && y < height - 2)
{
tex.SetPixel(x, y, levelColor);
}
}
}
}
}
tex.Apply();
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, width, height), new Vector2(0.5f, 0.5f));
spriteCache[key] = sprite;
return sprite;
}
/// <summary>
/// Создает стилизованную векторную иконку автомобиля для приложения АвтоБазар.
/// </summary>
public static Sprite GetCarIcon(int size, Color color)
{
string key = $"car_ico_{size}_{color}";
if (spriteCache.TryGetValue(key, out Sprite cached) && cached != null)
return cached;
Texture2D tex = new Texture2D(size, size, TextureFormat.RGBA32, false)
{
filterMode = FilterMode.Bilinear,
wrapMode = TextureWrapMode.Clamp
};
for (int y = 0; y < size; y++)
for (int x = 0; x < size; x++)
tex.SetPixel(x, y, Color.clear);
// Рисуем силуэт автомобиля в профиль
float s = size;
for (int y = 0; y < size; y++)
{
float ny = y / s;
for (int x = 0; x < size; x++)
{
float nx = x / s;
bool isBody = false;
// Нижний кузов (от nx=0.1 до 0.9, ny=0.35 до 0.55)
if (nx >= 0.12f && nx <= 0.88f && ny >= 0.35f && ny <= 0.52f)
isBody = true;
// Кабина / крыша (от nx=0.28 до 0.72, ny=0.50 до 0.70)
if (ny >= 0.50f && ny <= 0.68f)
{
float roofMin = Mathf.Lerp(0.20f, 0.34f, (ny - 0.50f) / 0.18f);
float roofMax = Mathf.Lerp(0.85f, 0.68f, (ny - 0.50f) / 0.18f);
if (nx >= roofMin && nx <= roofMax)
isBody = true;
}
// Вырезы под колеса
float distWheel1 = Vector2.Distance(new Vector2(nx, ny), new Vector2(0.28f, 0.35f));
float distWheel2 = Vector2.Distance(new Vector2(nx, ny), new Vector2(0.72f, 0.35f));
if (distWheel1 < 0.11f || distWheel2 < 0.11f)
isBody = false;
// Сами колеса (шины)
if (distWheel1 < 0.09f || distWheel2 < 0.09f)
isBody = true;
if (isBody)
tex.SetPixel(x, y, color);
}
}
tex.Apply();
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, size, size), new Vector2(0.5f, 0.5f));
spriteCache[key] = sprite;
return sprite;
}
/// <summary>
/// Создает векторную иконку геометки / пина навигатора.
/// </summary>
public static Sprite GetMapPinIcon(int size, Color color)
{
string key = $"pin_ico_{size}_{color}";
if (spriteCache.TryGetValue(key, out Sprite cached) && cached != null)
return cached;
Texture2D tex = new Texture2D(size, size, TextureFormat.RGBA32, false)
{
filterMode = FilterMode.Bilinear,
wrapMode = TextureWrapMode.Clamp
};
for (int y = 0; y < size; y++)
for (int x = 0; x < size; x++)
tex.SetPixel(x, y, Color.clear);
Vector2 headCenter = new Vector2(size * 0.5f, size * 0.65f);
float headRadius = size * 0.28f;
Vector2 tip = new Vector2(size * 0.5f, size * 0.12f);
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
{
Vector2 pos = new Vector2(x, y);
float distHead = Vector2.Distance(pos, headCenter);
float alpha = 0f;
// Верхняя округлая часть пина
if (distHead <= headRadius)
{
alpha = Mathf.Clamp01(headRadius - distHead + 0.6f);
// Отверстие в центре пина
float holeRadius = headRadius * 0.42f;
if (distHead < holeRadius)
{
alpha = Mathf.Clamp01(distHead - holeRadius + 0.6f);
}
}
// Нижний конусообразный хвостик
else if (y < headCenter.y && y >= tip.y)
{
float progress = (headCenter.y - y) / (headCenter.y - tip.y);
float coneWidth = Mathf.Lerp(headRadius * 0.95f, 2f, progress);
float dx = Mathf.Abs(x - tip.x);
if (dx <= coneWidth)
{
alpha = Mathf.Clamp01(coneWidth - dx + 0.6f);
}
}
Color c = color;
c.a *= alpha;
tex.SetPixel(x, y, c);
}
}
tex.Apply();
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, size, size), new Vector2(0.5f, 0.5f));
spriteCache[key] = sprite;
return sprite;
}
/// <summary>
/// Создает стрелку указателя направления (для указания на машину вне экрана).
/// </summary>
public static Sprite GetPointerArrow(int size, Color color)
{
string key = $"arrow_{size}_{color}";
if (spriteCache.TryGetValue(key, out Sprite cached) && cached != null)
return cached;
Texture2D tex = new Texture2D(size, size, TextureFormat.RGBA32, false)
{
filterMode = FilterMode.Bilinear,
wrapMode = TextureWrapMode.Clamp
};
for (int y = 0; y < size; y++)
for (int x = 0; x < size; x++)
tex.SetPixel(x, y, Color.clear);
float center = (size - 1) * 0.5f;
for (int y = 0; y < size; y++)
{
float ny = (float)y / size; // 0..1 (вверх)
float halfW = Mathf.Lerp(0f, size * 0.45f, 1f - ny);
for (int x = 0; x < size; x++)
{
float dx = Mathf.Abs(x - center);
if (dx <= halfW)
{
float a = Mathf.Clamp01(halfW - dx + 0.6f);
Color c = color;
c.a *= a;
tex.SetPixel(x, y, c);
}
}
}
tex.Apply();
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, size, size), new Vector2(0.5f, 0.5f));
spriteCache[key] = sprite;
return sprite;
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: dd21cf2efce2fc84a98a88b3940f0708
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 137929786778a74448ac28bb19488fa6