/* INFINITY CODE 2013-2019 */ /* http://www.infinity-code.com */ using UnityEngine; namespace InfinityCode.OnlineMapsExamples { /// /// How to make the map follow GameObject /// public class FollowGameObject : MonoBehaviour { /// /// GameObject to be followed by the map /// public GameObject target; /// /// Last position of GameObject /// private Vector3 lastPosition; /// /// Reference to the map /// private OnlineMaps map; /// /// Reference to the control /// private OnlineMapsTileSetControl control; /// /// Last tile position of the center of the map /// private double tx, ty; private void Start() { // Set a reference to the map and control map = OnlineMaps.instance; control = OnlineMapsTileSetControl.instance; // Disable the movement and zoom of the map with the mouse control.allowUserControl = false; control.allowZoom = false; // Subscribe to change zoom event map.OnChangeZoom += OnChangeZoom; // Store tile position of the center of the map map.GetTilePosition(out tx, out ty); // Initial update the map UpdateMap(); } /// /// This method is called when the zoom changes (in this case, using a script or inspector) /// private void OnChangeZoom() { // Store tile position of the center of the map map.GetTilePosition(out tx, out ty); } private void Update() { // If GameObject position has changed, update the map if (target.transform.position != lastPosition) UpdateMap(); } /// /// Updates map position /// private void UpdateMap() { // Store last position of GameObject lastPosition = target.transform.position; // Size of map in scene Vector2 size = control.sizeInScene; // Calculate center point of the map in the scene Vector3 center = new Vector3(size.x / -2, 0, size.y / 2); // Calculate offset (in tile position) Vector3 offset = lastPosition - map.transform.position - center; offset.x = offset.x / OnlineMapsUtils.tileSize / size.x * map.width * map.zoomCoof; offset.z = offset.z / OnlineMapsUtils.tileSize / size.y * map.height * map.zoomCoof; // Calculate current tile position of the center of the map tx -= offset.x; ty += offset.z; // Set position of the map center map.SetTilePosition(tx, ty); // Update map GameObject position map.transform.position = lastPosition - center; } } }