Firstborn/Assets/Scripts/CompassBar.cs

67 lines
2.3 KiB
C#
Raw Normal View History

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using RPGCreationKit;
using UnityEngine.UI;
using TMPro;
using System;
using RPGCreationKit.Player;
using UnityEngine.EventSystems;
namespace RPGCreationKit
{
public class CompassBar : MonoBehaviour
{
public GameObject IconPrefab;
List<QuestMarker> questMarkers = new List<QuestMarker>();
public RawImage CompassImage;
public Transform Player;
public float MaxDistance = 200f;
float compassUnit;
// Start is called before the first frame update
void Start() {
compassUnit = CompassImage.rectTransform.rect.width / 360f;
}
// Update is called once per frame
private void Update() {
CompassImage.uvRect = new Rect (Player.localEulerAngles.y / 360f, 0f, 1f, 1f);
foreach (QuestMarker marker in questMarkers) {
marker.image.rectTransform.anchoredPosition = GetPosOnCompass(marker);
float dst = Vector2.Distance(new Vector2(Player.transform.position.x, Player.transform.position.z), marker.position);
float scale = 0f;
if (dst < MaxDistance) {
scale = 1f - (dst / MaxDistance);
}
marker.image.rectTransform.localScale = Vector3.one * scale;
}
}
public void AddQuestMarker(QuestMarker marker) {
GameObject NewMarker = Instantiate(IconPrefab, CompassImage.transform);
marker.image = NewMarker.GetComponent<Image>();
marker.image.sprite = marker.icon;
questMarkers.Add(marker);
}
public void RemoveQuestMarker(QuestMarker marker) {
marker.image.rectTransform.localScale = Vector3.one * 0f;
marker.image.sprite = null;
questMarkers.Remove(marker);
}
Vector2 GetPosOnCompass(QuestMarker marker) {
Vector2 playerPos = new Vector2(Player.transform.position.x, Player.transform.position.z);
Vector2 playerFwd = new Vector2(Player.transform.forward.x, Player.transform.forward.z);
float angle = Vector2.SignedAngle(marker.position - playerPos, playerFwd);
return new Vector2(compassUnit * angle, 0f);
}
}
}