Quantcast
Channel: Answers by "hoekkii"
Viewing all articles
Browse latest Browse all 26

Answer by hoekkii

$
0
0
I made something. if you don't understand how to use, leave a comment using UnityEngine; using System.Collections; public class Character : MonoBehaviour { private Transform t = null; public float moveSpeed = 5.0f; public Cell currentCell = new Cell(); public Cell[] cells = new Cell[0]; /// /// Initialization /// public void Start() { t = transform; for (int i = 0; i < cells.Length; i++) { if (currentCell == cells[i]) { currentCell.position = cells[i].position; return; } } Debug.LogError("Current Cell is not valid"); cells = new Cell[0]; } /// /// Update is calling once a frame /// public void Update() { if (cells.Length < 1) { return; } Cell targetCell = Move(GetMoveDirection()); if (targetCell != Cell.NaC) { for (int i = 0; i < cells.Length; i++) { if (targetCell == cells[i]) { currentCell = cells[i]; break; } } } if (Vector3.Distance(currentCell.position, t.position) > 0.01f) { t.position = Vector3.Lerp(t.position, currentCell.position, Time.deltaTime * moveSpeed / Vector3.Distance(currentCell.position, t.position)); } } private Direction GetMoveDirection() { if (Input.GetKeyDown(KeyCode.W)) { return Direction.Up; } if (Input.GetKeyDown(KeyCode.S)) { return Direction.Down; } if (Input.GetKeyDown(KeyCode.A)) { return Direction.Left; } if (Input.GetKeyDown(KeyCode.D)) { return Direction.Right; } return Direction.Center; } private Cell Move(Direction md) { if (md == Direction.Center) { return Cell.NaC; } Cell targetCell = currentCell; switch(md) { case Direction.Up: targetCell.y++; break; case Direction.Down: targetCell.y--; break; case Direction.Left: targetCell.x--; break; case Direction.Right: targetCell.x++; break; } return targetCell; } } [System.Serializable] public struct Cell { /* * x and y are the imaginary positions, * for the connections. * * so (0, 0) and (0, 1) are connected to each other, * (2, 3) and (0, 0) are not connected. */ public Vector3 position; public int x, y; // Constructors public Cell(Vector3 position, int x, int y) { this.position = position; this.x = x; this.y = y; } public Cell(int x, int y) { this.position = Vector3.zero; this.x = x; this.y = y; } /// /// Not a Cell /// public static Cell NaC { get { return new Cell(Vector3.zero, -2147483648, -2147483648); } } public static bool operator ==(Cell a, Cell b) { return (a.x == b.x && a.y == b.y); } public static bool operator !=(Cell a, Cell b) { return (a.x != b.x || a.y != b.y); } } public enum Direction { Up = 0, Down, Left, Right, Center }

Viewing all articles
Browse latest Browse all 26

Trending Articles