void FixedUpdate() { if (!myRoom.IsActive()) { return; } if (!myHealth.knockedBack) { float epsilon = 0.1f; var radius = transform.localScale / 2; var obstacleInFront = Physics2D.Raycast( transform.position, Room.RoomSideToVec(walkingDirection), radius.x + epsilon).collider != null; var groundInFront = Physics2D.Raycast( transform.position + Room.RoomSideToVec(walkingDirection) * (radius.x + epsilon), new Vector2(0, -1), radius.y + epsilon).collider != null; // Debug.DrawRay(transform.position + Room.RoomSideToVec(walkingDirection) * (radius.x + epsilon), new Vector2(0, -1)); // Debug.Log("obstacle:" + obstacleInFront + ";ground:" + groundInFront); if (obstacleInFront || (!walksOffEdges && !groundInFront)) { // turn, do not update pos walkingDirection = Room.OppositeSide(walkingDirection); mySpriteRenderer.flipX = (walkingDirection == RoomSide.Left); return; } myBody.velocity = new Vector2(velocity * Room.RoomSideToVec(walkingDirection).x, myBody.velocity.y); } }
private List <RoomNode> GenerateNextRooms(RoomSide side, List <RoomNode> currentRooms, ShouldStillGenerate shouldStillGenerate, int radius) { var oppositeSide = Room.OppositeSide(side); var currRoomNum = 0; var doorsLeft = CountDoorsAtSide(side, currentRooms); var nextRooms = new List <RoomNode>(); while (doorsLeft > 0) { // find a room with <= rooms at opposite of side. RoomNode nextNode = GetRoomWithMaxDoors( oppositeSide, doorsLeft, shouldStillGenerate, radius); nextRooms.Add(nextNode); var nodesToMake = nextNode.GetDoorCount(oppositeSide); Assert.IsTrue(nodesToMake > 0); doorsLeft -= nodesToMake; Assert.IsTrue(doorsLeft >= 0); for (var doorNum = 0; doorNum < nodesToMake; doorNum++) { while (currentRooms[currRoomNum].GetNeighborRooms(side).Count >= currentRooms[currRoomNum].GetDoorCount(side)) { currRoomNum++; } var currentRoomDoorNum = currentRooms[currRoomNum].GetNeighborRooms(side).Count; currentRooms[currRoomNum].GetNeighborRooms(side).Add(nextNode); currentRooms[currRoomNum].GetRoomDoorNums(side).Add(doorNum); nextNode.GetNeighborRooms(oppositeSide).Add(currentRooms[currRoomNum]); nextNode.GetRoomDoorNums(oppositeSide).Add(currentRoomDoorNum); } } return(nextRooms); }
public Room(RoomSide roomSide, int indexFromUnder, UIManager ui) { this.roomSide = roomSide; this.indexFromUnder = indexFromUnder; boundsButton = new Button(0, 0, RoomWidth, RoomHeight, false); updateViewport(); ui.addView(boundsButton); }
private int CountDoorsAtSide(RoomSide side, List <RoomNode> nodes) { var doorsLeft = 0; foreach (RoomNode room in nodes) { doorsLeft += room.GetDoorCount(side); } return(doorsLeft); }
private RoomNode GetRoomWithMaxDoors(RoomSide side, int maxIncomingDoors, ShouldStillGenerate shouldStillGenerate, int madeRoomRadius) { Assert.IsTrue(maxIncomingDoors >= 1); var minOutgoingDoors = shouldStillGenerate.IsDone() ? 0 : 1; // Debug.Log("for side" + side + "make max" + maxIncomingDoors + "," + minOutgoingDoors + "," + maxOutgoingDoors); var maxOutgoingGeneralDoors = shouldStillGenerate.numGenericRooms; List <GameObject> available = new List <GameObject>(); foreach (GameObject roomPrefab in roomPrefabs) { var incomingDoorCount = roomPrefab.GetComponent <Room>().GetDoors(side).Count; var room = roomPrefab.GetComponent <Room>(); if (!(1 <= incomingDoorCount && incomingDoorCount <= maxIncomingDoors)) { continue; } if (shouldStillGenerate.numGenericRooms == 0 && shouldStillGenerate.numWaysDown == 0 && shouldStillGenerate.numSpecialRooms == 1 && room.specialRoomType == shouldStillGenerate.specialRoomType) { // special case: here, we can always finish, no matter how many outgoing doors there are. available.Add(roomPrefab); continue; } var outgoingDoorCount = roomPrefab.GetComponent <Room>().GetDoors(Room.OppositeSide(side)).Count; if (!(minOutgoingDoors <= outgoingDoorCount)) { continue; } if (room.entryPoint != null) { continue; } var isWayDown = room.wayDown != null; if (shouldStillGenerate.numWaysDown > 0 && isWayDown) { available.Add(roomPrefab); } else if (shouldStillGenerate.numSpecialRooms > 0 && room.specialRoomType == shouldStillGenerate.specialRoomType) { available.Add(roomPrefab); } else if (!isWayDown && !room.specialRoom && outgoingDoorCount <= maxOutgoingGeneralDoors) { available.Add(roomPrefab); } } Assert.IsTrue(available.Count > 0, "Not all necessary rooms are available to make " + shouldStillGenerate); var chosenRoomPrefab = available[Random.Range(0, available.Count)]; var madeNode = new RoomNode(this, chosenRoomPrefab, madeRoomRadius); shouldStillGenerate.AddMadeNode(madeNode); return(madeNode); }
private Bounds GetBoundsOfPrefab(GameObject prefab, RoomElementType type, RoomSide roomSide) { var meshRenderer = prefab.GetComponentInChildren <MeshRenderer>(); if (meshRenderer == null) { throw new MissingComponentException("Room elements are expected to contain a mesh renderer. The " + type.ToString() + " - " + roomSide.GetName() + " prefab doesn't seem to have a mesh renderer in it's hierarchy. Please add one."); } return(meshRenderer.bounds); }
private void Update() { if (!myRoom.IsActive()) { return; } if (myHealth.knockedBack) { //currWaitTime = maxAttackCooldown; return; } currWaitTime = Mathf.Max(0f, currWaitTime - Time.deltaTime); currentChargeTime = Mathf.Max(0f, currentChargeTime - Time.deltaTime); target = myRoom.roomNode.manager.player.transform; if (currentChargeTime == 0) { myBody.velocity = new Vector2(0f, myBody.velocity.y); //myCollider.enabled = true; attackCollider.GetComponent <PolygonCollider2D>().enabled = false; } // check if waiting if (currWaitTime <= 0) { // Start the attack if ((target.position - transform.position).magnitude <= range) { // calculate the attack direction Vector2 lookDirection = movementDirection == RoomSide.Left ? Vector2.left : Vector2.right; RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down, 2f, LayerMask.GetMask("Ground")); Vector2 direction = lookDirection - Vector2.Dot(hit.normal, lookDirection) * hit.normal; // Add an impulse to create the dash movement myBody.AddForce(direction.normalized * chargeSpeed, ForceMode2D.Impulse); currentChargeTime = maxChargeDurationTime; // Spawn in the attack //myCollider.enabled = false; attackCollider.GetComponent <PolygonCollider2D>().enabled = true; attackCollider.GetComponent <AttackController>().knockbackDirection = Room.RoomSideToVec(movementDirection); // collider rotation attackCollider.transform.rotation = movementDirection == RoomSide.Left ? Quaternion.Euler(0f, 180f, 0f) : Quaternion.Euler(0f, 0f, 0f); // Reset attack cooldown currWaitTime = maxAttackCooldown; } } else if (currWaitTime <= maxAttackCooldown * (1 - turnRatio)) { // Turn towards player movementDirection = (myRoom.roomNode.manager.player.transform.position.x >= transform.position.x) ? RoomSide.Right : RoomSide.Left; mySpriteRenderer.flipX = (movementDirection == RoomSide.Left); } }
public static string GetName(this RoomSide roomSide) { switch (roomSide) { case RoomSide.North: return("North"); case RoomSide.EastAndWest: return("EastAndWest"); case RoomSide.South: return("South"); default: return("Unknown"); } }
public Tile(string[] tileData) { row = Convert.ToInt32(tileData[0]); column = Convert.ToInt32(tileData[1]); room = bool.Parse(tileData[2]); spawn = bool.Parse(tileData[3]); containsVault = (VaultType)Enum.Parse(typeof(VaultType), tileData[4]); objective = bool.Parse(tileData[5]); TopSide = (RoomSide)Enum.Parse(typeof(RoomSide), tileData[6]); BottomSide = (RoomSide)Enum.Parse(typeof(RoomSide), tileData[7]); LeftSide = (RoomSide)Enum.Parse(typeof(RoomSide), tileData[8]); RighSide = (RoomSide)Enum.Parse(typeof(RoomSide), tileData[9]); }
public static Vector3 RoomSideToVec(RoomSide s) { switch (s) { case RoomSide.Left: return(Vector3.left); case RoomSide.Right: return(Vector3.right); default: Assert.IsTrue(false); return(new Vector3(0, 0, 0)); // return any } }
public static RoomSide OppositeSide(RoomSide s) { switch (s) { case RoomSide.Left: return(RoomSide.Right); case RoomSide.Right: return(RoomSide.Left); default: Assert.IsTrue(false); return(RoomSide.Left); // return any } }
public GameObject GetDoor(RoomSide side, int doorNum) { switch (side) { case RoomSide.Left: return(leftDoors[doorNum]); case RoomSide.Right: return(rightDoors[doorNum]); default: return(null); } }
public void StartAttack(RoomSide attackDir) { this.attackDir = attackDir; int attackDirInt = attackDir == RoomSide.Right ? 1 : -1; Rigidbody2D myBody = GetComponent <Rigidbody2D>(); myBody.velocity = attackDirInt * constantVelocity * attackAngle.normalized; var myRenderer = GetComponent <SpriteRenderer>(); if (myRenderer != null) { myRenderer.flipX = attackDir == RoomSide.Left; } }
public List <GameObject> GetDoors(RoomSide side) { switch (side) { case RoomSide.Left: return(leftDoors); case RoomSide.Right: return(rightDoors); default: Assert.IsTrue(false); return(null); } }
public List <int> GetRoomDoorNums(RoomSide side) { switch (side) { case RoomSide.Left: return(leftNeighborDoorNums); case RoomSide.Right: return(rightNeighborDoorNums); default: Assert.IsTrue(false); return(null); } }
private void LeaveRoomThroughDoor(RoomNode oldRoom, RoomSide oldDoorSide, int oldDoorNum) { if (!oldRoom.myRoom.IsCleared()) { return; } var newDoorSide = Room.OppositeSide(oldDoorSide); var newDoorNum = oldRoom.GetRoomDoorNums(oldDoorSide)[oldDoorNum]; // todo !!! set this!! Debug.Log("enter door from door num" + oldDoorNum + "to" + newDoorNum); RoomNode newRoom = oldRoom.GetNeighborRooms(oldDoorSide)[oldDoorNum]; var newDoor = newRoom.roomObject.GetComponent <Room>().GetDoor(newDoorSide, newDoorNum); transform.position = newDoor.transform.position - Room.RoomSideToVec(newDoorSide); currentRoomNode = newRoom; currentRoomNode.manager.ReloadMinimap(); }
//Looks to see if new room should be created on each side of room void HandleSide(Vector3Int pos, RoomSide side, Room room, int depth) { Vector3Int newPos = pos + offsets[(int)side]; if (!PosFree(newPos)) { return; } if (depth > maxDepth) { return; } //create room CreateRoom(room, newPos, depth); return; }
static bool CheckSide(Vector3 v, RoomSide side) { switch (side) { case RoomSide.EAST: return(v.x > 0); case RoomSide.WEST: return(v.x < 0); case RoomSide.NORTH: return(v.z > 0); case RoomSide.SOUTH: return(v.z < 0); } return(false); }
static bool CheckWall(Vector3 v, RoomSide side) { switch (side) { case RoomSide.NORTH: return(v.z > 1.5f); case RoomSide.SOUTH: return(v.z < -1.5f); case RoomSide.EAST: return(v.x > 2.5f); case RoomSide.WEST: return(v.x < -2.5f); } return(false); }
private void ToggleOrientation() { if (attacking) { return; } if (myRenderer.flipX && Input.GetAxis("Horizontal") > 0) { orientation = RoomSide.Right; myRenderer.flipX = false; return; } if (!myRenderer.flipX && Input.GetAxis("Horizontal") < 0) { orientation = RoomSide.Left; myRenderer.flipX = true; return; } }
static Vector3 GetDirection(RoomSide side) { switch (side) { case RoomSide.NORTH: return(Vector3.forward); case RoomSide.SOUTH: return(Vector3.back); case RoomSide.EAST: return(Vector3.right); case RoomSide.WEST: return(Vector3.left); } return(Vector3.zero); }
public bool invSideOpen(RoomSide roomSide) { if (roomSide == RoomSide.Top) { return(sideOpen(RoomSide.Bottom)); } else if (roomSide == RoomSide.Bottom) { return(sideOpen(RoomSide.Top)); } else if (roomSide == RoomSide.Left) { return(sideOpen(RoomSide.Right)); } else if (roomSide == RoomSide.Right) { return(sideOpen(RoomSide.Left)); } return(false); }
public bool sideOpen(RoomSide roomSide) { if (roomSide == RoomSide.Top) { return(sidesOpen.Top); } else if (roomSide == RoomSide.Bottom) { return(sidesOpen.Bottom); } else if (roomSide == RoomSide.Left) { return(sidesOpen.Left); } else if (roomSide == RoomSide.Right) { return(sidesOpen.Right); } return(false); }
void GenerateRooms(Room room, Vector3Int pos, int depth) { depth++; //keeps track of distance from origin amount++; //total number of rooms RoomInformation info = room.roomInformation; //information about which sides are open Room newRoom; //the object to be instantiated, changes for each side //loop each side for (int i = 0; i < 4; i++) { //side from index RoomSide side = RoomInformation.GetSide(i); if (info.sideOpen(side)) { //accessing inverse list to find room that will fit int index = InverseIndex(i); newRoom = sideRooms[index][Random.Range(0, counts[index])]; HandleSide(pos, side, newRoom, depth); } } }
void finalPass() { foreach (Room room in generatedRooms) { Transform thisRoom = room.transform; Vector3Int roomPosition = Vector3Int.RoundToInt(thisRoom.position); for (int i = 0; i < 4; i++) { Vector3Int testPosition = roomPosition + offsets[i]; RoomSide side = RoomInformation.GetSide(i); //******PLACING GRASS****** GameObject testObject = GetRoom(testPosition); if (!testObject) { CreateGrass(testPosition); } //******PLACING DOORS****** testObject = GetRoom(testPosition); //Debug.Log(room.gameObject + " " + testObject.gameObject + " this open: " + room.roomInformation.sideOpen(side) + " other open: " + !testObject.GetComponent<Room>().roomInformation.invSideOpen(side)); if (room.roomInformation.sideOpen(side)) { if (!testObject.GetComponent <Room>().roomInformation.invSideOpen(side)) { CreateDoor(thisRoom, side); } } //******PLACING GRASS CORNERS****** Vector3Int cornerPosition = roomPosition + corners[i]; if (!GetRoom(cornerPosition)) { CreateGrass(cornerPosition); } } } }
/// <summary> /// Spawns and places normal rooms in valid locations such that no rooms will overlap /// </summary> /// <returns>Transform[].0 = roomParent. 1 = bleedLightsParent</returns> public Transform[] SpawnHallwaysAndRooms() { // Make sure there is enough space to spawn the rooms int maxRoomWidth = _maxRoomSize.x + _minSpaceBetweenRooms * 2; int maxRoomHeight = _maxRoomSize.y + _minSpaceBetweenRooms * 2; int xDistAvail = _upperRightBound.x - _lowerLeftBound.x; int yDistAvail = _upperRightBound.y - _lowerLeftBound.y; int maxRoomCoverArea = maxRoomWidth * maxRoomHeight * _amountRoomsToSpawn; int givenCoverArea = xDistAvail * yDistAvail; if (maxRoomCoverArea > givenCoverArea) { Debug.Log("That many rooms may not fit. It has the potential to cover " + maxRoomCoverArea + " square tiles. You only have " + givenCoverArea + " square tiles."); //return; } // Just in case, to prevent an infinite loop and unity freezing // We define a limit to how many times we iterate to find a good spot for the room int breakOutLimit = _amountRoomsToSpawn * 100; // Create the rooms parent and center it _roomParent = new GameObject().transform; _roomParent.position = Vector3.zero; // Create the lights parent and center it _bleedLightsParent = new GameObject().transform; _bleedLightsParent.position = Vector3.zero; // This is the list that will eventually be returned Transform[] rtnList = new Transform[2]; rtnList[0] = _roomParent; rtnList[1] = _bleedLightsParent; // Create the first room // Define its dimensions Vector2Int fRoomSize = Vector2Int.zero; fRoomSize.x = (Random.Range(_minRoomSize.x / 2, _maxRoomSize.x / 2 + 1) * 2) + 1; fRoomSize.y = (Random.Range(_minRoomSize.y / 2, _maxRoomSize.y / 2 + 1) * 2) + 1; // Determine a position for it (in the middle) Vector2Int fRoomPos = Vector2Int.zero; fRoomPos.x = (_lowerLeftBound.x + _upperRightBound.x) / 2; fRoomPos.y = (_lowerLeftBound.y + _upperRightBound.y) / 2; // Create the first room Transform fRoomTrans = Instantiate(_roomPrefab, new Vector3(fRoomPos.x, fRoomPos.y, 0), Quaternion.identity, _roomParent).transform; fRoomTrans.localScale = new Vector3(fRoomSize.x, fRoomSize.y, fRoomTrans.localScale.z); fRoomTrans.name = "Room 0"; // Get its Room script and set its weight to 0, as well as make it not a hallway Room fRoomScriptRef = fRoomTrans.GetComponent <Room>(); fRoomScriptRef.RoomWeight = 0; fRoomScriptRef.MyRoomType = RoomType.START; // Set the last room info to be that of the first room Vector2 prevRoomSize = fRoomSize; Vector2 prevRoomPos = fRoomPos; Transform prevRoomTrans = fRoomTrans; // Iterate to create the correct number of rooms int roomsSpawned = 1; // The counter int timesLooped = 0; // In case it gets stuck in an infinite loop while (roomsSpawned < _amountRoomsToSpawn) { // Determine a side to spawn the hallway on RoomSide hallwaySide = RoomSide.TOP + Random.Range(0, 4); // Choose the size of the hallway int hallwayWidth = Random.Range(_hallwayWidthRange.x, _hallwayWidthRange.y + 1); int hallwayLength = Random.Range(_hallwayLengthRange.x, _hallwayLengthRange.y + 1); Vector2Int hallwayScale = Vector2Int.one; // Choose the size of the new room Vector2Int newRoomSize = Vector2Int.zero; newRoomSize.x = (Random.Range(_minRoomSize.x / 2, _maxRoomSize.x / 2 + 1) * 2) + 1;; newRoomSize.y = (Random.Range(_minRoomSize.y / 2, _maxRoomSize.y / 2 + 1) * 2) + 1;; // The positions of the hallway and room Vector2 hallwayPos = Vector2.zero; Vector2 newRoomPos = Vector2.zero; // The positionf of the point where the room and hallway meet Vector2 hallPrevJoinPoint = Vector2.zero; Vector2 hallNewJoinPoint = Vector2.zero; // The rotation of the bleed light broadcasting from the prev room into the hallway float bleedLightRot = 0f; // In case the first side choice does not work, we will loop this until we find a side that works bool spawnSuccessful = false; // If the most recent spawn was successful int amountSidesTested = 0; // The amount of sides of the current room that have been tested int prevRoomIndex = _roomParent.childCount - 1; // The index of the previous room while (!spawnSuccessful) { // This information will be used in calculating the positions of the hallway and room // Holds the information about half the size of the hallway and room in both the x and y Vector2 hallwayRadius = new Vector2(hallwayWidth / 2f, hallwayLength / 2f); Vector2 prevRoomRadius = new Vector2(prevRoomSize.x / 2f, prevRoomSize.y / 2f); Vector2 newRoomRadius = new Vector2(newRoomSize.x / 2f, newRoomSize.y / 2f); int offsetPrev = 0; // The offest where to spawn the hallway in relation to the previous room int offsetNew = 0; // The offest where to spawn the hallway in relation to the new room // We now have to do things based on which side the hallway will spawn switch (hallwaySide) { case RoomSide.TOP: // Calculate offset with the previous room (TOP and BOT) are the same calculation offsetPrev = Mathf.RoundToInt(Random.Range(-prevRoomRadius.x + hallwayRadius.x + _hallwayOffsetFromEdge, prevRoomRadius.x - hallwayRadius.x - _hallwayOffsetFromEdge)); // Calculate the hallway's position hallwayPos = prevRoomPos + new Vector2(offsetPrev, prevRoomRadius.y + hallwayRadius.y); // Calculate offeset with the new room (TOP and BOT) are same calculation offsetNew = Mathf.RoundToInt(Random.Range(-newRoomRadius.x + hallwayRadius.x + _hallwayOffsetFromEdge, newRoomRadius.x - hallwayRadius.x - _hallwayOffsetFromEdge)); // Calculate the room's position newRoomPos = hallwayPos + new Vector2(-offsetNew, newRoomRadius.y + hallwayRadius.y); // Set the hallway's scale hallwayScale = new Vector2Int(hallwayWidth, hallwayLength); // Calculate the join location of the hallway and the previous room hallPrevJoinPoint = hallwayPos + new Vector2(0, -hallwayRadius.y); // Calculate the join location of the hallway and the new room hallNewJoinPoint = hallwayPos + new Vector2(0, hallwayRadius.y); // The angle of the bleed light for TOP (up) bleedLightRot = 0f; break; case RoomSide.BOT: // Calculate offset with the previous room (TOP and BOT) are the same calculation offsetPrev = Mathf.RoundToInt(Random.Range(-prevRoomRadius.x + hallwayRadius.x + _hallwayOffsetFromEdge, prevRoomRadius.x - hallwayRadius.x - _hallwayOffsetFromEdge)); // Calculate the hallway's position hallwayPos = prevRoomPos + new Vector2(offsetPrev, -prevRoomRadius.y - hallwayRadius.y); // Calculate offeset with the new room (TOP and BOT) are same calculation offsetNew = Mathf.RoundToInt(Random.Range(-newRoomRadius.x + hallwayRadius.x + _hallwayOffsetFromEdge, newRoomRadius.x - hallwayRadius.x - _hallwayOffsetFromEdge)); // Calculate the room's position newRoomPos = hallwayPos + new Vector2(-offsetNew, -newRoomRadius.y - hallwayRadius.y); // Set the hallway's scale hallwayScale = new Vector2Int(hallwayWidth, hallwayLength); // Calculate the join location of the hallway and the previous room hallPrevJoinPoint = hallwayPos + new Vector2(0, hallwayRadius.y); // Calculate the join location of the hallway and the new room hallNewJoinPoint = hallwayPos + new Vector2(0, -hallwayRadius.y); // The angle of the bleed light for BOT (down) bleedLightRot = 180f; break; case RoomSide.RIGHT: // Calculate offset with the previous room (RIGHT and LEFT) are the same calculaiton offsetPrev = Mathf.RoundToInt(Random.Range(-prevRoomRadius.y + hallwayRadius.x + _hallwayOffsetFromEdge, prevRoomRadius.y - hallwayRadius.x - _hallwayOffsetFromEdge)); // Calculate the hallway's position hallwayPos = prevRoomPos + new Vector2(prevRoomRadius.x + hallwayRadius.y, offsetPrev); // Calculate offeset with the new room (RIGHT and LEFT) are same calculation offsetNew = Mathf.RoundToInt(Random.Range(-newRoomRadius.y + hallwayRadius.x + _hallwayOffsetFromEdge, newRoomRadius.y - hallwayRadius.x - _hallwayOffsetFromEdge)); // Calculate the room's position newRoomPos = hallwayPos + new Vector2(newRoomRadius.x + hallwayRadius.y, -offsetNew); // Set the hallway's scale hallwayScale = new Vector2Int(hallwayLength, hallwayWidth); // Calculate the join location of the hallway and the previous room hallPrevJoinPoint = hallwayPos + new Vector2(-hallwayRadius.y, 0); // Calculate the join location of the hallway and the new room hallNewJoinPoint = hallwayPos + new Vector2(hallwayRadius.y, 0); // The angle of the bleed light for RIGHT (right) bleedLightRot = 270f; break; case RoomSide.LEFT: // Calculate offset with the previous room (RIGHT and LEFT) are the same calculaiton offsetPrev = Mathf.RoundToInt(Random.Range(-prevRoomRadius.y + hallwayRadius.x + _hallwayOffsetFromEdge, prevRoomRadius.y - hallwayRadius.x - _hallwayOffsetFromEdge)); // Calculate the hallway's position hallwayPos = prevRoomPos + new Vector2(-prevRoomRadius.x - hallwayRadius.y, offsetPrev); // Calculate offeset with the new room (RIGHT and LEFT) are same calculation offsetNew = Mathf.RoundToInt(Random.Range(-newRoomRadius.y + hallwayRadius.x + _hallwayOffsetFromEdge, newRoomRadius.y - hallwayRadius.x - _hallwayOffsetFromEdge)); // Calculate the room's position newRoomPos = hallwayPos + new Vector2(-newRoomRadius.x - hallwayRadius.y, -offsetNew); // Set the hallway's scale hallwayScale = new Vector2Int(hallwayLength, hallwayWidth); // Calculate the join location of the hallway and the previous room hallPrevJoinPoint = hallwayPos + new Vector2(hallwayRadius.y, 0); // Calculate the join location of the hallway and the new room hallNewJoinPoint = hallwayPos + new Vector2(-hallwayRadius.y, 0); // The angle of the bleed light for LEFT (left) bleedLightRot = 90f; break; default: Debug.Log("TOP, BOT, RIGHT, and LEFT were all not chosen as the direction to spawn the hallway at."); break; } // If the room is valid, we can spawn it if (IsRoomValid(newRoomPos, newRoomSize)) { // Create the hallway and the room Transform hallwayTrans = Instantiate(_roomPrefab, new Vector3(hallwayPos.x, hallwayPos.y, 0), Quaternion.identity, _roomParent).transform; hallwayTrans.localScale = new Vector3(hallwayScale.x, hallwayScale.y, hallwayTrans.localScale.z); Transform newRoomTrans = Instantiate(_roomPrefab, new Vector3(newRoomPos.x, newRoomPos.y, 0), Quaternion.identity, _roomParent).transform; newRoomTrans.localScale = new Vector3(newRoomSize.x, newRoomSize.y, newRoomTrans.localScale.z); // Make the new room be adjacent to the hallway, // the hallway adjacent to the new room and the previous rooom, // and the previous room adjacent to the hallway // First get references Room newRoomScriptRef = newRoomTrans.GetComponent <Room>(); Room hallwayScriptRef = hallwayTrans.GetComponent <Room>(); Room prevRoomScriptRef = prevRoomTrans.GetComponent <Room>(); // Now add the adj rooms newRoomScriptRef.AdjacentRooms.Add(hallwayScriptRef); hallwayScriptRef.AdjacentRooms.Add(newRoomScriptRef); hallwayScriptRef.AdjacentRooms.Add(prevRoomScriptRef); prevRoomScriptRef.AdjacentRooms.Add(hallwayScriptRef); // Update the weights of each room to be 1 plus their previous room hallwayScriptRef.RoomWeight = prevRoomScriptRef.RoomWeight + 1; newRoomScriptRef.RoomWeight = hallwayScriptRef.RoomWeight + 1; // Set the new hallway to be a hallway and the new room to not be a hallway hallwayScriptRef.MyRoomType = RoomType.HALLWAY; newRoomScriptRef.MyRoomType = RoomType.NORMAL; ///// Spawn the lights at the join locations with the proper angles //// For between the prev room and hallway /// From the prev room to the hallway // Spawn BleedLight prefab GameObject hallFromPrevBroadcastObj = Instantiate(_bleedLightPrefab, hallPrevJoinPoint, Quaternion.Euler(0, 0, bleedLightRot), _bleedLightsParent); Vector3 tempPos = hallFromPrevBroadcastObj.transform.position; tempPos.z = -1; hallFromPrevBroadcastObj.transform.position = tempPos; // Get a reference to the BleedLight script attached to that object BleedLight hallFromPrevBroadcastBleedLight = hallFromPrevBroadcastObj.GetComponent <BleedLight>(); // Add the BleedLight to the appropriate broadcast and receive lists prevRoomScriptRef.BroadcastLights.Add(hallFromPrevBroadcastBleedLight); hallwayScriptRef.ReceiveLights.Add(hallFromPrevBroadcastBleedLight); // Give the BleedLight references to its corresponding Broadcast and Receive Rooms hallFromPrevBroadcastBleedLight.BroadcastRoom = prevRoomScriptRef; hallFromPrevBroadcastBleedLight.ReceiveRoom = hallwayScriptRef; /// From the hallway to the previous room // Spawn BleedLight prefab GameObject hallFromPrevReceiveObj = Instantiate(_bleedLightPrefab, hallPrevJoinPoint, Quaternion.Euler(0, 0, 180 + bleedLightRot), _bleedLightsParent); tempPos = hallFromPrevReceiveObj.transform.position; tempPos.z = -1; hallFromPrevReceiveObj.transform.position = tempPos; // Get a reference to the BleedLight script attached to that object BleedLight hallFromPrevReceiveBleedLight = hallFromPrevReceiveObj.GetComponent <BleedLight>(); // Add the BleedLight to the appropriate broadcast and receive lists hallwayScriptRef.BroadcastLights.Add(hallFromPrevReceiveBleedLight); prevRoomScriptRef.ReceiveLights.Add(hallFromPrevReceiveBleedLight); // Give the BleedLight references to its corresponding Broadcast and Receive Rooms hallFromPrevReceiveBleedLight.BroadcastRoom = hallwayScriptRef; hallFromPrevReceiveBleedLight.ReceiveRoom = prevRoomScriptRef; //// For between the new room and hallway /// From the new room to the hallway // Spawn BleedLight prefab GameObject hallFromNewBroadcastObj = Instantiate(_bleedLightPrefab, hallNewJoinPoint, Quaternion.Euler(0, 0, 180 + bleedLightRot), _bleedLightsParent); tempPos = hallFromNewBroadcastObj.transform.position; tempPos.z = -1; hallFromNewBroadcastObj.transform.position = tempPos; // Get a reference to the BleedLight script attached to that object BleedLight hallFromNewBroadcastBleedLight = hallFromNewBroadcastObj.GetComponent <BleedLight>(); // Add the BleedLight to the appropriate broadcast and receive lists newRoomScriptRef.BroadcastLights.Add(hallFromNewBroadcastBleedLight); hallwayScriptRef.ReceiveLights.Add(hallFromNewBroadcastBleedLight); // Give the BleedLight references to its corresponding Broadcast and Receive Rooms hallFromNewBroadcastBleedLight.BroadcastRoom = newRoomScriptRef; hallFromNewBroadcastBleedLight.ReceiveRoom = hallwayScriptRef; /// From the hallway to the new room // Spawn BleedLight prefab GameObject hallFromNewReceiveObj = Instantiate(_bleedLightPrefab, hallNewJoinPoint, Quaternion.Euler(0, 0, bleedLightRot), _bleedLightsParent); tempPos = hallFromNewReceiveObj.transform.position; tempPos.z = -1; hallFromNewReceiveObj.transform.position = tempPos; // Get a reference to the BleedLight script attached to that object BleedLight hallFromNewReceiveBleedLight = hallFromNewReceiveObj.GetComponent <BleedLight>(); // Add the BleedLight to the appropriate broadcast and receive lists hallwayScriptRef.BroadcastLights.Add(hallFromNewReceiveBleedLight); newRoomScriptRef.ReceiveLights.Add(hallFromNewReceiveBleedLight); // Give the BleedLight references to its corresponding Broadcast and Receive Rooms hallFromNewReceiveBleedLight.BroadcastRoom = hallwayScriptRef; hallFromNewReceiveBleedLight.ReceiveRoom = newRoomScriptRef; // Give the hallway and room a name hallwayTrans.name = "Hallway " + (roomsSpawned - 1).ToString(); newRoomTrans.name = "Room " + roomsSpawned.ToString(); // Make the chance not to update the prevRoom to instead create a branch // If the room is not a branch if (Random.Range(0, _chanceToSpawnBranch + 12 / _amountRoomsToSpawn) != 0) { // Make the prevRoom the room prevRoomPos = newRoomPos; prevRoomSize = newRoomSize; prevRoomTrans = newRoomTrans; } // If the room is a branch else { newRoomTrans.name += " Branch"; } // Increment ++roomsSpawned; // Say that the spawn was successful spawnSuccessful = true; } // If the room isn't valid and we have not yet checked all sides of the prevRoom, pick a new side and test again else if (amountSidesTested < 4) { // If the room is not valid, we need to choose the next side hallwaySide = RoomSide.TOP + ((int)hallwaySide + 1) % 4; ++amountSidesTested; spawnSuccessful = false; } // If the room isn't valid and we have already checked all the sides, we want to choose a different room to be the current room else if (amountSidesTested >= 4) { // We want the normal room that was before the last normal room, this means the room that is 2 behind the current prevRoom // since we spawn an initial room and then hallway, room, hallway, etc. prevRoomIndex -= 2; // If the new index is invalid, we have gone through all rooms possible, // so it is invalid to spawn any other rooms, so stop creating rooms entirely if (prevRoomIndex < 0) { Debug.Log("Cannot create anymore rooms"); return(rtnList); } // Otherwise, the room is valid, so we can set the prevRoom info to that room else { // Set the prevRoom info prevRoomTrans = _roomParent.GetChild(prevRoomIndex); prevRoomPos = prevRoomTrans.position; prevRoomSize = prevRoomTrans.localScale; // Also reset how many iterations of amountSidesTested we had amountSidesTested = 0; } } else { Debug.Log("WARNING - BUG DETECTED. THIS LINE IS NEVER SUPPOSED TO BE EXECUTED."); } if (++timesLooped > breakOutLimit) { Debug.Log("Too many iterations, had to break"); break; } } } // Return the parent of the rooms and the parent of the bleed lights return(rtnList); }
public int GenerateRoom(int floorIndex, int roomIndex, Material wallMaterial, Material floorMaterial, Transform parentContainer) { string newName = string.Format("room{0}-{1}", floorIndex, roomIndex); assignedFurniture.Clear(); PopulateSideAssignmentOrder(); Dimensions = new Vector3( UnityEngine.Random.Range(MinDimensions.x, MaxDimensions.x), UnityEngine.Random.Range(MinDimensions.y, MaxDimensions.y), UnityEngine.Random.Range(MinDimensions.z, MaxDimensions.z)); var _light = GameObject.Instantiate(LightPrefab, Vector3.zero, Quaternion.identity) as Light; var _blacklight = GameObject.Instantiate(LightPrefab, Vector3.zero, Quaternion.identity) as Light; wallLeft = GameObject.Instantiate(WallPartPrefab, Vector3.zero, Quaternion.identity) as RoomWall; wallRight = GameObject.Instantiate(WallPartPrefab, Vector3.zero, Quaternion.identity) as RoomWall; wallBack = GameObject.Instantiate(WallPartPrefab, Vector3.zero, Quaternion.identity) as RoomWall; floor = GameObject.Instantiate(WallPartPrefab, Vector3.zero, Quaternion.identity) as RoomWall; ceiling = GameObject.Instantiate(WallPartPrefab, Vector3.zero, Quaternion.identity) as RoomWall; GameObject room = new GameObject(newName, typeof(BuildingRoom)); room.transform.SetToParentZero(parentContainer); room.transform.position = Vector3.left * 100; var roomComponent = room.GetComponent<BuildingRoom>(); roomComponent.Room = roomIndex; roomComponent.Floor = floorIndex; roomComponent.Dimensions = Dimensions; BuiltRooms.Add(room); wallLeft.transform.SetParent(room.transform); wallRight.transform.SetParent(room.transform); wallBack.transform.SetParent(room.transform); floor.transform.SetParent(room.transform); ceiling.transform.SetParent(room.transform); _light.transform.SetParent(room.transform); _blacklight.transform.SetParent(room.transform); floor.transform.localScale = new Vector3(Dimensions.x, 0.1f, Dimensions.z); ceiling.transform.localScale = new Vector3(Dimensions.x, 0.1f, Dimensions.z); wallRight.SetSize(Dimensions.z, Dimensions.y); wallLeft.SetSize(Dimensions.z, Dimensions.y); wallBack.SetSize(Dimensions.x, Dimensions.y); _light.transform.localPosition = Vector3.zero; _blacklight.transform.localPosition = Vector3.zero; floor.transform.localPosition = Vector3.zero; ceiling.transform.localPosition = Vector3.zero; _light.transform.localPosition += Vector3.up * Dimensions.y; _blacklight.transform.localPosition += Vector3.up * Dimensions.y; wallLeft.transform.localPosition = new Vector3(Dimensions.x * 0.5f, 0, 0); wallRight.transform.localPosition = new Vector3(-(Dimensions.x * 0.5f), 0, 0); wallBack.transform.localPosition = new Vector3(0, 0, (Dimensions.z * 0.5f)); ceiling.transform.localPosition += Vector3.up * Dimensions.y; wallLeft.transform.localRotation = Quaternion.Euler(Vector3.up * 90); wallRight.transform.localRotation = Quaternion.Euler(Vector3.up * -90); _light.range = (Dimensions.x + Dimensions.z) * 2; _blacklight.range = 5; // (Dimensions.x + Dimensions.z) * 2; BedSide = (RoomSide)UnityEngine.Random.Range(0, 2); SideAssignmentOrder.Remove(BedSide); SideAssignmentOrder.Insert(0, BedSide); FillWalls(); roomComponent.AssignIndexesToItems(); SetWallMaterial(wallMaterial); SetFloorMaterial(floorMaterial); _blacklight.color = Color.Lerp(Color.red, Color.blue, .5f); _blacklight.intensity = 4; _blacklight.gameObject.SetActive(false); roomComponent.Blacklight = _blacklight; roomComponent.RoomLight = _light; return BuiltRooms.Count - 1; }
public ObjectFacingDirection(GoalObject target) { this.target = target; side = RandomSide(); }
public ObjectBySideWall(GoalObject target) { this.target = target; side = RandomSide(); }
public ObjectOnSideOfRoom(GoalObject target) { this.target = target; side = RandomSide(); }
private Transform GetWall(RoomSide side) { switch (side) { case RoomSide.Back: return wallBack.transform; case RoomSide.Left: return wallLeft.transform; case RoomSide.Right: return wallRight.transform; default: return null; } }
private float GetWallWidth(RoomSide side) { switch (side) { case RoomSide.Back: return Dimensions.x; case RoomSide.Left: case RoomSide.Right: return Dimensions.z; default: return Dimensions.x; } }
public Room[][] GenerateRoomMap(World world) { difficulty += difficulty / 4; roomsWithLogicToGenerate.Clear(); roomsWithLogicToGenerate.Add(new StartRoomLogic()); roomsWithLogicToGenerate.Add(new ExitRoomLogic()); amountOfRoomsToGenerate = random.Next(10, 20 + difficulty); if (roomLogicRegistry.Count > 0) { for (int i = 0; i < (amountOfRoomsToGenerate * precentOfRoomWithLogic) / 100; i++) { roomsWithLogicToGenerate.Add(roomLogicRegistry[random.Next(roomLogicRegistry.Count)].CreateNew()); } } Room[][] roomMap = new Room[world.worldSize.x][]; for (int x = 0; x < world.worldSize.x; x++) { roomMap[x] = new Room[world.worldSize.y]; } Position pos = new Position(world.worldSize.x / 2, world.worldSize.y / 2); Position dir = new Position(); roomMap[pos.x][pos.y] = new Room(pos); List <Position> roomsWithEmptyNeighbour = new List <Position>(); List <Position> validMoves = new List <Position>(); for (int i = 1; i < amountOfRoomsToGenerate; i++) { while (dir == Position.zero) { validMoves.Clear(); foreach (Position direction in Position.directions) { if (world.RoomInBounds(pos + direction) && roomMap[pos.x + direction.x][pos.y + direction.y] == null) { validMoves.Add(direction); } } if (roomsWithEmptyNeighbour.Count > 0 && random.Next(0, 10) == 0) { pos = roomsWithEmptyNeighbour[0]; roomsWithEmptyNeighbour.RemoveAt(0); continue; } //Debug.Log(validMoves.Count); if (validMoves.Count == 0) { if (roomsWithEmptyNeighbour.Count > 0) { pos = roomsWithEmptyNeighbour[0]; roomsWithEmptyNeighbour.RemoveAt(0); continue; } else { break; } } if (validMoves.Count > 1) { roomsWithEmptyNeighbour.Add(pos); } dir = validMoves[random.Next(validMoves.Count)]; } RoomSide rs = (RoomSide)random.Next(1, 3); for (int f = 0; f < Position.directions.Length; f++) { if (dir == Position.directions[f]) { roomMap[pos.x][pos.y].roomSides[f] = rs; } if (-dir == Position.directions[f]) { roomMap[pos.x + dir.x][pos.y + dir.y] = new Room(pos + dir); roomMap[pos.x + dir.x][pos.y + dir.y].roomSides[f] = rs; roomMap[pos.x + dir.x][pos.y + dir.y].distanceFromStart = roomMap[pos.x][pos.y].distanceFromStart + 1; } } pos += dir; dir = Position.zero; } return(roomMap); }
private float AssignFurnitureToSide(FurnitureType furnitureType, RoomSide side, float workingX) { RoomItem item = GetFurniture(furnitureType); Vector2 size = GetFurnitureSize(furnitureType); Transform wall = GetWall(side); float sideLength = GetWallWidth(side); item.transform.SetParent(wall, true); item.transform.localPosition = Vector3.zero; item.transform.localRotation = Quaternion.identity; item.transform.localPosition += Vector3.right * ((size.x / 2) + workingX); item.transform.localPosition += Vector3.left * (sideLength / 2); item.transform.localPosition += Vector3.back * 0.5f; item.transform.localScale = new Vector3(size.x, size.y, 1); assignedFurniture.Add(furnitureType); if (furnitureType != FurnitureType.Door) { var hands = GameObject.Instantiate<Transform>(HandsPrefab); hands.SetParent(item.transform, true); hands.localPosition = Vector3.zero + (Vector3.back * 0.505f); hands.localRotation = Quaternion.identity; item.Hands = hands; } item.HideHands(); return size.x; }