public void ResetToStart() { if (IsInvoking("Respawn")) { CancelInvoke("Respawn"); Respawn(); } transform.position = startPos; transform.rotation = startRot; camAngles = new Vector3(0, 0, 0); num_laps = 0; primedForLap = false; cur_off_time = 0; onTrack = true; foreach (WaypointScript waypoint in gc.getWaypoints()) { if (waypoint.id == 0) { furthest_waypoint = waypoint; } } HandleCamera(); }
private void Start() { agent = GetComponent <NavMeshAgent>(); SqrAttackRange = attackRange * attackRange; //Finding waypoints GameObject[] waypoints = GameObject.FindGameObjectsWithTag("waypoint"); foreach (GameObject waypoint in waypoints) { WaypointScript wpt = waypoint.GetComponent <WaypointScript>(); if (wpt.lane == gameObject.GetComponent <Minion>().lane&& wpt.team == gameObject.GetComponent <Targetable>().team) { mWaypoints.Add(waypoint); } } mWaypoints.Sort((p1, p2) => p1.GetComponent <WaypointScript>().waypointOrder.CompareTo(p2.GetComponent <WaypointScript>().waypointOrder)); mCurrentWaypointIndex = 0; agent.SetDestination(mWaypoints[mCurrentWaypointIndex].transform.position); attackRange = 5.0f; possibleTargets = new List <GameObject>(); enemyList = new List <GameObject>(); myTeam = gameObject.GetComponent <Targetable>().team; InvokeRepeating("UpdatePossibleTargets", 1.0f, 2.0f); }
void SpawnKiller(GameObject killer, List <Transform> roomList) { List <Transform> tempList = new List <Transform>(); tempList.AddRange(roomList); foreach (Transform node in tempList) { RoomManager room = node.GetComponentInChildren <RoomManager>(); if (room.meshesEnabled) { WaypointScript waypoint = node.GetComponent <WaypointScript>(); int randNum = Random.Range(0, waypoint.adjactentNodes.Count); Vector3 adjacentRoom = waypoint.adjactentNodes[randNum].position; killer = Instantiate(killer, new Vector3(adjacentRoom.x, adjacentRoom.y + 1 - (WaypointManager.scale / 4), adjacentRoom.z), Quaternion.identity) as GameObject; break; } } //int randNum = Random.Range(0, tempList.Count); //Transform targetRoom = tempList[randNum]; //RoomManager roomScript = targetRoom.GetComponentInChildren<RoomManager>(); //if (roomScript.meshesEnabled || (roomScript.litByFlashlight && Player.flashlightOn)) //{ // SpawnKiller(killer, tempList); //} //else //{ // killer = Instantiate(killer, new Vector3(targetRoom.position.x, targetRoom.position.y + 1 - (WaypointManager.scale / 4), targetRoom.position.z), Quaternion.identity) as GameObject; //} }
//TO DO: Update this function so that the position is randomized and then repeated on only the next floor; currenly only works for single position and only for 2 floors void GenerateStairNode(int floors, List <Transform> nodeList) { List <Transform> tempList = new List <Transform>(); tempList.AddRange(nodeList); for (int i = floors; i > 0; i--) { int randNum = Random.Range(0, tempList.Count); WaypointScript room = tempList[randNum].GetComponent <WaypointScript>(); if (room.zPos == i - 1) { if ((room.type == WaypointScript.Type.empty || room.type == WaypointScript.Type.eventRoom)) { room.type = WaypointScript.Type.stairs; } else { //tempList.Remove(room.transform); GenerateStairNode(i, tempList); break; } } else { GenerateStairNode(i, tempList); break; } } }
void MoveToNewRoom(List <Transform> roomList) { if (!GetComponentInChildren <SpriteRenderer>().enabled) //!GetComponent<MeshRenderer>().enabled) //If killer is currently not visible { List <Transform> tempList = new List <Transform>(); tempList.AddRange(roomList); //This code feels like it could be written more cleanly foreach (Transform node in tempList) { RoomManager room = node.GetComponentInChildren <RoomManager>(); if (room.hasActiveInteracts || room.meshesEnabled) //If the player is currently in this room { WaypointScript waypoint = node.GetComponent <WaypointScript>(); int randNum = Random.Range(0, waypoint.adjactentNodes.Count); RoomManager rm = waypoint.adjactentNodes[randNum].GetComponentInChildren <RoomManager>(); if (!rm.meshesEnabled && !rm.litByFlashlight) { Vector3 adjacentRoom = waypoint.adjactentNodes[randNum].position; transform.position = new Vector3(adjacentRoom.x, adjacentRoom.y + 1 - (WaypointManager.scale / 4), adjacentRoom.z); break; } else { tempList.Remove(waypoint.transform); MoveToNewRoom(tempList); break; } } } } }
public static float distBetween(WaypointScript w1, WaypointScript w2, Vector3 pos) { WaypointScript first; WaypointScript second; if (w1.value < w2.value) { first = w1; second = w2; } else { first = w2; second = w1; } float firstval = first.value; float secondval = second.value; if (first.value == 0 && second.value > 0.5f) { firstval = secondval; secondval = 1; WaypointScript third = first; first = second; second = third; } return(firstval + (secondval - firstval) * (first.distanceFrom(pos) / (first.distanceFrom(pos) + second.distanceFrom(pos)))); }
public void CleanUp() { CurrentWaypoint = null; TraverseWaypoints = new WaypointScript[2]; //LeftWaypoint = null; //RightWaypoint = null; }
// Use this for initialization void Start() { roomScript = GetComponent <RoomManager>(); wayPoint = GetComponentInParent <WaypointScript>(); doorPrefab = Resources.Load("Door") as GameObject; CreateDoors(wayPoint, doorPrefab); }
void Start() { furthest_waypoint = gc.getWaypoints()[0]; startPos = transform.position; startRot = transform.rotation; meshes = GetComponentsInChildren <MeshRenderer>(); }
void OnTriggerExit(Collider other) { if (!this.enabled) return; waypointQuickFix = null; canCollide = true; }
void SpawnObjectives(GameObject[] objItem, List <Transform> roomList, int count, float scale) { WaypointManager wpm = GameObject.FindObjectOfType <WaypointManager>(); List <Transform> tempList = new List <Transform>(); tempList.AddRange(roomList); for (int i = count; i > 0; i--) { int randNum = Random.Range(0, tempList.Count); Transform targetRoom = tempList[randNum]; RoomManager roomScript = targetRoom.GetComponentInChildren <RoomManager>(); WaypointScript room = targetRoom.GetComponent <WaypointScript>(); if (roomScript.meshesEnabled || (roomScript.litByFlashlight && Player.flashlightOn) || room.type == WaypointScript.Type.stairs) { tempList.Remove(targetRoom); SpawnObjectives(objItem, tempList, i, scale); break; } else { //Removing the randomized positions for the time being so that I can determine a better way to populate each room Vector3 randPos = new Vector3( targetRoom.position.x + Random.Range(-WaypointManager.scale / 3, WaypointManager.scale / 3), targetRoom.position.y + 1 - (WaypointManager.scale / 4), targetRoom.position.z + Random.Range(-WaypointManager.scale / 3, WaypointManager.scale / 3) ); Collider[] colliders = Physics.OverlapSphere(randPos, scale / 2); if (colliders.Length > 1) //Room collider { SpawnObjectives(objItem, tempList, i, scale); break; } else { GameObject objPrefab; try { objPrefab = Instantiate(objItem[i], randPos, Quaternion.identity); } catch { objPrefab = Instantiate(objItem[0], randPos, Quaternion.identity); //Debug.Log("Item list out of range"); } objPrefab.transform.localScale = Vector3.one * scale; objPrefab.transform.parent = roomScript.gameObject.transform; roomScript.UpdateMeshes(); tempList.Remove(targetRoom); } } } }
public void EnterWaypoint(Vector3 direction) { //Debug.Log("Setting up Waypoint by direction"); CurrentWaypoint = direction == Vector3.right ? TraverseWaypoints[1] : TraverseWaypoints[0]; EnterWaypoint(); //CurrentWaypoint.ToggleActive(); //LeftWaypoint = null; //RightWaypoint = null; //MissionLogic.Fsm.Event("Waypoint Loaded"); }
// Update is called once per frame void Update() { // First things first, we need to find the closest node first! On the first frame, closestWaypoint == null, so we go through // all of the waypoints in the map and figure out which one is closest using a simple distance comparison. if (distanceToWaypoint == -1) // this GameObject has not found its closest waypoint yet { foreach (GameObject node in wp.waypoints) { tempDistance = Vector2.Distance(rb.position, node.transform.position); if (distanceToWaypoint == -1 || distanceToWaypoint > tempDistance) // If this waypoint is the closest so far, make it official and put a gad damn ring on it { distanceToWaypoint = tempDistance; closestWaypoint = node; } } wp = closestWaypoint.GetComponent <WaypointScript>(); } // Now that we've found the closest waypoint at the start, we don't need to check every single waypoint anymore! // Each waypoint stores an array of its neighboring waypoints. We just need to check if we're closer to any of those adjacent waypoints // every frame! It keeps the math down in update and should prevent this script from grinding shit to a halt because of shitty code. // Not to say that this code isn't shitty in it's own right, but this is an attempt to make it less shitty. else { distanceToWaypoint = Vector2.Distance(rb.position, closestWaypoint.transform.position); // update the current distance to our currently set closest waypoint closestNeighborDistance = 100; foreach (GameObject neighbor in wp.adjacentWaypoints) // check neighboring waypoints { tempDistance = Vector2.Distance(rb.position, neighbor.transform.position); // find distance to neighbor if (tempDistance < distanceToWaypoint && tempDistance < closestNeighborDistance) // true if neighbor is closer than our current closest node { tempWaypoint = neighbor; closestNeighborDistance = tempDistance; } } if (closestNeighborDistance < distanceToWaypoint) { closestWaypoint = tempWaypoint; wp = closestWaypoint.GetComponent <WaypointScript>(); } } if (distanceToWaypoint > 2) // if something breaks and the waypoint doesn't update correctly, recheck every node to find the closest one and unfuck things. { foreach (GameObject node in wp.waypoints) { tempDistance = Vector2.Distance(rb.position, node.transform.position); if (distanceToWaypoint > tempDistance) // If this waypoint is the closest so far, make it official and put a gad damn ring on it { distanceToWaypoint = tempDistance; closestWaypoint = node; } } wp = closestWaypoint.GetComponent <WaypointScript>(); } }
void Update() { //Get current gamespeed from the timecontroller set in maincontroller and calculate bird avatar's movement speed //TODO: Null checks TimeController tc = GameObject.Find("MainController").GetComponent <TimeController>(); float timeSpeed = tc.getTimeSpeed(); calculatedMoveSpeed = moveSpeed * (int)timeSpeed; if (nextWaypoint) { Debug.DrawLine(transform.position, nextWaypoint.position, Color.green); } if (lastWaypoint) { Debug.DrawLine(transform.position, lastWaypoint.position, Color.black); } WaypointScript nextWp = nextWaypoint.GetComponent <WaypointScript> (); if (nextWp.stopPoint && currentState == MovementStates.MOVING) { this.currentState = MovementStates.STOPPED; this.stoppedAtTime = tc.getCurrentDateTime(); this.leaveTime = stoppedAtTime.AddMinutes(nextWp.stopTimeInMinutes); nextWp.stopPoint = false; if (nextWp.gameObject.GetComponent <PointOfInterest>() != null) { nextWp.gameObject.GetComponent <PointOfInterest>().show(); } } if (currentState == MovementStates.STOPPED) { if (tc.getCurrentDateTime() >= leaveTime) { currentState = MovementStates.MOVING; if (nextWp.gameObject.GetComponent <PointOfInterest>() != null) { nextWp.gameObject.GetComponent <PointOfInterest>().hide(); } } } // move if (movingTowardsObject && currentState == MovementStates.MOVING) { MoveTowardsObject(); } // Rotate towards object if (rotatingTowardsObject) { RotateTowardsObject(); } }
void HandleLapping() { if (!onTrack) { return; } waypoints.Sort((x, y) => x.distanceFrom(transform.position).CompareTo(y.distanceFrom(transform.position))); distance = WaypointScript.distBetween(waypoints[0], waypoints[1], transform.position); /*if (distance > 0.5f && distance < 0.55f) { * if (waypoints[0].id == 0 || waypoints[1].id == 0) { * if (primedForLap) { * num_laps++; * furthest_waypoint = waypoints[0]; * primedForLap = false; * print("LAP"); * } * } else { * if (!primedForLap) { * primedForLap = true; * print("PRIMED"); * } * } * }*/ if (!primedForLap) { if (distance > 0.5f && distance < 0.55f) { primedForLap = true; } } else if (furthest_waypoint.id == 0) { primedForLap = false; num_laps++; } if (furthest_waypoint == null) { furthest_waypoint = waypoints[0]; } else if (waypoints[0] == gc.getWaypoints()[0]) { furthest_waypoint = waypoints[0]; } else if (furthest_waypoint != waypoints[0] && distance > waypoints[0].value && waypoints[0].value > furthest_waypoint.value) { furthest_waypoint = waypoints[0]; } }
void OnTriggerEnter(Collider other) { if (!this.enabled) return; WaypointScript waypoint = other.GetComponent<WaypointScript>(); if (!waypoint) return; waypointQuickFix = waypoint; }
void GenerateStartNode(int nodeValue, List <Transform> nodeList) { WaypointScript room = nodeList[nodeValue].GetComponent <WaypointScript>(); if (room.type == WaypointScript.Type.wall && room.zPos == 0) { nodeList[nodeValue].GetComponent <WaypointScript>().type = WaypointScript.Type.start; } else { GenerateStartNode(Random.Range(0, totalWaypoints), nodeList); } }
public void LeaveWaypoint(WaypointScript wp) { Debug.Log("Leaving WP"); CurrentWaypoint.ToggleActive(); TraverseWaypoints[0] = CurrentWaypoint; TraverseWaypoints[1] = wp; TraverseWaypoints[0].SetColor(WaypointScript.cHighlighted); TraverseWaypoints[1].SetColor(WaypointScript.cTerminating); CurrentWaypoint = null; //gameObject.SetActive(false); }
void Start() { GameObject[] templightarray = new GameObject[1]; templightarray = GameObject.FindGameObjectsWithTag("Flashlight"); // grabs a copy of every flashlight in the scene Light2D templightobject; flashlightObject = new GameObject[3]; flashlightLight2D = new Light2D[3]; int j = 0; for (int i = 0; i < templightarray.Length; ++i) { if (Vector2.Distance(transform.position, templightarray[i].transform.position) < 1f) { templightobject = templightarray[i].GetComponent <Light2D>(); if (templightobject.pointLightOuterRadius == 7.5f) // change the float to be the outter radius of the lowest alert level flashlight { flashlightObject[0] = templightarray[i]; flashlightLight2D[0] = templightobject; } else if (templightobject.pointLightOuterRadius == 8.5f) // change the float to be the outter radius of the medium alert level flashlight { flashlightObject[1] = templightarray[i]; flashlightLight2D[1] = templightobject; } else if (templightobject.pointLightOuterRadius == 10f) // change the float to be the outter radius of the highest alert level flashlight { flashlightObject[2] = templightarray[i]; flashlightLight2D[2] = templightobject; } } } flashlightObject[1].SetActive(false); // disables the two higher alert flashlights flashlightObject[2].SetActive(false); waitTime = startWaitTime; pathfindingIndex = 0; isPathfinding = false; isSearching = false; actualPlayer = GameObject.FindGameObjectWithTag("Player"); closestWaypoint = gameObject.GetComponent <ClosestWaypoint>(); wscopy = closestWaypoint.GetComponent <WaypointScript>(); patrolRoute = new Transform[routeWaypoints.Length]; index = 0; foreach (GameObject node in routeWaypoints) { patrolRoute[index] = node.transform; index++; } waitTime = startWaitTime; }
void Update() { if (currentWaypoint < waypoints.Length) { isMoving = true; for (int i = 0; i < waypoints.Length; i++) { WaypointScript script = waypoints[i].GetComponent <WaypointScript>(); if (script.queuePosition == currentWaypoint) { targetWaypoint = waypoints[i].transform; } } if (targetWaypoint != null) { if (transform.position.y < targetWaypoint.position.y) { dir = Direction.Up; } else if (transform.position.y > targetWaypoint.position.y) { dir = Direction.Down; } else if (transform.position.x < targetWaypoint.position.x) { dir = Direction.Right; } else if (transform.position.x > targetWaypoint.position.x) { dir = Direction.Left; } Move(targetWaypoint.position); float distance = Vector2.Distance(transform.position, targetWaypoint.position); if (distance <= 0f) { currentWaypoint++; } } } else { isMoving = false; } }
List <Transform> GetEventRooms(List <Transform> roomList) { List <Transform> availableRooms = new List <Transform>(); foreach (Transform room in roomList) { WaypointScript node = room.GetComponent <WaypointScript>(); if (node.type == WaypointScript.Type.eventRoom) { availableRooms.Add(room); } } return(availableRooms); }
void CreateDoors(WaypointScript currentRoom, GameObject prefab) { GameObject door = null; List <Transform> roomList = currentRoom.adjactentNodes; foreach (Transform room in roomList) { WaypointScript wayPoint = room.GetComponentInParent <WaypointScript>(); RoomManager roomScript = room.GetComponentInChildren <RoomManager>(); if (currentRoom.xPos == wayPoint.xPos && currentRoom.yPos == wayPoint.yPos + 1) { door = Instantiate(prefab, new Vector3(roomScript.transform.position.x, roomScript.transform.position.y, roomScript.transform.position.z + (WaypointManager.scale / 2)), Quaternion.Euler(0, 0, 0), roomScript.transform); } else if (currentRoom.xPos == wayPoint.xPos && currentRoom.yPos == wayPoint.yPos - 1) { door = Instantiate(prefab, new Vector3(roomScript.transform.position.x, roomScript.transform.position.y, roomScript.transform.position.z - (WaypointManager.scale / 2)), Quaternion.Euler(0, 0, 0), roomScript.transform); } else if (currentRoom.xPos == wayPoint.xPos + 1 && currentRoom.yPos == wayPoint.yPos) { door = Instantiate(prefab, new Vector3(roomScript.transform.position.x + (WaypointManager.scale / 2), roomScript.transform.position.y, roomScript.transform.position.z), Quaternion.Euler(0, 90, 0), roomScript.transform); } else if (currentRoom.xPos == wayPoint.xPos - 1 && currentRoom.yPos == wayPoint.yPos) { door = Instantiate(prefab, new Vector3(roomScript.transform.position.x - (WaypointManager.scale / 2), roomScript.transform.position.y, roomScript.transform.position.z), Quaternion.Euler(0, 90, 0), roomScript.transform); } door.transform.localScale = new Vector3(0.4f, 1f, 0.05f); //need to find a better way to set object scale before coming here. will not scale properly door.GetComponent <InteractDoor>().doorManager = this; door.GetComponent <InteractDoor>().sigilWord = sigilWord; door.GetComponent <InteractDoor>().sigilImage = sigilImage; roomScript.UpdateMeshes(); connectedDoors.Add(door); } }
Vector2 TowardsWaypoint(WaypointScript target) { float r = GetRadius(); float theta = Mathf.Atan2(target.transform.localPosition.z, target.transform.localPosition.x) - Mathf.Atan2(transform.localPosition.z, transform.localPosition.x); if (theta < -Mathf.PI) theta += Mathf.PI * 2; else if (theta > Mathf.PI) theta -= Mathf.PI * 2; return new Vector2( -r * theta, target.transform.position.y - transform.position.y ).normalized; }
private void Update() { wscopy = closestWaypoint.GetComponent <WaypointScript>(); if (isPathfinding && !isSearching) { FollowNodePath(); } else if (inView == true) { isChasing = true; Chase(); } else if (inView == false && isChasing == true && isPathfinding == false) { isSearching = true; } else { Patrol(); } }
void SpawnPlayers(GameObject player, List <Transform> roomList) { List <Transform> tempList = new List <Transform>(); tempList.AddRange(roomList); Transform startPos = null; foreach (Transform currentNode in tempList) { WaypointScript nodeData = currentNode.GetComponentInChildren <WaypointScript>(); if (nodeData.type == WaypointScript.Type.start) { startPos = nodeData.transform; //Debug.Log(nodeData.name); } } player = Instantiate(player, new Vector3(startPos.position.x, 1 - (WaypointManager.scale / 4), startPos.position.z), Quaternion.identity); }
void FixedUpdate() { // If there is no more waypoint left than applying the damage to the player and destroying this EnemyShip if (currentWaypoint == null) { gameManager.DamagePlayersHealth(damageApplied); Destroy(gameObject); return; } // Calculating the distance between the EnemyShip and the waypoint that the it is moving towards float dist = Vector2.Distance(transform.position, currentWaypoint.GetPosition()); // If the waypoint is considered reached because below the threshold of the constant changeDist if (dist <= changeDist) { RotateIntoMoveDirection(currentWaypoint.GetPosition()); currentWaypoint = currentWaypoint.GetNextWaypoint(); } else { MoveTowards(currentWaypoint.GetPosition()); } }
private MoneyScript moneyMeter; // Variable to store the money void Start() { // If the reference to the Game Manager is missing, the script gets it if (gameManager == null) { gameManager = FindObjectOfType <GameManagerScript>(); } // Checking if the there is a reference for the above money, if not assigning it if (moneyMeter == null) { moneyMeter = FindObjectOfType <MoneyScript>(); } audioSource = GetComponent <AudioSource>(); animator = GetComponent <Animator>(); // Getting the reference to the Rigidbody2d rb2D = GetComponent <Rigidbody2D>(); // Gtinget the first waypoint from the Game Manager currentWaypoint = gameManager.firstWaypoint; }
public void GetWeight() { weight = 0; if (GetComponent <PlayerMovement>().isLocked&& !GetComponent <PlayerMovement>().canUnlock) { weight = -100; ai_Manager.SelectPawnToMove(this.gameObject); return; } //else, if it is a six and the pawn is locked, move this pawn out of the jail area if (player.diceRoll == 6 && player.canUnlock && player.isLocked) { weight += 150; } //else, if this pawn is the furthest forward, move the pawn forward if (player.MoveConstraint == 0) { weight += ((float)currentTravelledTiles / (float)MaxTilesToTravel) * 100f; } else { if (player.diceRoll > player.MoveConstraint) { weight = -100000; } else { if (player.diceRoll == player.MoveConstraint) { weight += 100000; } else { weight += 30; } } } //if there is anyone within a dice roll away from the pawn, add 100 to the weight. WaypointScript point = player.target.GetComponent <WaypointScript>().PreviousPoint.GetComponent <WaypointScript>(); //check the last 6 squares, that is the maximum dice roll for (int i = 0; i <= 6; i++) { //check if there are any player in the square if (point.playerInBox.Count > 0) { //check if the pawn present is the same as current pawn or not if (point.playerInBox[0].GetComponent <PlayerMovement>().color != GetComponent <PlayerMovement>().color&& !player.target.GetComponent <WaypointScript>().isSafeBox) { //if it not the same as current pawn, increase weight of this pawn 100 weight += 100 * i; } if (showDebug) { Debug.Log("Being Chased" + gameObject.name + weight); } } //get the tile before the current tile point = point.PreviousPoint.GetComponent <WaypointScript>(); } //else, if there is a chance to knock out an enemy within a certain distance, add 10 to the weight point = player.target.GetComponent <WaypointScript>().nextPoint[0].GetComponent <WaypointScript>(); int placeToKnockDown = 0; //check for X number of squares, where X is ChaseDistance for (int i = 0; i < ChaseDistance; i++) { //check if there are any players in the current square if (point.playerInBox.Count > 0) { //check if the player present is of the same type as this player if (point.playerInBox[0].GetComponent <PlayerMovement>().color != GetComponent <PlayerMovement>().color) { //save the position of the square placeToKnockDown = i; //check if the dice roll is higher than where the players are located, if it is lower, or the diceroll is a six, then add weight according to the number of pawns present if (player.diceRoll - 1 <= placeToKnockDown && !point.isSafeBox || player.canUnlock) { //number of players present in the target box for (int j = 0; j < point.playerInBox.Count; j++) { //increase weight by 25 weight += 25; } if (showDebug) { Debug.Log("Chasing" + gameObject.name + weight); } } else { //decrease the weight of this as it will have a higher chance of dying if moved ahead of an opposition if (showDebug) { Debug.Log("Will be eaten if chased" + gameObject.name + weight); } weight = -10; //weight = Mathf.Clamp(weight, 0, 999999); } break; } } //if no enemy was found else { //move to the next waypoint if (point.nextPoint[0] == null) { break; } point = point.nextPoint[0].GetComponent <WaypointScript>(); } } //set this pawn in the list of pawns with weight in AIManager ai_Manager.SelectPawnToMove(this.gameObject); }
public void EnterWaypoint(WaypointScript wp) { CurrentWaypoint = wp; EnterWaypoint(); }
public IEnumerator FindShortestPath(GuardMechanics Guard) // uses djikstra's algorithm to find the shortest path from this node to targetNode { GameObject currentNode; Stack <GameObject> pathNodes = new Stack <GameObject>(); djlist = new List <GameObject> { Capacity = waypoints.Length }; int[] visitedFrom = new int[waypoints.Length]; // lets us backtrack our path once we've found the path to the target int dji = 0; // dj index, used for indexing in the method djdistances = new float[waypoints.Length]; // array that stores the distance from our source node to each given node djvisited = new bool[waypoints.Length]; // keeps track of which nodes we've visited i = 0; //Debug.Log("Waypoints array size = " + waypoints.Length); //foreach (GameObject node in waypoints) for (i = 0; i < waypoints.Length; i++) { //Debug.Log("Loop #" + i + ", node name is " + waypoints[i].name); if (waypoints[i] == gameObject) // if this node is the source node, set distance to 0 { djdistances[i] = 0; } else { djdistances[i] = 1f / 0; // apparently this makes it infinity? } //Debug.Log("Set: djdistance [" + i + "] = " + djdistances[i]); djlist.Insert(i, waypoints[i]); // Copies waypoints array into djlist List, better functionality with lists! } while (djlist.Count > 0) // while the list is not empty { dji = FindShortestDistanceIndex(djdistances, djvisited); // find index for the node with shortest distance // Debug.Log("DJ Index = " + dji + ", Node name = " + waypoints[dji].name); currentNode = waypoints[dji]; // copies the node we are currently checking the branches of if (djlist.Remove(currentNode)) // remove the node we are currently at from the list { //Debug.Log("Successfully removed the node from the list!"); } else { //Debug.Log("Couldn't remove node from list! Oh no! Node = " + currentNode.name + " at index " + dji); break; } if (waypoints[dji] == targetNode) // we've arrived at the target node! Break the loop! { break; // More code probably needed here haha } nodeForDjikstra = currentNode.GetComponent <WaypointScript>(); // so we can access the adjacent waypoints of the node //foreach (GameObject neighbor in nodeForDjikstra.adjacentWaypoints) // goes through each of our current node's neighbors for (i = 0; i < nodeForDjikstra.numberOfAdjacentNodes; i++) { int neighborIndex = nodeForDjikstra.neighboringIndicies[i]; // grabs in index of the neighboring node in the waypoints array float alt = djdistances[dji] + Vector2.Distance(currentNode.transform.position, waypoints[neighborIndex].transform.position); //Debug.Log("N Loop: want to check " + nodeForDjikstra.adjacentWaypoints[i].name + ", currently checking neighbor: " + waypoints[neighborIndex].name + ", distance = " + alt); if (alt < djdistances[neighborIndex]) { //Debug.Log("N Loop: new shortest distance to " + waypoints[neighborIndex].name + ", index = " + neighborIndex + ", visitedFrom array size = " + visitedFrom.Length); djdistances[neighborIndex] = alt; visitedFrom[neighborIndex] = dji; } } djvisited[dji] = true; //Debug.Log("Set visited to " + djvisited[dji] + " at node " + waypoints[dji]); if (djlist.Count % 5 == 0) // this makes it so that we only check 8 nodes per frame to avoid freezing the game when we trigger the pathfinding. Change the mod value to change how many times we loop { yield return(null); } } bool done = false; int targetIndex = FindWaypointIndex(targetNode); while (!done) { pathNodes.Push(waypoints[targetIndex]); //Debug.Log("Stack: Pushed " + waypoints[targetIndex] + ", new targetIndex = " + visitedFrom[targetIndex]); targetIndex = visitedFrom[targetIndex]; if (waypoints[targetIndex] == gameObject) { done = true; } } Debug.Log("Shortest path alg. finished!"); pathNodesArray = pathNodes.ToArray(); // put our path nodes stack into an array so we can iterate through it easier Transform[] tempPos = new Transform[pathNodesArray.Length]; // make a new array to extract the transform of each path node, saves work later for (i = 0; i < pathNodesArray.Length; i++) // copies the transform of the path nodes from pathNodesArray into tempPos { tempPos[i] = pathNodesArray[i].transform; } Guard.pathfindingPos = tempPos.ToList <Transform>(); Guard.pathfindingReturnPos = tempPos.ToList <Transform>(); Guard.pathfindingReturnPos.Reverse(); Guard.pathfindingNodes = pathNodesArray; Guard.isPathfinding = true; }
// Start is called before the first frame update void Start() { tempWaypoint = GameObject.FindGameObjectWithTag("Waypoint"); // just grabs a waypoint from the scene to get at them sweet components wp = tempWaypoint.GetComponent <WaypointScript>(); // This script stores all the goodies we need distanceToWaypoint = -1; }
//public static Vector3 Direction(WaypointScript current, WaypointScript target) //{ // return target.location.Direction(current.location); //} ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Creation ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public bool AddWaypoint(Vector3 location, WaypointScript waypoint) { waypoints.Add(location, waypoint); waypointCount++; return waypointCount >= mapOptions.maxWaypoints; }
void NextWaypoint(Vector3 direction, WaypointScript wp) { var wpMag = Mathf.Max(1, wp.location.sqrMagnitude); var maxMag = new Vector3(mapOptions.edgeDistance, 0, mapOptions.edgeDistance).sqrMagnitude; var magRatio = wpMag / maxMag; var randDir = mapOptions.randomDirection + Mathf.RoundToInt(mapOptions.randomDirection * (wpMag / maxMag)); if (direction == Vector3.zero || Roll(randDir)) { direction = RandomDirection(); } else if (Roll(mapOptions.randomWaypoint)) { NextWaypoint(Vector3.zero, waypoints.GetRandom()); return; } // Reroll direction if location already taken. var repeats = 0; while (repeats <= 4 - wp.neighbours.Count && waypoints.ContainsKey(wp.location + direction)) { repeats++; direction = RandomDirection(); } Debug.Log("Next Direction: " + direction); // Check for boundary and either reverse or select a random waypoint. if (CheckBoundary(wp.location + direction)) { Debug.Log("<b>Boundary Check true</b>"); if (Roll(mapOptions.randomReverse)) NextWaypoint(direction.Reflect(), wp); else NextWaypoint(Vector3.zero, waypoints.GetRandom()); return; } if (waypoints.ContainsKey(wp.location + direction)) { var nextWP = waypoints[wp.location + direction]; var mag2Ratio = nextWP.location.sqrMagnitude / maxMag; var mag2Range = 3 + (6 * mag2Ratio); var mag1Range = 3 + (6 * magRatio); #region var connectChance = Random.Range(mag1Range, mag2Range); var pathTaken = wp.neighbours.ContainsKey(direction); var numPaths = wp.neighbours.Count + nextWP.neighbours.Count; //Debug.Log(wpMag + " " + maxMag); //Debug.Log(magRatio + " " + magDiv); //Debug.Log(mag1Range + " " + mag2Range); Debug.Log("total paths: " + (numPaths).ToString()); Debug.Log("Connect Chance: " + connectChance); if (pathTaken) Debug.Log("<b>Path Already Taken</b>"); #endregion if (numPaths <= connectChance && !pathTaken) { //Debug.Log("<b>Connecting</b>"); ConnectWaypoints(direction, wp, nextWP); NextWaypoint(direction, nextWP); } else if (Roll(mapOptions.randomWaypoint)) NextWaypoint(Vector3.zero, waypoints.GetRandom()); else NextWaypoint(direction, nextWP); } else { CreateWaypoint(direction, wp); } }
void CreateWaypoint(Vector3 direction, WaypointScript neighbour) { var go = GameObject.Instantiate(WaypointPrefab);//, location * (MapManager.Instance.traverseSize + 1), Quaternion.identity) as GameObject; go.name = "WP " + waypointCount.ToString(); go.transform.SetParent(ElementGroup.transform, false); var script = go.GetComponent<WaypointScript>(); if (neighbour != null) { script.location = neighbour.location + direction; ConnectWaypoints(direction, neighbour, script); } else script.location = Vector3.zero; Debug.Log("<b>Creating Waypoint " + go.name + ": </b>" + script.location); go.transform.position = script.location * (mapOptions.traverseSize + 1); UpdateMapExtents(go.transform.position); if (AddWaypoint(script.location, script)) return; NextWaypoint(direction, script); }
TraverseScript CreateTraverse(Vector3 direction, WaypointScript wp1, WaypointScript wp2) { //Debug.Log("Creating Traverse"); var go = Instantiate(TraversePrefab, wp1.location * (mapOptions.traverseSize + 1), Quaternion.identity) as GameObject; go.name = wp1.name + " to " + wp2.name; go.transform.SetParent(ElementGroup.transform, false); var script = go.GetComponent<TraverseScript>(); //traverses.Add(script); script.waypoints.Add(wp1); script.waypoints.Add(wp2); script.Setup(direction, mapOptions.traverseSize); return script; }
void ConnectWaypoints(Vector3 direction, WaypointScript wp1, WaypointScript wp2) { //Debug.Log("Connecting Waypoints"); wp1.neighbours.Add(direction, wp2); wp2.neighbours.Add(direction.Reflect(), wp1); var newTraverse = CreateTraverse(direction, wp1, wp2); wp1.pathways.Add(direction, newTraverse); wp2.pathways.Add(direction.Reflect(), newTraverse); }
public void EnterTraverse(WaypointScript wp) { WaypointManager.Instance.LeaveWaypoint(wp); TraverseManager.Instance.EnterTraverse();//WaypointManager.Instance.LeftWaypoint, WaypointManager.Instance.RightWaypoint); }
void GenerateNodes(GameObject node, int xNum, int yNum, int levelNum, float scaleNum) { for (int z = 0; z < levelNum; z++) { for (int i = 0; i < xNum; i++) { for (int j = 0; j < yNum; j++) { GameObject newnode = Instantiate(node, new Vector3(i * scaleNum, z * scaleNum, j * scaleNum), Quaternion.identity); newnode.transform.parent = GameObject.FindObjectOfType <WaypointManager>().transform; WaypointScript wayPointRef = newnode.AddComponent <WaypointScript>(); wayPointRef.xPos = i; wayPointRef.yPos = j; wayPointRef.zPos = z; if (i == 0 || i == xNum - 1) { if (j == 0 || j == yNum - 1) { wayPointRef.type = WaypointScript.Type.corner; if (i == 0) { if (j == 0) { wayPointRef.direction = WaypointScript.Direction.bottom; } else { wayPointRef.direction = WaypointScript.Direction.left; } } else { if (j == 0) { wayPointRef.direction = WaypointScript.Direction.right; } else { wayPointRef.direction = WaypointScript.Direction.top; } } } else { wayPointRef.type = WaypointScript.Type.wall; if (i == 0) { wayPointRef.direction = WaypointScript.Direction.left; } else { wayPointRef.direction = WaypointScript.Direction.right; } wallNodes.Add(newnode.transform); } } else { if (j == 0 || j == yNum - 1) { wayPointRef.type = WaypointScript.Type.wall; if (j == 0) { wayPointRef.direction = WaypointScript.Direction.bottom; } else { wayPointRef.direction = WaypointScript.Direction.top; } wallNodes.Add(newnode.transform); } else { if (Random.value < eventRoomProbability) { wayPointRef.type = WaypointScript.Type.eventRoom; } else { wayPointRef.type = WaypointScript.Type.empty; } } } } } } }
void FixedUpdate() { Direction dir = GetInputDirection(); if (waypointQuickFix && waypointQuickFix.leftTarget && waypointQuickFix.rightTarget && waypointQuickFix.upTarget && dir == Direction.Up) { transform.position = waypointQuickFix.transform.position; currentWaypoint = waypointQuickFix; waypointQuickFix = null; } else if (waypointQuickFix && waypointQuickFix.leftTarget && waypointQuickFix.rightTarget && waypointQuickFix.downTarget && dir == Direction.Down) { transform.position = waypointQuickFix.transform.position; currentWaypoint = waypointQuickFix; waypointQuickFix = null; } if (currentWaypoint != null) { if (dir != Direction.None) { if (dir == Direction.Up && currentWaypoint.upExit) { this.player.ExitUnderground(currentWaypoint.upExit); } Vector2 possibleDirection = currentWaypoint.GetDirection(dir); if (possibleDirection != Vector2.zero) { //Debug.Log("Leaving Waypoint"); if (dir == Direction.Up || dir == Direction.Down) { transform.localScale = new Vector3(currentWaypoint.ropeOnLeft ? 1 : -1, 1, 1); } movementDirection = possibleDirection; controlDirection = dir; currentWaypoint = null; } } } if (currentWaypoint == null && dir != Direction.None) { if (dir == controlDirection) { //Debug.Log("Moving Fowards"); if (dir == Direction.Up || dir == Direction.Down) Move(movementDirection * upDownSpeed); else Move(movementDirection * leftRightSpeed); AnimateMove(dir); } else if (dir == controlDirection.Opposite()) { //Debug.Log("Moving Backwards"); canCollide = true; if (dir == Direction.Up || dir == Direction.Down) Move(-movementDirection * upDownSpeed); else Move(-movementDirection * leftRightSpeed); AnimateMove(dir); } } if (dir == Direction.None) { AnimateMove(dir); } }
void Collide(Collider other) { //Debug.Log("Hit Waypoint"); currentWaypoint = other.GetComponent<WaypointScript>(); transform.position = currentWaypoint.transform.position; if (currentWaypoint.isGem) { shouldTeleport = true; } }