Skip to content

Instantly share code, notes, and snippets.

@unitycoder
Created August 30, 2023 18:02
Show Gist options
  • Select an option

  • Save unitycoder/5e5c14fba4a00b6bfa6e34155f113f69 to your computer and use it in GitHub Desktop.

Select an option

Save unitycoder/5e5c14fba4a00b6bfa6e34155f113f69 to your computer and use it in GitHub Desktop.
Simple 2D Minimap Player position indicator
// see making-of video at https://youtu.be/_xkqcyW40g8
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Minimap : MonoBehaviour
{
public Renderer mapBoundsRenderer;
public Transform player;
public RectTransform playerIcon;
public RectTransform minimapBoundsRect;
Bounds mapBounds;
Rect minimapRect;
void Start()
{
mapBounds = mapBoundsRenderer.bounds;
minimapRect = minimapBoundsRect.rect;
}
void LateUpdate()
{
float x = Remap(player.position.x, mapBounds.min.x, mapBounds.max.x, 0, minimapRect.width);
// minus height, because UI is anchored at top right
float y = Remap(player.position.z, mapBounds.min.z, mapBounds.max.z, 0, minimapRect.height) - minimapRect.height;
Vector2 newPlayerPos = new Vector2(x, y);
// clamp player icon to bounds
// TODO could swap icon if out of bounds
newPlayerPos.x = Mathf.Clamp(newPlayerPos.x, 0, minimapRect.width);
newPlayerPos.y = Mathf.Clamp(newPlayerPos.y, -minimapRect.height, 0);
// set position
playerIcon.anchoredPosition = newPlayerPos;
// set rotation
playerIcon.localEulerAngles = new Vector3(0, 0, -player.eulerAngles.y + 180) ;
}
float Remap(float source, float sourceFrom, float sourceTo, float targetFrom, float targetTo)
{
return targetFrom + (source - sourceFrom) * (targetTo - targetFrom) / (sourceTo - sourceFrom);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment