An isometric mobile puzzle game in which you swipe tiles around to find your way through each level and keep your flame burning.
Made in Unity 2017.1 using C#. Currently in open-alpha on the Play Store.
Scripts
Below you can look at some of the scripts I wrote for this project.
I used my own preference for conventions here, but I’d have no problem using others’.
A quick sum-up:
Player Movement
Pathfinding
Tile
Touch Manager
Rotator
Player Movement
Used for the actual movement of the player when the user taps on a tile. Utilises the Pathfinder class.
To be able to do tests without always needing to build to mobile I wrote some of the functionality for the Unity editor as well.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 |
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using EmberSkies.Gameplay.AI; using EmberSkies.Level; using EmberSkies.Util; using EmberSkies.Input; using Logger = EmberSkies.Util.Logger; namespace EmberSkies.Gameplay { using Input = UnityEngine.Input; using Camera = UnityEngine.Camera; public class Player : MonoBehaviour { #region Events private event EventHandler m_ReachedTargetEvent; public event EventHandler ReachedTargetEvent { add { m_ReachedTargetEvent += value; } remove { m_ReachedTargetEvent -= value; } } #endregion Events #region Members private Logger m_Logger; private Camera m_Camera; private TouchManager m_TouchManager; private GameObject m_OriginalParent; private TileNode m_CurrentNode; private TileNode[] m_CurrentPath; private Coroutine m_CurrentMoveRoutine; private bool m_HasTouchMoved; #endregion Members #region Serialized Members [SerializeField] private Tile m_StartingTile; [SerializeField] private float m_JumpingHeight; [SerializeField] private AnimationCurve m_JumpingCurve; [SerializeField] private Animator m_Animator; [SerializeField] private int m_MaxStepHeight; [SerializeField] private float m_Speed; [SerializeField] private bool m_IsSelected = false; #endregion Serialized Members #region Properties public int MaxStepHeight { get { return m_MaxStepHeight; } } public bool IsSelected { get { return m_IsSelected; } } public float Speed { get { return m_Speed; } } public GameObject OriginalParent { get { return m_OriginalParent; } } #endregion Properties private void Awake() { m_Logger = new Logger(this, Logger.BLUE); m_OriginalParent = transform.parent.gameObject; m_CurrentNode = m_StartingTile.Node; } private void Start() { transform.position = m_CurrentNode.transform.position; m_Camera = Camera.main; m_TouchManager = TouchManager.Instance; } public void SetSelected(bool selected) { m_IsSelected = selected; m_Logger.Log($"{(selected ? "S" : "Des")}elected!"); } #region Movement Functions public void Move(TileNode targetNode, float stepHeight) { if (targetNode != null) { if (targetNode.Tile.Type != TileType.Decoration) { if (targetNode != m_CurrentNode) { TileNode[] newPath = Pathfinder.FindPath(m_CurrentNode, targetNode, m_MaxStepHeight); /* * Move if there's a new path and we aren't moving already. */ if (newPath != null && newPath.Length > 0) { if (m_CurrentMoveRoutine == null) { m_CurrentMoveRoutine = StartCoroutine(TravelPathRoutine(newPath, m_Speed)); m_CurrentPath = newPath; return; } } } } } SetSelected(false); } public void Move(TileNode target) { Move(target, m_MaxStepHeight); } private IEnumerator TravelPathRoutine(TileNode[] path, float speed) { /* * Loop through each path node. */ int length = path.Length; for (int i = 0; i < length; i++) { TileNode currentNode = m_CurrentNode; TileNode nextNode = path[i]; Vector3 currentPos = currentNode.transform.position; Vector3 targetPos = nextNode.transform.position; float distToNextNode = Vector3.Distance(currentPos, targetPos); float startingTime = Time.time; float time = .0f; float jumpWaitTime = .5f; bool waitedForJump = false; bool isJump = false; /* * Rotate the player to the walking direction. */ float angle = MathUtil.GetAngleBetween(new Vector2(currentPos.x, currentPos.z), new Vector2(targetPos.x, targetPos.z)); transform.rotation = Quaternion.AngleAxis(angle + 90.0f, transform.up); /* * Move towards the next node in the appropriate manner until we reached it. */ while (Vector3.Distance(transform.position, targetPos) > .01f) { time += Time.deltaTime; /* * If we need to jump then make sure we've waited a bit for the animation first. */ if (isJump && !waitedForJump) { yield return new WaitForSeconds(jumpWaitTime); waitedForJump = true; continue; } //float timeDiff = Time.time - startingTime; float distCovered = /*timeDiff*/ time * speed; float fracJourney = distCovered / distToNextNode; float t = fracJourney; Vector3 newPosition = Vector3.Lerp(currentPos, targetPos, t); /* * If there is a height difference to the next node, then we need to jump. */ if (Mathf.RoundToInt(Mathf.Abs((targetPos - currentPos).y)) != 0) { isJump = true; m_Animator.SetBool("IsJumping", true); /* * Don't actually move yet until we've waited for the animation. */ if (waitedForJump) { newPosition.y += m_JumpingCurve.Evaluate(fracJourney) * m_JumpingHeight; } } else { m_Animator.SetFloat("Speed", 1); } // Apply final change in position. transform.position = newPosition; yield return null; } m_Animator.SetBool("IsJumping", false); /* * Hard-set the values in the end just in case we couldn't precisely reach the target mathematically. */ transform.position = targetPos; m_CurrentNode = nextNode; } SetSelected(false); m_ReachedTargetEvent?.Invoke(this, EventArgs.Empty); m_Animator.SetFloat("Speed", 0); m_CurrentMoveRoutine = null; } #endregion Movement Functions private void OnDrawGizmos() { if (m_CurrentPath != null && m_CurrentPath.Length > 0) { Gizmos.color = Color.red; for (int i = 0; i < m_CurrentPath.Length; i++) { Gizmos.DrawWireCube(m_CurrentPath[i].transform.position, Vector3.one); } } if (m_CurrentNode != null) { Gizmos.color = Color.green; Gizmos.DrawWireCube(m_CurrentNode.transform.position, Vector3.one); } } private void Update() { #region Editor #if UNITY_EDITOR if (Application.isEditor) { if (Input.GetMouseButtonDown(0)) { Ray ray = m_Camera.ScreenPointToRay(Input.mousePosition); RaycastHit hitInfo; if (Physics.Raycast(ray, out hitInfo, m_Camera.farClipPlane)) { /* * If the player is selected, move it to the tile that's clicked on. */ if (m_IsSelected) { Tile tileHit = hitInfo.transform.parent.GetComponent<Tile>(); TileNode tileNodeHit = hitInfo.collider.gameObject.GetComponent<TileNode>(); TileNode targetTileNode = null; if (tileHit != null) { targetTileNode = tileHit.Node; } else if (tileNodeHit != null) { targetTileNode = tileNodeHit; } Move(targetTileNode); } /* * Select/deselect the player if clicked on. */ if (hitInfo.collider.gameObject.GetComponent<Player>() == this) { SetSelected(!m_IsSelected); } } } } #endif #endregion Editor #region Android #if UNITY_ANDROID if (Application.isMobilePlatform) { if (Input.touchCount > 0) { Touch touch = Input.touches[0]; /* * If the touch moves, remember that until it ends or cancels. */ if (m_TouchManager.TouchDeltas[0].magnitude > m_TouchManager.MaxStationaryTouchDeadzonePx) { if (!m_HasTouchMoved) { m_HasTouchMoved = true; m_Logger.Log("Touch has moved!"); } } /* * Move to the tile we're pointing at after the touch is released. */ if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled) { if (!m_HasTouchMoved) { Ray ray = m_Camera.ScreenPointToRay(touch.position); RaycastHit hitInfo; bool hitSuccess = Physics.Raycast(ray, out hitInfo, m_Camera.farClipPlane, LayerMask.GetMask("Tile", "TileNode")); if (hitSuccess) { Tile tileHit = hitInfo.transform.parent.GetComponent<Tile>(); TileNode tileNodeHit = hitInfo.collider.gameObject.GetComponent<TileNode>(); TileNode targetNode = null; if (tileHit != null) { targetNode = tileHit.Node; } else if (tileNodeHit != null) { targetNode = tileNodeHit; } Move(targetNode); } } } } else { m_HasTouchMoved = false; } } #endif #endregion Android } } } |
Pathfinding
This script simply finds paths between one tile and another using a specialised A* system properly integrated with the levels.
It takes things like height differences, diagonals, and path history into account.
Right now only the player entity uses this script, but it can and will be used by any entity needed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 |
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using EmberSkies.Level; namespace EmberSkies.Gameplay.AI { using Logger = Util.Logger; public static class Pathfinder { #region Members private static Logger m_Logger = new Logger("Pathfinder", Logger.GREEN); private static PathNode[,] m_PathNodeMap; private static TileNode m_StartNode; private static TileNode m_TargetNode; #endregion Members #region Path Node Map Functions private static void RefreshPathNodeMap() { Tile[,] tileMap = Tile.TileMap; int tileMapWidth = tileMap.GetLength(0); int tileMapHeight = tileMap.GetLength(1); m_PathNodeMap = new PathNode[tileMapWidth, tileMapHeight]; for (int y = 0; y < tileMapHeight; y++) { for (int x = 0; x < tileMapWidth; x++) { Tile tile = tileMap[x, y]; if (tile != null) { TileNode node = tile.Node; m_PathNodeMap[x, y] = new PathNode(node, x, y); } } } } private static List<PathNode> GetPathNodeNeighbours(PathNode node) { List<PathNode> neighbours = new List<PathNode>(); for (int y = -1; y <= 1; y++) { for (int x = -1; x <= 1; x++) { if ((x == 0 && y == 0) || (x != 0 && y != 0)) { continue; } int xCheck = node.MapX + x; int yCheck = node.MapY + y; int pathNodeMapWidth = m_PathNodeMap.GetLength(0); int pathNodeMapHeight = m_PathNodeMap.GetLength(1); if (xCheck >= 0 && xCheck < pathNodeMapWidth && yCheck >= 0 && yCheck < pathNodeMapHeight) { neighbours.Add(m_PathNodeMap[xCheck, yCheck]); } } } return neighbours; } private static PathNode FindPathNodeFromNode(TileNode node) { int pathNodeMapWidth = m_PathNodeMap.GetLength(0); int pathNodeMapHeight = m_PathNodeMap.GetLength(1); for (int y = 0; y < pathNodeMapHeight; y++) { for (int x = 0; x < pathNodeMapWidth; x++) { PathNode pathNode = m_PathNodeMap[x, y]; if (pathNode != null) { if (pathNode.Node == node) { return pathNode; } } } } return null; } #endregion Path Node Map Functions public static TileNode[] FindPath(TileNode startNode, TileNode targetNode, float maxStepHeight) { m_StartNode = startNode; m_TargetNode = targetNode; RefreshPathNodeMap(); List<PathNode> openSet = new List<PathNode>(); HashSet<PathNode> closedSet = new HashSet<PathNode>(); PathNode startPathNode = FindPathNodeFromNode(m_StartNode); PathNode targetPathNode = FindPathNodeFromNode(m_TargetNode); PathNode currentPathNode = null; PathNode lastApprovedPathNode = null; openSet.Add(startPathNode); /* * Go through all the currently unprocessed available nodes to find out which we will need to reach the target. */ while (openSet.Count > 0) { currentPathNode = GetLowestFCostNode(openSet.ToArray()); openSet.Remove(currentPathNode); closedSet.Add(currentPathNode); /* * Stop if we reached the target. */ if (currentPathNode == targetPathNode) { m_Logger.Log("Found path to target!"); break; } /* * One of our current neighbours might be our progression towards the target... unless this is a dead end. */ List<PathNode> neighbours = GetPathNodeNeighbours(currentPathNode); for (int i = 0; i < neighbours.Count; i++) { PathNode neighbour = neighbours[i]; /* * Skip this neighbour if it's not legit, not walkable, has already been processed, or if the height difference is too big. */ if (neighbour != null && neighbour.Node.Tile.Data.IsWalkable && !closedSet.Contains(neighbour)) { float yDiff = (neighbour.Node.transform.position.y - currentPathNode.Node.transform.position.y); if (Mathf.Abs(yDiff) > maxStepHeight) { continue; } } else { continue; } int newCostToNeighbour = currentPathNode.GCost + GetNodeDistance(currentPathNode, neighbour); /* * Add the neighbour to the open set if it's not processed yet. */ if (newCostToNeighbour < neighbour.GCost || !openSet.Contains(neighbour)) { neighbour.GCost = newCostToNeighbour; neighbour.HCost = GetNodeDistance(neighbour, targetPathNode); neighbour.Parent = currentPathNode; lastApprovedPathNode = neighbour; if (!openSet.Contains(neighbour)) { openSet.Add(neighbour); } } } } if (lastApprovedPathNode != null) { Vector3 lastApprovedPathNodePos = currentPathNode.Node.transform.position; Vector3 startPathNodePos = startPathNode.Node.transform.position; Vector3 targetPathNodePos = targetPathNode.Node.transform.position; lastApprovedPathNodePos.y = .0f; startPathNodePos.y = .0f; targetPathNodePos.y = .0f; float lastApprovedToTargetDist = Vector3.Distance(lastApprovedPathNodePos, targetPathNodePos); float startToTargetDist = Vector3.Distance(startPathNodePos, targetPathNodePos); /* * Just a little check to avoid weird backtracking. * If the end of the path is actually closer to the target than we are currently, then go for it! */ if (lastApprovedToTargetDist < startToTargetDist) { m_Logger.Log("Found path!"); return GetRetracedPath(startPathNode, currentPathNode); } } return null; } private static TileNode[] GetRetracedPath(PathNode startNode, PathNode endNode) { List<TileNode> path = new List<TileNode>(); PathNode currentNode = endNode; while (currentNode != startNode) { path.Add(currentNode.Node); currentNode = currentNode.Parent; } path.Reverse(); return path.ToArray(); } private static int GetNodeDistance(PathNode nodeA, PathNode nodeB) { int distX = Mathf.Abs(nodeA.MapX - nodeB.MapX); int distY = Mathf.Abs(nodeB.MapY - nodeB.MapY); return (distX > distY) ? 14 * distY + 10 * (distX - distY) : 14 * distX + 10 * (distY - distX); } private static PathNode GetLowestFCostNode(PathNode[] nodes) { //return (from e in nodes orderby e.FCost ascending select e).First(); PathNode lowest = nodes[0]; for (int i = 1; i < nodes.Length; i++) { if (nodes[i].FCost < lowest.FCost) { lowest = nodes[i]; } } return lowest; } } } |
Tile
Handles things like tile movement (single & dual, including the mapping) and displaying direction indicative arrows.
Also applies its inspector-acquired data which orchestrates the specific functioning of the tile instance.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 |
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using EmberSkies.Gameplay; using EmberSkies.Input; using EmberSkies.Input.Events; using EmberSkies.Util; using EmberSkies.Management; using Random = UnityEngine.Random; namespace EmberSkies.Level { using Camera = UnityEngine.Camera; public enum TileType { Fixed = 0, MoveX, MoveY, MoveZ, Decoration } public class Tile : MonoBehaviour { #region Members private Player m_Player; private Camera m_Camera; private TouchManager m_TouchManager; private LevelManager m_LevelManager; protected static Tile[,] m_TileMap = new Tile[100, 100]; private Coroutine m_MoveRoutine; private bool m_IsOccupied; private int m_MapX; private int m_MapY; private Vector3 m_Direction; #endregion Members #region Serialized Members [Header("General")] [SerializeField] private TileData m_Data; [SerializeField] private TileType m_Type; [SerializeField] private bool m_IsLocked; [SerializeField] private bool m_IsFinish; [Header("Movement")] [SerializeField] private Tile m_Link; [SerializeField] private float m_RequiredSwipeSpeed; [SerializeField] private float m_SwipeErrorRange = 0.1f; [SerializeField] private int m_CurrentMoves; [SerializeField] private MinMax m_MaxMoveRange; [SerializeField] private float m_Speed; [Header("References")] [SerializeField] private Renderer m_Renderer; [SerializeField] private TileNode m_Node; [SerializeField] private GameObject m_FinishFlag; [Header("Arrows")] [SerializeField] private Color m_ArrowColor; [SerializeField] private SpriteRenderer m_NorthArrow; [SerializeField] private SpriteRenderer m_EastArrow; [SerializeField] private SpriteRenderer m_SouthArrow; [SerializeField] private SpriteRenderer m_WestArrow; [SerializeField] private List<SpriteRenderer> m_UpArrows; [SerializeField] private List<SpriteRenderer> m_DownArrows; #endregion Serialized Members #region Properties public static Tile[,] TileMap { get { return m_TileMap; } set { m_TileMap = value; } } public int MapX { get { return m_MapX; } } public int MapY { get { return m_MapY; } } public int Moves { get { return m_CurrentMoves; } set { m_CurrentMoves = value; } } public MinMax MaxMoveRange { get { return m_MaxMoveRange; } } public float VerticalSpeed { get { return m_Speed; } } public TileNode Node { get { return m_Node; } } public TileData Data { get { return m_Data; } set { m_Data = value; } } public Tile Link { get { return m_Link; } } public TileType Type { get { return m_Type; } set { m_Type = value; UpdateDirection(value); } } public bool IsLocked { get { return m_IsLocked; } set { m_IsLocked = value; } } public bool IsFinish { get { return m_IsFinish; } } public bool IsOccupied { get { return m_IsOccupied; } } public Vector3 Direction { get { return m_Direction; } } public Color ArrowColor { get { return m_ArrowColor; } } #endregion Properties private void Awake() { LoadTileData(); UpdateDirection(); RefreshArrows(); SetRandomCardinalRotation(); } private void Start() { m_Player = FindObjectOfType<Player>(); m_Camera = Camera.main; // Singleton Referencing m_TouchManager = TouchManager.Instance; m_LevelManager = LevelManager.Instance; // Event Subscriptions m_Player.ReachedTargetEvent += OnPlayerTargetReached; m_TouchManager.SwipeEvent += OnSwipe; OnPlayerTargetReached(this, EventArgs.Empty); RegisterMapPosition(); if (m_Type != TileType.Decoration) { m_FinishFlag?.SetActive(m_IsFinish); } } private void SetRandomCardinalRotation() { Vector3 newEuler = m_Renderer.transform.rotation.eulerAngles; newEuler.z = Random.Range(0, 4) * 90; m_Renderer.transform.rotation = Quaternion.Euler(newEuler); } #region On Event Functions private void OnValidate() { LoadTileData(); RefreshArrows(); if (m_Type != TileType.Decoration) { m_FinishFlag?.SetActive(m_IsFinish); } } private void OnPlayerTargetReached(object sender, EventArgs args) { if (m_Type != TileType.Decoration) { m_IsOccupied = (Vector3.Distance(m_Node.transform.position, m_Player.transform.position) < .5f); /* * Finish the level if we're a finish tile and the player stands on us. */ if (m_IsOccupied && m_IsFinish) { m_LevelManager.FinishCurrentLevel(); } } } private void OnSwipe(SwipeEventArgs args) { if (m_Type != TileType.Decoration) { if (!m_Player.IsSelected) { Ray ray = m_Camera.ScreenPointToRay(args.TouchOrigin); RaycastHit hitInfo; bool hitSuccess = Physics.Raycast(ray, out hitInfo, m_Camera.farClipPlane); if (hitSuccess) { if (hitInfo.transform.parent.GetComponent<Tile>() == this) { switch (m_Type) { case TileType.MoveX: MoveIfSwipedInDirection(Vector3.right, false, args.SwipeDelta); MoveIfSwipedInDirection(Vector3.left, true, args.SwipeDelta); break; case TileType.MoveY: MoveIfSwipedInDirection(Vector3.up, false, args.SwipeDelta); MoveIfSwipedInDirection(Vector3.down, true, args.SwipeDelta); break; case TileType.MoveZ: MoveIfSwipedInDirection(Vector3.forward, false, args.SwipeDelta); MoveIfSwipedInDirection(Vector3.back, true, args.SwipeDelta); break; } } } } } } #endregion On Event Functions #region Arrow Functions private void DisableAllArrowRenderers() { if (m_Type != TileType.Decoration) { m_NorthArrow.enabled = m_EastArrow.enabled = m_SouthArrow.enabled = m_WestArrow.enabled = false; for (int i = 0; i < m_UpArrows.Count; i++) { m_UpArrows[i].enabled = false; } for (int i = 0; i < m_DownArrows.Count; i++) { m_DownArrows[i].enabled = false; } } } private void RefreshArrows() { if (m_Type != TileType.Decoration) { DisableAllArrowRenderers(); bool hasNegativeMovesLeft = m_CurrentMoves > m_MaxMoveRange.Min; bool hasPositiveMovesLeft = m_CurrentMoves < m_MaxMoveRange.Max; switch (m_Type) { case TileType.MoveX: m_WestArrow.enabled = hasNegativeMovesLeft; m_EastArrow.enabled = hasPositiveMovesLeft; m_WestArrow.color = m_ArrowColor; m_EastArrow.color = m_ArrowColor; break; case TileType.MoveY: for (int i = 0; i < m_UpArrows.Count; i++) { m_UpArrows[i].enabled = hasPositiveMovesLeft; m_UpArrows[i].color = m_ArrowColor; } for (int i = 0; i < m_DownArrows.Count; i++) { m_DownArrows[i].enabled = hasNegativeMovesLeft; m_DownArrows[i].color = m_ArrowColor; } break; case TileType.MoveZ: m_NorthArrow.enabled = hasPositiveMovesLeft; m_SouthArrow.enabled = hasNegativeMovesLeft; m_NorthArrow.color = m_ArrowColor; m_SouthArrow.color = m_ArrowColor; break; default: break; } } } #endregion Arrow Functions #region Map Functions private void RegisterMapPosition() { if (m_Type != TileType.Decoration) { if (m_TileMap[Mathf.RoundToInt(transform.position.x), Mathf.RoundToInt(transform.position.z)] == null) { m_MapX = Mathf.RoundToInt(transform.position.x); m_MapY = Mathf.RoundToInt(transform.position.z); m_TileMap[m_MapX, m_MapY] = this; } } } private void ResetMapPosition() { if (m_Type != TileType.Decoration) { m_TileMap[Mathf.RoundToInt(transform.position.x), Mathf.RoundToInt(transform.position.z)] = null; } } #endregion Map Functions #region Movement Functions public bool MoveAlone(int amount) { if (amount > 0) { if (!m_IsLocked && m_Type != TileType.Fixed) { if (m_MoveRoutine == null) { int x = Mathf.Clamp(Mathf.RoundToInt(transform.position.x + (m_Type == TileType.MoveX ? amount : 0)), 0, m_TileMap.GetLength(0)); int y = Mathf.Clamp(Mathf.RoundToInt(transform.position.z + (m_Type == TileType.MoveZ ? amount : 0)), 0, m_TileMap.GetLength(1)); Tile targetTile = m_TileMap[x, y]; /* * Return if the target spot is occupied or if it's us. */ if (targetTile != null && targetTile != this) { return false; } /* * Restrict the amount of moves. */ int movesSum = m_CurrentMoves + amount; if (movesSum <= m_MaxMoveRange.Max && movesSum >= m_MaxMoveRange.Min) { m_CurrentMoves += amount; targetTile = this; ResetMapPosition(); // we'll register our new position after we arrive m_MoveRoutine = StartCoroutine(MoveRoutine(amount, m_Speed)); return true; } } } } return false; } public void Move(bool negative) { int amount = negative ? -1 : 1; MoveAlone(amount); m_Link?.MoveAlone(-amount); } private void MoveIfSwipedInDirection(Vector3 dir, bool isNegative, Vector2 swipeDelta) { if (SwipeUtil.HasSwipedInWorldDirection(m_Camera, transform.position, transform.position + dir, swipeDelta, m_SwipeErrorRange)) { Move(isNegative); } } private IEnumerator MoveRoutine(int amount, float speed) { float startingTime = Time.time; Vector3 origin = transform.position; /* * Attach the player. */ if (m_IsOccupied) { m_Player.transform.SetParent(transform); } Vector3 target = origin + m_Direction * amount; float journeyLength = Vector3.Distance(origin, target); /* * Move towards the target position until we've reached it. */ while (Vector3.Distance(transform.position, target) > .01f) { float timeDiff = Time.time - startingTime; float distCovered = timeDiff * speed; float fracJourney = distCovered / journeyLength; transform.position = Vector3.Lerp(origin, target, fracJourney); yield return null; } // Hard-set the value in the end just in case we couldn't precisely reach the target mathematically. transform.position = target; // Detach the player after we arrived. m_Player.transform.SetParent(m_Player.OriginalParent.transform); // Register our new position RegisterMapPosition(); RefreshArrows(); // Increment the moves counter. (GUI) m_LevelManager.TotalTileMoves += 1; m_MoveRoutine = null; } #endregion Movement Functions #region Tile Data Functions private void LoadTileData() { if (m_Data != null) { Material defMat = m_Renderer.sharedMaterial; /* * Apply the proper tile material. */ if (m_IsFinish) { m_Renderer.material = m_Data.FinishMaterial ?? defMat; } else { switch (m_Type) { case TileType.Fixed: m_Renderer.material = m_Data.FixedMaterial ?? defMat; break; case TileType.MoveX: m_Renderer.material = m_Data.XSlideMaterial ?? defMat; break; case TileType.MoveY: m_Renderer.material = m_Data.YSlideMaterial ?? defMat; break; case TileType.MoveZ: m_Renderer.material = m_Data.ZSlideMaterial ?? defMat; break; } } gameObject.name = m_IsFinish ? $"Finish{m_Data.name}" : m_Data.name; } } public void SetTileData(TileData data) { m_Data = data; LoadTileData(); } #endregion Tile Data Functions #region Update Functions private void UpdateDirection(TileType type) { switch (type) { case TileType.MoveX: m_Direction = Vector3.right; break; case TileType.MoveY: m_Direction = Vector3.up; break; case TileType.MoveZ: m_Direction = Vector3.forward; break; } } private void UpdateDirection() { UpdateDirection(m_Type); } #endregion Update Functions public virtual void Remove() { Destroy(gameObject); } } } |
Touch Manager
This script is used for the tracking of touches, pinches/stretches, and swipes.
Since swiping is a singular gesture (unlike pinch/stretching) I can use an event to notify other scripts when one occurs.
To be able to do tests without always needing to build to mobile I wrote some of the functionality for the Unity editor as well.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 |
using System; using System.Collections; using System.Collections.Generic; using EmberSkies.Input.Events; using UnityEngine.Events; namespace EmberSkies.Input { using UnityEngine; public enum SwipeDirection { Up = 0, Down, Left, Right } public class TouchManager : Singleton<TouchManager> { public delegate void SwipeEventHandler(SwipeEventArgs args); #region Events private event SwipeEventHandler m_SwipeEvent; public event SwipeEventHandler SwipeEvent { add { m_SwipeEvent += value; } remove { m_SwipeEvent -= value; } } #endregion Events #region Members private float m_PreviousStretchDist; private Vector2[] m_PreviousTouchPositions; private float m_StretchVelocity; private bool[] m_IsTouching; private bool[] m_HasTouchSwiped; private Vector2[] m_TouchDeltas; private Vector2[] m_TouchVelocities; private Vector2[] m_TouchOrigins; #endregion Members #region Serialized Members [SerializeField] private int m_MaxTouches = 10; [SerializeField] private int m_SwipeDeadzonePx = 60; [SerializeField] private int m_MaxStationaryTouchDeadzonePx = 10; [SerializeField] private UnityEvent m_TapAnywhereEvent; #endregion Serialized Members #region Properties public int MaxStationaryTouchDeadzonePx { get { return m_MaxStationaryTouchDeadzonePx; } } public float StretchVelocity { get { return m_StretchVelocity; } } public bool[] IsTouching { get { return m_IsTouching; } } public Vector2[] TouchDeltas { get { return m_TouchDeltas; } } public Vector2[] TouchVelocities { get { return m_TouchVelocities; } } public Vector2[] TouchOrigins { get { return m_TouchOrigins; } } #endregion Properties public override void Awake() { base.Awake(); m_PreviousTouchPositions = new Vector2[m_MaxTouches]; m_IsTouching = new bool[m_MaxTouches]; m_HasTouchSwiped = new bool[m_MaxTouches]; m_TouchDeltas = new Vector2[m_MaxTouches]; m_TouchVelocities = new Vector2[m_MaxTouches]; m_TouchOrigins = new Vector2[m_MaxTouches]; } #region Reset Functions private void ResetTouch(int touchIndex) { if (touchIndex < m_MaxTouches) { m_TouchOrigins[touchIndex] = m_TouchDeltas[touchIndex] = m_TouchVelocities[touchIndex] = Vector2.zero; m_IsTouching[touchIndex] = m_HasTouchSwiped[touchIndex] = false; } } private void ResetVector2Array(ref Vector2[] vectors) { int length = vectors.Length; for (int i = 0; i < length; i++) { vectors[i] = Vector2.zero; } } #endregion Reset Functions #region Event Call Functions private void CallSwipeEvent(SwipeEventArgs args) { SwipeEventHandler evt = m_SwipeEvent; evt?.Invoke(args); } #endregion Event Call Functions private void Update() { /* * Some touch data must be reset every update to stay accurate. */ ResetVector2Array(ref m_TouchDeltas); ResetVector2Array(ref m_TouchVelocities); /* * Just a little event for convenience. */ if (Input.GetButtonUp("Fire1")) { m_TapAnywhereEvent?.Invoke(); } #region Editor #if UNITY_EDITOR /* * Take note of the origin pos when clicking and reset the touch data when releasing. */ if (Input.GetMouseButtonDown(0)) { m_TouchOrigins[0] = Input.mousePosition; m_IsTouching[0] = true; } else if (Input.GetMouseButtonUp(0)) { ResetTouch(0); } /* * Calculate the swipe data to be used later. */ if (m_IsTouching[0]) { if (Input.GetMouseButton(0)) { m_TouchDeltas[0] = (Vector2) Input.mousePosition - m_TouchOrigins[0]; m_TouchVelocities[0] = (Vector2) Input.mousePosition - m_PreviousTouchPositions[0]; m_PreviousTouchPositions[0] = Input.mousePosition; } } #endif #endregion Editor #region Android #if UNITY_ANDROID if (Application.isMobilePlatform) { int touchCount = Input.touchCount; if (touchCount > 0) { int length = Mathf.Clamp(touchCount, 0, m_MaxTouches); for (int i = 0; i < length; i++) { Touch touch = Input.touches[i]; /* * Take note of the origin pos when touching and reset the touch data when releasing. */ if (touch.phase == TouchPhase.Began) { m_TouchOrigins[i] = Input.touches[i].position; m_IsTouching[i] = true; } else if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled) { ResetTouch(i); } /* * Calculate the swipe data to be used later. */ if (m_IsTouching[i]) { m_TouchDeltas[i] = touch.position - m_TouchOrigins[i]; m_TouchVelocities[i] = touch.position - m_PreviousTouchPositions[i]; m_PreviousTouchPositions[i] = touch.position; } } } /* * Keep track of pinching/stretching. Requires two touches. */ if (Input.touchCount > 1) { Vector2 a = Input.touches[0].position; Vector2 b = Input.touches[1].position; float stretchDist = Vector2.Distance(a, b); if (m_PreviousStretchDist == .0f) { m_PreviousStretchDist = stretchDist; } m_StretchVelocity = m_PreviousStretchDist - stretchDist; m_PreviousStretchDist = stretchDist; } else { m_PreviousStretchDist = .0f; m_StretchVelocity = .0f; } } #endif #endregion Android /* * Call the swipe event when a touch delta crossed the deadzone and hasn't been registered yet. */ for (int i = 0; i < m_TouchDeltas.Length; i++) { if (!m_HasTouchSwiped[i]) { if (m_TouchDeltas[i].magnitude > m_SwipeDeadzonePx) { // Did the delta cross the deadzone? Then its a swipe! float x = m_TouchDeltas[i].x; float y = m_TouchDeltas[i].y; SwipeDirection dir; if (Mathf.Abs(x) > Mathf.Abs(y)) { // Horizontal dir = (x < 0) ? SwipeDirection.Left : SwipeDirection.Right; // Left or right? } else { // Vertical dir = (y < 0) ? SwipeDirection.Down : SwipeDirection.Up; // Up or down? } CallSwipeEvent(new SwipeEventArgs(i, dir, m_TouchOrigins[i], m_TouchDeltas[i], m_TouchVelocities[i])); // Register the swipe for this touch. m_HasTouchSwiped[i] = true; } } } } } } |
Rotator
I use this script for the actual rotation around levels. (including in level showcasing)
It uses animation curves to make it easy to ease in and/or out.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace EmberSkies.Util.Transform { public class Rotator : MonoBehaviour { #region Members private Logger m_Logger; private Coroutine m_RotationRoutine; #endregion Members private void Awake() { m_Logger = new Logger(this, Logger.GREEN); } public void Rotate(Vector3 axis, int degrees, bool additive, float timeInSeconds, AnimationCurve curve) { if (m_RotationRoutine == null) { m_RotationRoutine = StartCoroutine(RotateRoutine(axis, degrees, additive, timeInSeconds, curve)); } } public void Rotate(int degrees, bool additive, float timeInSeconds, AnimationCurve curve) { Rotate(Vector3.up, degrees, additive, timeInSeconds, curve); } private IEnumerator RotateRoutine(Vector3 axis, int degrees, bool additive, float timeInSeconds, AnimationCurve curve) { Vector3 currentEuler = transform.rotation.eulerAngles; Vector3 eulerOrigin = currentEuler; Vector3 degreesOnAxis = axis * degrees; Vector3 eulerTarget = additive ? eulerOrigin + degreesOnAxis : degreesOnAxis; Vector3 eulerDelta = eulerTarget - eulerOrigin; float normalTime = 0; /* * Rotate along the provided curve until the end is reached. */ if (timeInSeconds > 0) { while (normalTime < 1) { normalTime += Time.deltaTime / timeInSeconds; float rotationCurveValue = curve.Evaluate(normalTime); Vector3 newEuler = eulerOrigin + (rotationCurveValue * eulerDelta); currentEuler = newEuler; transform.rotation = Quaternion.Euler(newEuler); yield return null; } } // Hard-set the value in the end just in case we couldn't precisely reach the target mathematically transform.rotation = Quaternion.Euler(eulerTarget); m_Logger.Log("Finished rotating routine!"); m_RotationRoutine = null; } } } |