public long GetRoadTime(Point[] points) { DBC.Assert(points.Length == 2, "Calculating road time requires exactly 2 points. " + points.Length + " were provided."); var cacheResult = routeCache.GetTime(points[0].address, points[1].address); if (cacheResult != null) { Log(points, true); return cacheResult.Value; } Log(points, false); var router = new RouteServiceClient(); var request = new RouteRequest(); request.Credentials = new Credentials(); request.Credentials.Token = GetToken(); request.Waypoints = new Waypoint[points.Length]; for (int i = 0; i < points.Length; i++) { var p = points[i]; var waypoint = new Waypoint(); waypoint.Description = p.address; waypoint.Location = new Location(); waypoint.Location.Latitude = p.lat; waypoint.Location.Longitude = p.lon; request.Waypoints[i] = waypoint; } RouteResponse response = router.CalculateRoute(request); var seconds = response.Result.Summary.TimeInSeconds; routeCache.Add(points, seconds); return seconds; }
public List<Waypoint> ShortestPath(Waypoint a, Waypoint b) { Dictionary<Waypoint, Waypoint> cameFrom = new Dictionary<Waypoint, Waypoint> (); Dictionary<Waypoint, float> costSoFar = new Dictionary<Waypoint, float> (); PQueue frontier = new PQueue(); cameFrom[a] = null; costSoFar [a] = 0f; frontier.push (a, 0); while (!frontier.empty ()) { Waypoint current = frontier.pop (); if (current == b) break; foreach (Waypoint next in current.connections) { float newCost = costSoFar [current] + Waypoint.distance (current, next); if (!costSoFar.ContainsKey(next) || newCost < costSoFar[next]) { costSoFar [next] = newCost; frontier.push (next, newCost); cameFrom [next] = current; } } } List<Waypoint> path = new List<Waypoint> (); Waypoint point = b; while (point != a) { path.Add (point); point = cameFrom[point]; } path.Add (a); path.Reverse (); return path; }
public void push(Waypoint w, float cost) { PNode node = new PNode (w, cost); if (count == 0) { head = node; tail = node; } else { // find the place to insert PNode curr = head; while (curr != null && curr.cost < node.cost) { curr = curr.next; } if (curr == null) { // we are inserting at the end tail.next = node; node.prev = tail; node.next = null; tail = node; } else if (curr == head) { // we are insterint at the beginning head.prev = node; node.next = head; node.prev = null; head = node; } else { // somewhere in the middle curr.prev.next = node; node.prev = curr.prev; node.next = curr; curr.prev = node; } } count++; }
void Update() { if (death_timer_ > 0.0f) { death_timer_ -= Time.deltaTime; if (death_timer_ <= 0.0f) { Rigidbody rigidbody = GetComponent<Rigidbody>(); if (rigidbody != null) { rigidbody.constraints = RigidbodyConstraints.FreezeRotation; } AndroidPool.Destroy(gameObject); } } else if (NextNode != null) { Vector3 pos = transform.position; Vector3 target_pos = NextNode.transform.position; target_pos.y = pos.y; Vector3 direction = (target_pos - pos).normalized; transform.Translate(direction * speed_ * Time.deltaTime, Space.World); transform.LookAt(target_pos); FixHeight(); if (Vector3.Distance(transform.position, target_pos) <= node_threshold) { if (NextNode.Next.Count > 0) { NextNode = NextNode.Next[0]; } else { NextNode = null; } } } }
public void Reset() { m_isMoving = false; m_levelStartWp = null; m_levelEndWp = null; m_nextWaypoint = null; }
public Waypoint(long timeVal, Tile tileVal, Waypoint prevVal, List<UnitSelection> startVal) { time = timeVal; tile = tileVal; prev = prevVal; start = startVal; }
// Use this for initialization protected override void Start() { thePlayerPosition = GameObject.FindGameObjectWithTag("Player").transform.position; characterController = GetComponent<CharacterController>(); UnityEngine.Random.seed = RANDOMIZER_SEED; current = path[currentIndex]; }
// Use this for initialization void Start() { current = waypoints [0]; rbody = GetComponent<Rigidbody2D> (); rbody.velocity = current.speed*(current.transform.position - transform.position) / (current.transform.position - transform.position).magnitude; initialized = true; }
public override void OnTriggerEnter(Collider trigger) { base.OnTriggerEnter (trigger); if (activeWaypoint.GetComponent<Collider>() == trigger) { activeWaypoint = activeWaypoint.getNextWaypoint(); } }
void Update() { if (Input.GetMouseButtonDown(0)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit)) { Waypoint waypoint = hit.collider.GetComponent<Waypoint>(); if (waypoint != null) { path = graphManager.GetPath(currentWaypoint, waypoint); } } } if (path != null && path.Count > 0 && Vector3.Distance(transform.position, currentWaypoint.transform.position) < reachThreshold) { currentWaypoint = path[0]; path.RemoveAt(0); } transform.position = Vector3.Lerp(transform.position, currentWaypoint.transform.position, lerpRatio * Time.deltaTime); }
public override void Start() { base.Start (); startRotation = -180f; activeWaypoint = Waypoint.startingWaypoint; player = GameObject.FindGameObjectWithTag("Player"); enemies = GameObject.FindGameObjectsWithTag("Enemy"); for (int i = 0; i < enemies.Length; i++) if (enemies[i] == this.gameObject) enemies[i] = player; obstacles = GameObject.FindGameObjectsWithTag("Terrain"); timeToDestroy = 0.0f; rotation += startRotation; syncStartPosition = GetComponent<Rigidbody>().position; syncEndPosition = GetComponent<Rigidbody>().position; syncStartRotation = GetComponent<Rigidbody>().rotation; syncEndRotation = GetComponent<Rigidbody>().rotation; nextBurst = true; burstTime = 0.0f; flare = turboFlare.GetComponent<ParticleSystem> (); core = turboCore.GetComponent<ParticleSystem> (); flare.startSize = 2.0f; core.startSize = 2.0f; flare.startRotation = transform.eulerAngles.y *Mathf.Deg2Rad; core.startRotation = transform.eulerAngles.y *Mathf.Deg2Rad; turboFlare.SetActive (false); turboCore.SetActive (false); }
void MoveToWaypoit(Waypoint waypoint) { //als de waypoint afstand kleiner is als 0.1 dan haal nieuwe waypoint op if (Vector2.Distance(waypoint.gameObject.transform.position, this.transform.position) < 0.1) { this.targetWaypoint = waypoint.NextWaypoint; } else { //reken de vector richting de waypoint uit Vector2 vectorRichtingWaypoint = waypoint.transform.position - this.transform.position; //normalize deze vector(dat betekend dat de lengte van de vector terug naar 1 gebracht word) vectorRichtingWaypoint.Normalize(); //vermenigvuldig deze vector met de (speed*deltatime) die we willen hebben(dit betekend de lengte van de vector word nu zo groot als de speed*detltatime) vectorRichtingWaypoint *= Speed * Time.fixedDeltaTime; //voeg deze nieuwe vector aan onze positie en we bewegen richting de waypoint this.transform.position += new Vector3(vectorRichtingWaypoint.x, vectorRichtingWaypoint.y); //convert v3 naar v2 Vector2 thispos = new Vector2(this.transform.position.x, this.transform.position.y); this.drawLineTo(this.movementLine, this.transform.position, thispos + vectorRichtingWaypoint.normalized * Speed); this.bewegingsVector = vectorRichtingWaypoint; } }
// Use this for initialization void Start() { animation.Play(); myController = GetComponent<CharacterController>(); initialPosition = transform.position; initialWaypoint = waypoint; }
public void AddRotationWaypoint() { GameObject go = new GameObject(); go.AddComponent("RotationWaypoint"); Waypoint w = go.GetComponent<Waypoint>(); w.manager = this; if (count > 0) { if (last != null) { go.transform.position = last.transform.position; last.next = w; last = w; } else { last = first; while (last.next != null) { last = last.next; } go.transform.position = last.transform.position; last.next = w; last = w; } } else { first = w; last = w; go.transform.position = transform.position; } count++; Selection.activeObject = go; go.name = "Waypoint " + count + " (rotation)"; go.transform.parent = transform; }
private string CreateMajorRoutes(string locationString) { string results = ""; string key = "ArLeGdHOcc5h7j3L4W37oFGcU9E-LF3tAZi4o0DfhXbPJ8aiyTGbIDNHex08R2u7"; MajorRoutesRequest majorRoutesRequest = new MajorRoutesRequest(); // Set the credentials using a valid Bing Maps key majorRoutesRequest.Credentials = new RouteService.Credentials(); majorRoutesRequest.Credentials.ApplicationId = key; // Set the destination of the routes from major roads Waypoint endPoint = new Waypoint(); endPoint.Location = new RouteService.Location(); string[] digits = locationString.Split(','); endPoint.Location.Latitude = double.Parse(digits[0].Trim()); endPoint.Location.Longitude = double.Parse(digits[1].Trim()); endPoint.Description = "Location"; // Set the option to return full routes with directions MajorRoutesOptions options = new MajorRoutesOptions(); options.ReturnRoutes = true; majorRoutesRequest.Destination = endPoint; majorRoutesRequest.Options = options; // Make the route-from-major-roads request RouteServiceClient routeService = new RouteServiceClient("BasicHttpBinding_IRouteService"); // The result is an MajorRoutesResponse Object MajorRoutesResponse majorRoutesResponse = routeService.CalculateRoutesFromMajorRoads(majorRoutesRequest); Regex regex = new Regex("<[/a-zA-Z:]*>", RegexOptions.IgnoreCase | RegexOptions.Multiline); if (majorRoutesResponse.StartingPoints.Length > 0) { StringBuilder directions = new StringBuilder(); for (int i = 0; i < majorRoutesResponse.StartingPoints.Length; i++) { directions.Append(String.Format("Coming from {1}\n", i + 1, majorRoutesResponse.StartingPoints[i].Description)); for (int j = 0; j < majorRoutesResponse.Routes[i].Legs[0].Itinerary.Length; j++) { //Strip tags string step = regex.Replace( majorRoutesResponse.Routes[i].Legs[0].Itinerary[j].Text, string.Empty); directions.Append(String.Format(" {0}. {1}\n", j + 1, step)); } } results = directions.ToString(); } else results = "No Routes found"; return results; }
public static void CsvLoadTripRoutes(string filename, bool lngFirst) { // load trip routes Dictionary<string, LinkedList<Waypoint>> routes = new Dictionary<string, LinkedList<Waypoint>>(); using (CsvFileReader reader = new CsvFileReader(filename)) { CsvRow row = new CsvRow(); while (reader.ReadRow(row, ',')) { string routeID = row[0]; double distance = 0; double lat = Convert.ToDouble(lngFirst ? row[2] : row[1]); double lng = Convert.ToDouble(lngFirst ? row[1] : row[2]); if (routes.ContainsKey(routeID)) distance = routes[routeID].First.Value.GetDistance(new Location(lat, lng, "null")); Waypoint waypoint = new Waypoint(lat, lng, TimeSpan.Parse(row[3]), distance, row[4].Replace("\"", "")); // Scenario #1 if (!routes.ContainsKey(routeID)) routes[routeID] = new LinkedList<Waypoint>(); routes[routeID].AddLast(waypoint); } } foreach (LinkedList<Waypoint> w in routes.Values) { Route r = new Route(w.ToArray()); string key = Route.GetKey(r.start, r.end); MapTools.routes.Add(key, r); } }
public override void ResumeMovement(Transform target) { if (target == null) { CurrWaypoint = waypointManager.GetWaypoint(this.gameObject); this.target = CurrWaypoint.transform; } }
private bool CanSeePlayer(Waypoint waypoint) { RaycastHit2D hit = MazeManager.RayCast( CurrentPosition, waypoint, waypoint.Position - CurrentPosition, VISION_ANGLE_LIMIT, PLAYER_LAYER_MASK); return hit.collider != null; }
public virtual void Respawn() { CurrentPosition = spawn.Position; CurrentDirection = Vector2.zero; transform.rotation = Quaternion.identity; Target = spawn; }
private void decideNextPatrolPoint() { // Keep track of the previous patrol point to prevent backtracking previousWaypoint = parent.CurrentWaypoint; // Set our target to go to parent.FinalTargetWaypoint = parent.CurrentWaypoint.GetRandomNeighbour(previousWaypoint); }
// Game freaks out without a default constructor. I never use it. public StationaryPointParameter() { targetBody = Planetarium.fetch.Home; longitude = 0.0; wp = new Waypoint(); submittedWaypoint = false; this.successCounter = 0; }
public StationaryPointParameter(CelestialBody targetBody, double longitude) { this.targetBody = targetBody; wp = new Waypoint(); submittedWaypoint = false; this.successCounter = 0; this.longitude = longitude; }
public void Connect(Waypoint other) { if (other == null) throw new ArgumentNullException("other"); this.AddNeighbour(other); other.AddNeighbour(this); }
private int waypointWriteOffset = 0; //location where it can write next waypoint in array. #endregion Fields #region Constructors public WalkingQueue(Player player) { this.player = player; for(int i = 0; i < MAX_WALKING_WAYPOINTS; i++) walkingQueue[i] = new Waypoint(0, 0, -1); this.lastDirection = 6; resetWalkingQueue(); }
/// <summary>Initializes a new FlightGroup</summary> /// <remarks>All Orders set Throttle to <b>100%</b>, all Goals set to <b>FALSE</b>, SP1 <b>Enabled</b></remarks> public FlightGroup() { _stringLength = 0xC; for (int i = 0; i < _orders.Length; i++) _orders[i] = new Order(); for (int i = 0; i < _arrDepTriggers.Length; i++) _arrDepTriggers[i] = new Mission.Trigger(); Goals = new FGGoals(); for (int i = 0; i < _waypoints.Length; i++) _waypoints[i] = new Waypoint(); _waypoints[(int)WaypointIndex.Start1].Enabled = true; }
float targInnaccuracy = 2f; // Extra innaccuray to simulate mouse hand shake or something // Use this for initialization void Start () { netChar = GetComponent<NetworkCharacter>(); if(waypoints == null) { waypoints = GameObject.FindObjectsOfType<Waypoint>(); } destination = GetClosestWaypoint(); }
public void LoadFromXML() { XmlDocument doc = new XmlDocument(); string[] files = System.IO.Directory.GetFiles(Path, "*.xml"); doc.Load(files[0]); XmlElement xelRoot = doc.DocumentElement; XmlNodeList ModNodes = xelRoot.SelectNodes("/Mod"); foreach (XmlNode Mod in ModNodes) { modName = Mod["ModName"].InnerText; modDiscription = Mod["ModDiscription"].InnerText; } XmlNodeList ObjectNodes = xelRoot.SelectNodes("/Mod/Objects/Object"); foreach (XmlNode ParkOBJ in ObjectNodes) { ParkitectObject PO = new ParkitectObject(); PO.ObjName = ParkOBJ["OBJName"].InnerText; PO.type = (ParkitectObject.ObjType)Enum.Parse(typeof(ParkitectObject.ObjType), ParkOBJ["Type"].InnerText, true); PO.XSize = float.Parse(ParkOBJ["X"].InnerText); PO.ZSize = float.Parse(ParkOBJ["Z"].InnerText); PO.inGameName = ParkOBJ["inGameName"].InnerText; PO.price = Int32.Parse(ParkOBJ["price"].InnerText); PO.grid = Convert.ToBoolean(ParkOBJ["grid"].InnerText); PO.snapCenter = Convert.ToBoolean(ParkOBJ["snapCenter"].InnerText); PO.heightDelta = Int32.Parse(ParkOBJ["heightDelta"].InnerText); PO.recolorable = Convert.ToBoolean(ParkOBJ["recolorable"].InnerText); if (PO.recolorable) { PO.color1 = HexToColor(ParkOBJ["Color1"].InnerText); PO.color2 = HexToColor(ParkOBJ["Color2"].InnerText); PO.color3 = HexToColor(ParkOBJ["Color3"].InnerText); PO.color4 = HexToColor(ParkOBJ["Color4"].InnerText); } XmlNodeList WaypointsNodes = ParkOBJ.SelectNodes("Waypoints/Waypoint"); foreach (XmlNode xndNode in WaypointsNodes) { Waypoint w = new Waypoint(); w.isOuter = Convert.ToBoolean(xndNode["isOuter"].InnerText); w.isRabbitHoleGoal = Convert.ToBoolean(xndNode["isRabbitHoleGoal"].InnerText); if (xndNode["connectedTo"].InnerText != "") { w.connectedTo = xndNode["connectedTo"].InnerText.Split(',').ToList().ConvertAll(s => Int32.Parse(s)); } w.localPosition = getVector3(xndNode["localPosition"].InnerText); PO.waypoints.Add(w); } PO.XMLNode = ParkOBJ; ParkitectObjects.Add(PO); } UnityEngine.Debug.Log("Loaded from XML in : " + files[0]); }
void Start() { animAttack = GetComponent<Animator>(); Speed = Speed + (Random.value) + (Random.value); Tower = GameObject.FindObjectOfType<TowerHealth>(); targetWaypoint = this.FindClosestWaypoint(); this.movementLine = makeLine(Vector2.zero, Color.green); delay = delayTime; }
/// <summary> /// Adds the an unconnected waypoint to the map . /// </summary> /// <param name="waypoint">The waypoint.</param> public void AddWaypointUnconnected(Waypoint waypoint) { if (waypoint == null) throw new NullReferenceException("waypoint cannot be null"); waypoint.Id = getId(); waypoint.NeightBorWaypointsId = null; col.IdWaypoint.Add(waypoint.Id, waypoint); col.State = WaypointsState.UnConnected; }
/// <summary> /// Create a Route from an xml document /// </summary> /// <param name="element">The xml document for the route we want to parse</param> /// <param name="_userAssembly"></param> /// <returns>A newly created Route</returns> public static Route Parse(string xml) { XElement element = XElement.Parse(xml); Route route = new Route(); XElement waypointsNode = element.Element("Waypoints");//We get the first child of the root node. Which is the WaypointsNode //We get our start and end attributes. route.Start = waypointsNode.Attribute("start").Value; route.End = waypointsNode.Attribute("end").Value; route.Waypoints = new Dictionary<String, Waypoint>(); //We are going to circle through all the waypoint of the route (All the Waypoint node child of Waypoints). foreach (XElement waypointNode in waypointsNode.Elements()) { //We get all the infos we need from the node. Waypoint waypoint = new Waypoint(); waypoint.Id = waypointNode.Attribute("id").Value;//Get the id from the attributes. waypoint.Title = waypointNode.Element("Title") != null ? waypointNode.Element("Title").Value : "";//We set the title if the node has a Title child. waypoint.LatLng = new GeoCoordinate(float.Parse(waypointNode.Element("Lat").Value), float.Parse(waypointNode.Element("Lng").Value), 0);//We parse the value from the Lat and Lng child node value to create the position of the waypoint. waypoint.Destinations = new List<String>(); //We check that we have destinations and circle through all of them to add them to the waypoint. if (waypointNode.Element("Next") != null) { foreach (XElement next in waypointNode.Element("Next").Elements()) { waypoint.Destinations.Add(next.Value); } } //Same for conditions. waypoint.Conditions = new List<String>(); if (waypointNode.Element("Conditions") != null) { foreach (XElement tId in waypointNode.Element("Conditions").Elements()) { waypoint.Conditions.Add(tId.Value); } } route.Waypoints.Add(waypoint.Id, waypoint); } route.Triggers = new Dictionary<string, Trigger>(); if (element.Element("Triggers") != null) //We are going to loop through every trigger. foreach (XElement triggerElement in element.Element("Triggers").Elements()) { // For every trigger we get its factory and then we create a new trigger. TriggerFactory factory = TriggerFactory.GetFactory(triggerElement); Trigger t = factory.CreateTrigger(triggerElement); route.Triggers.Add(t.id, t); } return route; }
public void Import() { importResult = new ImportResult(); if (BeginWork != null) { BeginWork(this, new EventArgs()); } // The trackpoints List <RouteSegment> routeSegments = new List <RouteSegment>(); bool lastTrackpointWasInvalid = false; bool thisTrackpointIsInvalid = false; RouteSegment rs = new RouteSegment(); int current = 0; int total = sessionToImport.Trackpoints.Count; foreach (D303_Trk_Point_Type tp in sessionToImport.Trackpoints) { Waypoint waypoint = new Waypoint(); waypoint.Time = tp.TimeAsDateTime; waypoint.LongLat = new LongLat(tp.Position.LongitudeAsDegrees, tp.Position.LatitudeAsDegrees); waypoint.Altitude = (double)tp.Altitude; waypoint.HeartRate = (double)tp.HeartRate; thisTrackpointIsInvalid = (tp.Position.Latitude == 2147483647 && tp.Position.Longitude == 2147483647); if (!thisTrackpointIsInvalid) { rs.Waypoints.Add(waypoint); } if (thisTrackpointIsInvalid && lastTrackpointWasInvalid && rs.Waypoints.Count > 0) { routeSegments.Add(rs); rs = new RouteSegment(); } lastTrackpointWasInvalid = thisTrackpointIsInvalid; current++; if (WorkProgress != null && current % 10 == 0) { WorkProgress(this, new WorkProgressEventArgs((double)current / total)); } } if (rs.Waypoints.Count > 0) { routeSegments.Add(rs); } // The laps List <double> elapsedTimes = new List <double>(); double elapsedTime = 0; DateTime startTime = DateTime.MinValue; foreach (D1001_Lap_Type xLap in sessionToImport.Laps) { if (startTime == DateTime.MinValue) { startTime = xLap.StartTimeAsDateTime; } elapsedTimes.Add(elapsedTime); elapsedTime += (double)xLap.TotalTime / 100; } LapCollection laps = RouteImporterUtil.CreateLapsFromElapsedTimes(startTime, elapsedTimes, routeSegments); importResult.Route = new Route(routeSegments); importResult.Laps = laps; importResult.Succeeded = true; if (EndWork != null) { EndWork(this, new EventArgs()); } }
public Waypoint Peek() { Waypoint frontItem = data[0]; return(frontItem); }
// Add waypoint to drop path public void AddWaypoint(Waypoint waypoint) { dropWaypoints.Add(waypoint); }
public bool IsLast(Waypoint waypoint) { return(waypoint.id == waypoints.Count - 1); }
public static void setPlayerPosition(Character chr, float goX, float goY, short map) { MartialClient c = chr.getAccount().mClient; Logger.WriteLog(Logger.LogTypes.Debug, goX + " | " + goY + " | " + map); Area lastArea = chr.getArea(); Area newArea = WMap.Instance.getGrid(map).getAreaByRound(goX, goY); if (newArea == null) { StaticPackets.sendSystemMessageToClient(chr.getAccount().mClient, 1, "The position " + goX + "|" + goY + "|" + map + " can't be reached."); Waypoint closestTown = TownCoordsCache.Instance.getClosestWaypointForMap(map, new Waypoint(goX, goY)); if (closestTown == null) { Area vvArea = WMap.Instance.getGrid(1).getAreaByRound(-1660, 2344); if (vvArea == null) { Logger.WriteLog(Logger.LogTypes.Error, "Pure setPlayerPosition error {0}|{1}|{2}", goX, goY, map); StaticPackets.sendSystemMessageToClient(chr.getAccount().mClient, 1, "We're sorry, but an hard error has occured. Please report it to an admin."); c.Close(); return; } else { goX = -1660; goY = 2344; map = 1; newArea = vvArea; } } else { goX = closestTown.getX(); goY = closestTown.getY(); newArea = WMap.Instance.getGrid(map).getAreaByRound(goX, goY); } } if (lastArea != null) { WMap.Instance.getGrid(chr.getMap()).sendTo3x3AreaLeave(chr, lastArea); lastArea.removeCharacter(chr); } if (newArea != null) { chr.setArea(newArea); } else { chr.getAccount().mClient.Close(); return; } newArea.addCharacter(chr); chr.setMap(map); chr.setPosition(new float[] { goX, goY }); OutPacket op = new OutPacket(5840); op.WriteInt(5824); op.WriteShort(4); // 4 - 5 op.WriteShort(1); // 6 - 7 op.WriteInt(1); // 8 - 11 op.WriteInt(chr.getuID()); // 12 - 15 op.WriteShort(1); // 16 - 19 op.WriteShort(1); // 16 - 19 op.WriteInt(chr.getMap()); // 20 - 23 op.WriteInt(DateTime.Now.Year - 2000); // 24 - 27 op.WriteByte((byte)DateTime.Now.Month); // 28 op.WriteByte(DateTime.Now.Day > 30 ? (byte)0x1e : (byte)DateTime.Now.Day); // 29 op.WriteInt(DateTime.Now.Hour); // 30 - 37 for (int i = 0; i < 120; i++) { if (chr.getCargo().getSeqSaved()[i] != -1 && chr.getCargo().getCargoSaved()[chr.getCargo().getSeqSaved()[i]] != null) { op.WriteInt(); op.WriteByte((byte)(chr.getCargo().getSeqSaved()[i] / 100)); op.WriteByte((byte)(chr.getCargo().getSeqSaved()[i] % 100)); Item item = chr.getCargo().getCargoSaved()[chr.getCargo().getSeqSaved()[i]]; op.WriteInt(item.getItemID()); ItemData itemData = ItemDataCache.Instance.getItemData(item.getItemID()); if (itemData.getTimeToExpire() > 0) { } op.WriteShort(item.getQuantity()); } else { op.WriteZero(12); } } // 38 - 1477 op.Position = 1476; for (int i = 0; i < chr.getCommunity().getFriendsList().Capacity; i++) { if (chr.getCommunity().getFriendsList().ElementAtOrDefault(i) != null) { op.WritePaddedString(chr.getCommunity().getFriendsList()[i], 17); } else { op.WriteZero(17); } } // 1476 - 1934 op.WriteRepeatedByte(0x58, 40); op.Position = 1986; for (int i = 0; i < chr.getCommunity().getIgnoresList().Capacity; i++) { if (chr.getCommunity().getIgnoresList().ElementAtOrDefault(i) != null) { op.WritePaddedString(chr.getCommunity().getIgnoresList()[i], 17); } else { op.WriteZero(17); } } // 1987 - 2157 op.WriteInt(363); // questsy op.WriteLong(); op.WriteLong(138769276674441706); op.WriteLong(21692910); op.WriteShort(); op.WriteShort(1); op.Position = 2248; for (byte i = 0; i < 240; i++) { if (chr.getInventory().getSeqSaved()[i] != -1 && chr.getInventory().getInvSaved()[chr.getInventory().getSeqSaved()[i]] != null) { op.WriteShort(); op.WriteByte((byte)(chr.getInventory().getSeqSaved()[i] / 100)); op.WriteByte((byte)(chr.getInventory().getSeqSaved()[i] % 100)); Item item = chr.getInventory().getInvSaved()[chr.getInventory().getSeqSaved()[i]]; op.WriteInt(item.getItemID()); op.WriteInt(item.getQuantity()); } else { op.WriteZero(12); } } // 2252 - 5133 op.WriteLong(chr.getCoin()); op.Position = 5140; for (byte i = 0; i < 21; i++) { if (chr.getSkillBar().getSkillBar().ContainsKey(i)) { int barID = chr.getSkillBar().getSkillBar()[i]; if (barID > 200000000) { op.WriteInt(1); } else if (barID > 511) { op.WriteInt(5); barID -= 512; } else if (barID > 255) { op.WriteInt(6); barID -= 256; } else { SkillData skill = SkillDataCache.Instance.getSkill(chr.getSkills().getLearnedSkills().ElementAtOrDefault(barID)); if (skill == null) { op.WriteInt(0); } else if (skill.getTypeSpecific() == 6) { op.WriteInt(3); } else if (skill.getTypeSpecific() == 7) { op.WriteInt(4); } else { op.WriteInt(2); } } op.WriteInt(barID); } else { op.WriteZero(8); } } // 5140 - 5299 op.Position = 5320; for (int i = 0; i < 60; i++) { if (chr.getSkills().getLearnedSkills().Count > i && chr.getSkills().getLearnedSkills()[i] != 0) { op.WriteInt(chr.getSkills().getLearnedSkills()[i]); op.WriteInt(SkillDataCache.Instance.getSkill(chr.getSkills().getLearnedSkills()[i]).getSkillPoints()); } else { op.WriteLong(); } } // 5320 - 5799 op.WriteFloat(chr.getPosition()[0]); op.WriteFloat(chr.getPosition()[1]); op.WriteInt(0x0c); op.WriteInt(140338688); op.WriteInt(); op.WriteShort(); op.WriteShort(10962); //s3c0nd p4ck3t op.WriteInt(16); op.WriteInt(7929861); op.WriteInt(chr.getuID()); c.WriteRawPacket(op.ToArray()); WMap.Instance.getGrid(chr.getMap()).sendTo3x3AreaSpawn(chr, chr.getArea()); }
/// <summary> /// Called when [bot reached way point]. /// </summary> /// <param name="waypoint">The way point.</param> public abstract void OnReachedWaypoint(Waypoint waypoint);
void Awake() { waypoint = GetComponent <Waypoint>(); meshRenderer = gameObject.GetComponentInChildren <MeshRenderer>(); }
/// <summary> /// Moves within range of the current target. /// </summary> /// <param name="attackRange"></param> private void moveInRangeofTarget(float attackRange) { // First, update player and target location and save them locally Waypoint player_loc = getLocation(); Waypoint target_loc = this.target.getLocation(); if (!isInRange(target_loc, attackRange)) { // get the total distance float distance = player_loc.getDistance(target_loc); // Get the X vector float xVector = target_loc.getX() - player_loc.getX(); // Get the Y vector float yVector = target_loc.getY() - player_loc.getY(); // Quadrant int quadrant = 0; if (xVector >= 0 && yVector >= 0) { quadrant = 1; } else if (xVector < 0 && yVector >= 0) { quadrant = 2; } else if (xVector < 0 && yVector < 0) { quadrant = 3; } else { quadrant = 4; } xVector = Math.Abs(xVector); yVector = Math.Abs(yVector); // Find Theta float theta = (float)Math.Acos(xVector / distance); //Debug.Print("Theta: " + theta); float toMove = distance - (attackRange - 2.0f); //Debug.Print("Distance to move: " + toMove); float newX; float newY; if (toMove < 0.0f) { //faceTarget(); } else { // Calc new X newX = (float)Math.Cos(theta) * toMove; // Calc new Y newY = (float)Math.Sin(theta) * toMove; if (quadrant == 1) { } else if (quadrant == 2) { newX = newX * -1; } else if (quadrant == 3) { newX = newX * -1; newY = newY * -1; } else { newY = newY * -1; } Waypoint to_move = new Waypoint(player_loc.getX() + newX, player_loc.getY() + newY, (player_loc.getZ() + target_loc.getZ()) / 2.0f); moveToLoc(to_move); } } }
/// <summary> /// Faces a given Location. /// Sometimes still acts a bit funny. /// TODO: Facade this when Settings are implmented /// </summary> /// <param name="wp">Waypoint to face</param> private void faceLocation(Waypoint wp) { float turnaccuracy = 0.2f; // First, update player and target location and save them locally Waypoint player_loc = this.getLocation(); float PlayerFacing = this.getFacing(); //get the angle to which we need to turn in order to face our target float f = (float)Math.Atan2(wp.getY() - player_loc.getY(), wp.getX() - player_loc.getX()); //if the turning angle is negative //(sometimes happens, depending on negative coordinates and such) if (f < 0) { //add the maximum possible angle (PI x 2) to normalize the negative angle f += (float)(Math.PI * 2); } Debug.Print("Want to face: " + f); Debug.Print("Facing: " + PlayerFacing); if (PlayerFacing < (f + turnaccuracy) && PlayerFacing > (f - turnaccuracy)) { // We are already facing withing the error margin Debug.Print("Already Facing"); } else { double r, l; //if our current facing angle, in radians, is greater than //the angle which we desire to face if (PlayerFacing > f) { Debug.WriteLine("Current Angle GREATER than where we want to be."); //we'd have to turn past North if we're turning left l = ((2 * Math.PI) - PlayerFacing) + f; //we don't have to turn past North if we're turning right r = PlayerFacing - f; } else { Debug.WriteLine("Current Angle LESS than where we want to be."); //we don't have to turn past North if we're turning left l = f - PlayerFacing; //we have to turn past North if we're turning right r = PlayerFacing + ((2 * Math.PI) - f); } //let's please turn in the direction where we have to spend //the least amount of time turning //PostMessage.mouseHold((int)WoW_Instance.getProcess().MainWindowHandle, "right", 100, 100, false); Debug.WriteLine("L: " + l); Debug.WriteLine("R: " + r); if (l < r) { Debug.WriteLine("Turning Left."); //turnkey = Post.ArrowKeys.Left; // Banned for this method //PostMessage.SendKeys((int)WoW_Instance.getProcess().MainWindowHandle, "{LEFT}"); PostMessage.ArrowKey((int)WoW_Instance.getProcess().MainWindowHandle, "left", true); while (!(this.getFacing() < (f + turnaccuracy) && this.getFacing() > (f - turnaccuracy))) { //Thread.Sleep(10); //PostMessage.ArrowKey((int)WoW_Instance.getProcess().MainWindowHandle, "left", 20); } PostMessage.ArrowKey((int)WoW_Instance.getProcess().MainWindowHandle, "left", false); // try with mouse //PostMessage.LinearSmoothMove(100f, 15, "left"); } else { Debug.WriteLine("Turning Right."); //turnkey = Post.ArrowKeys.Right; // Banned for this method //PostMessage.SendKeys((int)WoW_Instance.getProcess().MainWindowHandle, "{RIGHT}"); PostMessage.ArrowKey((int)WoW_Instance.getProcess().MainWindowHandle, "right", true); while (!(this.getFacing() < (f + turnaccuracy) && this.getFacing() > (f - turnaccuracy))) { //Thread.Sleep(10); //PostMessage.ArrowKey((int)WoW_Instance.getProcess().MainWindowHandle, "right", 20); } PostMessage.ArrowKey((int)WoW_Instance.getProcess().MainWindowHandle, "right", false); //PostMessage.LinearSmoothMove(100f, 15, "right"); } //PostMessage.mouseHold((int)WoW_Instance.getProcess().MainWindowHandle, "right", 100, 100, true); //MemoryWriter.WriteMem(WoW_Instance.getProcess(), PlayerOffsets.FACING, BitConverter.GetBytes(f)); //Thread.Sleep(10); //PostMessage.SendKeys((int)WoW_Instance.getProcess().MainWindowHandle, "{RIGHT}"); } }
private void Awake() { wayPoint = GetComponent <Waypoint>(); }
public void SetTarget(Waypoint target) { targetWayPoint = target; foundTarget = true; }
// public static PathFollowerSkillProjectile Clone(SkillProjectile skillPrefab, Mage mage, Waypoint EndWaypoint, bool isAnimation) public static PathFollowerSkillProjectile Clone(SkillProjectile skillPrefab, Mage mage, Waypoint EndWaypoint) { Vector3 pos = new Vector3(EndWaypoint.transform.position.x, EndWaypoint.transform.position.y, EndWaypoint.transform.position.z); var skillProjectile = (PathFollowerSkillProjectile)GetPoolable(skillPrefab); skillProjectile.transform.position = pos; skillProjectile.transform.rotation = Quaternion.identity; skillProjectile.transform.LookAt(EndWaypoint.Previous.transform); skillProjectile._data = mage.Data.GetSkillData(); skillProjectile._player = mage.Player; // skillProjectile._isAnimation = isAnimation; return(skillProjectile); }
void Compare(GpsData data, GpsData data2) { Assert.AreEqual(data.Metadata.Count, data2.Metadata.Count); foreach (var entry in data.Metadata) { Assert.AreEqual(entry.Value, data2.Metadata[entry.Key]); } Assert.AreEqual(data.Tracks.Count, data2.Tracks.Count); for (int i = 0; i < data.Tracks.Count; i++) { Track track1 = data.Tracks[i]; Track track2 = data2.Tracks[i]; Assert.AreEqual(track1.Metadata.Count, track2.Metadata.Count); foreach (var entry in track1.Metadata) { Assert.AreEqual(entry.Value, track2.Metadata[entry.Key]); } Assert.AreEqual(track1.Segments.Count, track2.Segments.Count); for (int s = 0; s < track1.Segments.Count; s++) { TrackSegment segment1 = track1.Segments[s]; TrackSegment segment2 = track2.Segments[s]; Assert.AreEqual(segment1.Waypoints.Count, segment2.Waypoints.Count); for (int f = 0; f < segment1.Waypoints.Count; f++) { Waypoint f1 = segment1.Waypoints[f]; Waypoint f2 = segment2.Waypoints[f]; Compare(f1.Point.Coordinate, f2.Point.Coordinate); Assert.AreEqual(f1.TimeUtc, f2.TimeUtc); } } } Assert.AreEqual(data.Waypoints.Count, data2.Waypoints.Count); for (int i = 0; i < data.Waypoints.Count; i++) { Waypoint wp1 = data.Waypoints[i]; Waypoint wp2 = data2.Waypoints[i]; Assert.AreEqual(wp1.Name, wp2.Name); Assert.AreEqual(wp1.Description, wp2.Description); Assert.AreEqual(wp1.Comment, wp2.Comment); Compare(wp1.Coordinate, wp2.Coordinate); } Assert.AreEqual(data.Routes.Count, data2.Routes.Count); for (int i = 0; i < data.Routes.Count; i++) { Route r1 = data.Routes[i]; Route r2 = data2.Routes[i]; Assert.AreEqual(r1.Metadata.Count, r2.Metadata.Count); foreach (var entry in r1.Metadata) { Assert.AreEqual(entry.Value, r2.Metadata[entry.Key]); } Assert.AreEqual(r1.Waypoints.Count, r2.Waypoints.Count); for (int c = 0; c < r1.Waypoints.Count; c++) { Compare(r1.Waypoints[c], r2.Waypoints[c]); } } }
private void Awake() { waypoint = GetComponent <Waypoint>(); typeController = GetComponent <TypeController>(); }
void BuildBoardWaypoints() { Waypoint waypointPrev = null; Waypoint waypointCurrent = null; // Predefined walkable fields for current map // // top: left -> right for (int i = 3; i < 14; ++i) { AddWaypoint(i, 1, ref waypointCurrent, ref waypointPrev); } // right: top -> bottom for (int i = 1; i < 4; ++i) { AddWaypoint(14, i, ref waypointCurrent, ref waypointPrev); } // Save waypoint for later Waypoint waypointPrevTemp = waypointPrev; Waypoint waypointCurrentTemp = waypointCurrent; // build Violet home path for (int i = 13; i > 8; --i) { AddWaypoint(i, 3, ref waypointCurrent, ref waypointPrev); waypointCurrent.UseBy(Player.Type.Violet); } // Restore waypoints waypointPrev = waypointPrevTemp; waypointCurrent = waypointCurrentTemp; // right: top -> bottom for (int i = 4; i < 5; ++i) { AddWaypoint(14, i, ref waypointCurrent, ref waypointPrev); } for (int i = 14; i > 12; --i) { AddWaypoint(i, 5, ref waypointCurrent, ref waypointPrev); } violetPlayer.entry = waypointCurrent; for (int i = 5; i < 7; ++i) { AddWaypoint(12, i, ref waypointCurrent, ref waypointPrev); } // bottom: right -> left for (int i = 12; i > 1; --i) { AddWaypoint(i, 7, ref waypointCurrent, ref waypointPrev); } // left: bottom -> top for (int i = 7; i > 4; --i) { AddWaypoint(1, i, ref waypointCurrent, ref waypointPrev); } // Save waypoint for later waypointPrevTemp = waypointPrev; waypointCurrentTemp = waypointCurrent; // build Violet home path for (int i = 2; i < 7; ++i) { AddWaypoint(i, 5, ref waypointCurrent, ref waypointPrev); waypointCurrent.UseBy(Board.Player.Type.Mint); } // Restore waypoints waypointPrev = waypointPrevTemp; waypointCurrent = waypointCurrentTemp; AddWaypoint(1, 4, ref waypointCurrent, ref waypointPrev); for (int i = 1; i < 3; ++i) { AddWaypoint(i, 3, ref waypointCurrent, ref waypointPrev); } mintPlayer.entry = waypointCurrent; for (int i = 3; i > 1; --i) { AddWaypoint(3, i, ref waypointCurrent, ref waypointPrev); } // Connect with begine waypointCurrent.AddNextWaypoint(walkableFields[0]); walkableFields[0].AddPreviousWaypoint(waypointCurrent); }
/// <summary> /// Chooses the storage location to use for the given pod. /// </summary> /// <param name="pod">The pod to store.</param> /// <returns>The storage location to use for the pod.</returns> private Waypoint ChooseStorageLocation(Pod pod) { // Get the storage class the pod should end up in int desiredStorageClass = _classManager.DetermineStorageClass(pod); // Try to allocate the pod to its storage class - if not possible try neighboring classes int currentClassTriedLow = desiredStorageClass; int currentClassTriedHigh = desiredStorageClass; Waypoint chosenStorageLocation = null; while (true) { // Try the less frequent class first if (currentClassTriedLow < _classManager.ClassCount) { chosenStorageLocation = _classManager.GetClassStorageLocations(currentClassTriedLow) .Where(wp => !Instance.ResourceManager.IsStorageLocationClaimed(wp)) // Only use not occupied ones .OrderBy(wp => { switch (_config.PodDisposeRule) { case TurnoverPodStorageLocationDisposeRule.NearestEuclid: return(Distances.CalculateEuclid(wp, pod, Instance.WrongTierPenaltyDistance)); case TurnoverPodStorageLocationDisposeRule.NearestManhattan: return(Distances.CalculateManhattan(wp, pod, Instance.WrongTierPenaltyDistance)); case TurnoverPodStorageLocationDisposeRule.NearestShortestPath: return(Distances.CalculateShortestPathPodSafe(Instance.WaypointGraph.GetClosestWaypoint(pod.Tier, pod.X, pod.Y), wp, Instance)); case TurnoverPodStorageLocationDisposeRule.NearestShortestTime: return(Distances.CalculateShortestTimePathPodSafe(Instance.WaypointGraph.GetClosestWaypoint(pod.Tier, pod.X, pod.Y), wp, Instance)); case TurnoverPodStorageLocationDisposeRule.OStationNearestEuclid: return(Instance.OutputStations.Min(s => Distances.CalculateEuclid(wp, s, Instance.WrongTierPenaltyDistance))); case TurnoverPodStorageLocationDisposeRule.OStationNearestManhattan: return(Instance.OutputStations.Min(s => Distances.CalculateManhattan(wp, s, Instance.WrongTierPenaltyDistance))); case TurnoverPodStorageLocationDisposeRule.OStationNearestShortestPath: return(Instance.OutputStations.Min(s => Distances.CalculateShortestPathPodSafe(wp, s.Waypoint, Instance))); case TurnoverPodStorageLocationDisposeRule.OStationNearestShortestTime: return(Instance.OutputStations.Min(s => Distances.CalculateShortestTimePathPodSafe(wp, s.Waypoint, Instance))); case TurnoverPodStorageLocationDisposeRule.Random: return(wp.Instance.Randomizer.NextDouble()); default: throw new ArgumentException("Unknown pod dispose rule: " + _config.PodDisposeRule); } }) // Order the remaining ones by the given rule .FirstOrDefault(); // Use the first one } // Check whether we found a suitable pod of this class if (chosenStorageLocation != null) { break; } // Try the higher frequent class next if (currentClassTriedHigh >= 0 && currentClassTriedHigh != currentClassTriedLow) { chosenStorageLocation = _classManager.GetClassStorageLocations(currentClassTriedHigh) .Where(wp => !Instance.ResourceManager.IsStorageLocationClaimed(wp)) // Only use not occupied ones .OrderBy(wp => { switch (_config.PodDisposeRule) { case TurnoverPodStorageLocationDisposeRule.NearestEuclid: return(Distances.CalculateEuclid(wp, pod, Instance.WrongTierPenaltyDistance)); case TurnoverPodStorageLocationDisposeRule.NearestManhattan: return(Distances.CalculateManhattan(wp, pod, Instance.WrongTierPenaltyDistance)); case TurnoverPodStorageLocationDisposeRule.NearestShortestPath: return(Distances.CalculateShortestPathPodSafe(Instance.WaypointGraph.GetClosestWaypoint(pod.Tier, pod.X, pod.Y), wp, Instance)); case TurnoverPodStorageLocationDisposeRule.NearestShortestTime: return(Distances.CalculateShortestTimePathPodSafe(Instance.WaypointGraph.GetClosestWaypoint(pod.Tier, pod.X, pod.Y), wp, Instance)); case TurnoverPodStorageLocationDisposeRule.OStationNearestEuclid: return(Instance.OutputStations.Min(s => Distances.CalculateEuclid(wp, s, Instance.WrongTierPenaltyDistance))); case TurnoverPodStorageLocationDisposeRule.OStationNearestManhattan: return(Instance.OutputStations.Min(s => Distances.CalculateManhattan(wp, s, Instance.WrongTierPenaltyDistance))); case TurnoverPodStorageLocationDisposeRule.OStationNearestShortestPath: return(Instance.OutputStations.Min(s => Distances.CalculateShortestPathPodSafe(wp, s.Waypoint, Instance))); case TurnoverPodStorageLocationDisposeRule.OStationNearestShortestTime: return(Instance.OutputStations.Min(s => Distances.CalculateShortestTimePathPodSafe(wp, s.Waypoint, Instance))); case TurnoverPodStorageLocationDisposeRule.Random: return(wp.Instance.Randomizer.NextDouble()); default: throw new ArgumentException("Unknown pod dispose rule: " + _config.PodDisposeRule); } }) // Order the remaining ones by the given rule .FirstOrDefault(); // Use the first one } // Check whether we found a suitable pod of this class if (chosenStorageLocation != null) { break; } // Update the class indeces to check next currentClassTriedLow++; currentClassTriedHigh--; // Check index correctness if (currentClassTriedHigh < 0 && currentClassTriedLow >= _classManager.ClassCount) { throw new InvalidOperationException("There was no storage location available!"); } } // Return the chosen one return(chosenStorageLocation); }
public Waypoint GetNextWaypoint(Waypoint waypoint) { return(IsLast(waypoint) ? waypoints[0] : waypoints[waypoint.id + 1]); }
/// <summary> /// Determines a value that can be used to order possible rest locations for a pod. /// </summary> /// <param name="orderType">The order metric to use.</param> /// <param name="bot">The bot looking for a job.</param> /// <param name="restLocation">The rest location to look at.</param> /// <returns>A value reflecting the given metric. The lowest value indicates the best option for the given metric.</returns> public double RestLocationToBotAllocationMetric(PrefRestLocationForBot orderType, Bot bot, Waypoint restLocation) { double value; switch (orderType) { case PrefRestLocationForBot.Random: value = Instance.Randomizer.NextDouble(); break; case PrefRestLocationForBot.RandomSameTier: value = restLocation.Tier == bot.Tier ? -Instance.Randomizer.NextDouble() : Instance.Randomizer.NextDouble(); break; case PrefRestLocationForBot.Middle: value = bot.GetDistance(bot.Tier.Length / 2.0, bot.Tier.Width / 2.0); break; case PrefRestLocationForBot.MiddleSameTier: value = restLocation.Tier == bot.Tier ? restLocation.GetDistance(restLocation.Tier.Length / 2.0, restLocation.Tier.Width / 2.0) : restLocation.GetDistance(restLocation.Tier.Length / 2.0, restLocation.Tier.Width / 2.0) + Instance.WrongTierPenaltyDistance;; break; case PrefRestLocationForBot.Nearest: value = restLocation.Tier == bot.Tier ? bot.GetDistance(restLocation) : bot.GetDistance(restLocation) + Instance.WrongTierPenaltyDistance; break; default: throw new ArgumentException("Unknown order type: " + orderType); } return(value); }
/// <summary> /// Function to check if the Enemy has reached a particular Waypoint /// </summary> /// <param name="w">The Waypoint to check with.</param> /// <returns>If Enemy has reached Waypoint w</returns> internal bool reachedWaypoint(Waypoint w) { // Check if we have reached the Waypoint return(reachedPoint(w.transform.position)); }
public void addConnection(Waypoint p) { connections.Add(p); }
public WaypointRelative(ICoreAPI api, Waypoint ownWaypoint, int index) { this.api = api; OwnWaypoint = ownWaypoint; Index = index; }
void WaypointController_OnWaypointChanged(Waypoint waypoint) { pathFinder.setTarget(waypoint.transform.position); }