Example #1
0
        Transit CreateTransit()
        {
            Transit transit = new Transit();

            transit.Deleted    += (s, e) => { Console.WriteLine("Transit Deleted"); };
            transit.Repeat      = 1;
            transit.AutoReverse = true;
            transit.Duration    = 1;
            return(transit);
        }
Example #2
0
        private ITransit BuildPedestrianTransit <T>(T startNode, T endNode, ITransport transport) where T : INode
        {
            var pedestrianTransit = new Transit();

            pedestrianTransit.StartNode = startNode;
            pedestrianTransit.EndNode   = endNode;
            pedestrianTransit.Transport = transport;

            return(pedestrianTransit);
        }
        public async Task <ActionResult> AddTransit([FromBody] Transit transit)
        {
            var addTransitResult = await transitService.AddTransit(transit);

            if (!addTransitResult.IsSuccessful)
            {
                return(BadRequest(addTransitResult));
            }

            return(Ok(addTransitResult));
        }
 public TransitIcon(Transit transit, MapTab mapTab)
 {
     this.transit = transit;
     this.mapTab  = mapTab;
     InitializeComponent();
     Arrow.Width  = 20; //todo: optimization: make the path already have the right size
     Arrow.Height = 20;
     Canvas.SetZIndex(this, 1000);
     Canvas.SetZIndex(PlottedRouteLine, -2);
     Canvas.SetZIndex(PlaceOrderLine, -1);
     DataContext = transit;
 }
 public TransitIcon(Transit transit, MapTab mapTab)
 {
     this.transit = transit;
     this.mapTab = mapTab;
     InitializeComponent();
     Arrow.Width = 20; //todo: optimization: make the path already have the right size
     Arrow.Height = 20;
     Canvas.SetZIndex(this, 1000);
     Canvas.SetZIndex(PlottedRouteLine, -2);
     Canvas.SetZIndex(PlaceOrderLine, -1);
     DataContext = transit;
 }
Example #6
0
        public async Task <IActionResult> Post([FromBody] Transit value)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            value.Code = await _sequenceRepository.GetCode("Transit");

            await _transitRepository.InsertAsync(value);

            return(Created($"transit/{value.TransitId}", value));
        }
Example #7
0
    private void OnTransit(Transit transit, Transit.TransitState state, float progress)
    {
        if (state == Transit.TransitState.Finished)
        {
            // trigger at next update
            nextTime = Time.time;
            waiting  = false;
            Destroy(tunnel);
            tunnel = null;
            if (currentReef != null)
            {
                Destroy(currentReef);
            }
            currentReef = nextReef;
            nextReef    = null;
        }
        else
        {
            // TODO: When should the next reef be instantiated and old one destroyed? Immediately? Part way through the tunnel?
            if (nextReef == null)
            {
                // put reef in wrapper object positioned relative to transit destination
                nextReef = new GameObject("Reef Wrapper");
                nextReef.transform.parent = reefs.transform;
                GameObject reef = Instantiate(ReefPrefabs[ReefVisitIndex]);
                ReefVisitIndex = (ReefVisitIndex + 1) % ReefPrefabs.Length;
                ReefVisitCount++;
                reef.transform.parent = nextReef.transform;

                /*MeshRenderer renderer = reef.GetComponent<MeshRenderer>();
                 * if (renderer != null) {
                 *      renderer.material.color = new Color(Random.value, Random.value, Random.value, 1.0f);
                 * }*/

                activeStages.Clear();
                IReefVisitor[] visitors = reef.GetComponentsInChildren <IReefVisitor>();
                for (int i = 0, n = visitors.Length; i < n; i++)
                {
                    ReefStage stage = new ReefStage(this, activeStages);
                    activeStages.Add(stage);
                    visitors[i].visitingReef(stage);
                }

                // Place reef a bit past where transit will end
                Vector3 dir = transit.FinalPosition - transit.ExitPosition;
                dir.Normalize();
                Vector3 pos = transit.FinalPosition + 4 * dir;
                nextReef.transform.position = pos;
                // TODO: Rotate reef so it's facing the player
            }
        }
    }
        public GetTransitView(ref object value)
        {
            InitializeComponent();

            transitData   = value as Transit;
            this.flightID = transitData.flightID;
            mode          = (int)transitSign.modifyTransit;

            airport.PreviewTextInput += PlaneScheduleView.Instance.Menu_TextInput;
            airport.PreviewKeyDown   += PlaneScheduleView.Instance.Menu_PreviewKeyDown;

            this.loadData();
        }
        public async Task <IActionResult> Post([FromBody] Transit value)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            await _transitRepository.InsertAsync(value);

            value = _transitRepository.GetAll().Where(n => n.TransitId == value.TransitId).FirstOrDefault();

            return(Created($"transit/{value.TransitId}", value));
        }
Example #10
0
        public IActionResult ShowQuestion()
        {
            List <Transit> transitList = new List <Transit>();

            foreach (Question que in ds.GetQuestions())
            {
                Transit transit = new Transit();
                transit.Qid    = que.Id;
                transit.Qtitle = que.Title;
                transit.Qtext  = que.Text;
                transitList.Add(transit);
            }
            return(View("ShowQuestion", transitList));
        }
Example #11
0
        public IActionResult EditAnswer([FromForm(Name = "Aid")] string answerId)
        {
            Transit transit = new Transit();
            Answer  answer  = ds.GetAnswer(answerId);

            transit.Aid             = answer.AId;
            transit.AUserId         = answer.AUserId;
            transit.Qid             = answer.QId;
            transit.AsubmissionTime = answer.SubmissionTime;
            transit.Atext           = answer.Text;
            transit.Aimage          = answer.Image;
            transit.Aaccepted       = answer.Aaccepted;
            return(View("EditAnswer", transit));
        }
        private async void transitDataDelete_Click(object sender, RoutedEventArgs e)
        {
            Transit rowValue = transitDataGridView.SelectedItem as Transit;

            await FlightBusControl.Instance.DisableTransit(rowValue);

            await Task.Factory.StartNew(() => {
                this.Dispatcher.Invoke(() => {
                    List <Transit> tempList = transitDataGridView.ItemsSource as List <Transit>;
                    tempList.Remove(rowValue);
                    transitDataGridView.Items.Refresh();
                });
            });
        }
Example #13
0
        public IActionResult Vote()
        {
            List <Transit> transit_list = new List <Transit>();

            foreach (Question que in ds.GetQuestions())
            {
                Transit transit = new Transit();
                transit.Qid    = que.Id;
                transit.Qtitle = que.Title;
                transit.Qtext  = que.Text;
                transit.Qvote  = que.VoteNumber;
                transit_list.Add(transit);
            }
            return(View("Vote", transit_list));
        }
Example #14
0
        public IActionResult EditQuestion1()
        {
            List <Transit>  transList = new List <Transit>();
            List <Question> questions = ds.GetQuestions();

            foreach (Question qst in questions)
            {
                Transit transit = new Transit();
                transit.Qid    = qst.Id;
                transit.Qtitle = qst.Title;
                transit.Qtext  = qst.Text;
                transList.Add(transit);
            }
            return(View("EditQuestion1", transList));
        }
Example #15
0
        public InboundConnection(Socket s, ServerBase server, bool isBlocking) : base(isBlocking)
        {
            MyServer = server;
            NUM_CONNECTIONS_IN_MEMORY++;
            try
            {
                MyTCPSocket = s;
                MyTCPSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, DisableTCPDelay);

                m_TimeoutTimer = new Timer();

                int timeout = ConfigHelper.GetIntConfig("PlayerConnectionTimeout");
                if (timeout < 1)
                {
                    timeout = 10;
                }

                m_TimeoutTimer.Interval = timeout * 1000;
                m_TimeoutTimer.Elapsed += new ElapsedEventHandler(TimeoutTimer_Elapsed);
                m_TimeoutTimer.Start();

                ServerUser = new Shared.ServerUser();
                ServerUser.MyConnection = this;

                // Track the network socket associated with this connection object.
                string msg = "";
                if (!ConnectionManager.TrackUserSocket(this, ref msg))
                {
                    KillConnection(msg);
                    return;
                }

                if (!Transit.ListenForDataOnSocket())
                {
                    KillConnection("Remote end closed socket.");
                    return;
                }

                Log1.Logger("Server").Info("Now have [" + ConnectionManager.ConnectionCount.ToString() + " connections] attached.");
            }
            catch (Exception e)
            {
                KillConnection("Error instantiating Inbound connection object " + GetType().ToString() + " : " + e.Message);
                Log1.Logger("Server.Network").Error("Error instantiating Inbound connection object " + GetType().ToString() + " : " + e.Message, e);
                return;
            }
            SendRijndaelExchangeRequest();
        }
Example #16
0
        public IActionResult EditQuestion2([FromForm(Name = "editTitle")] string que)
        {
            Transit         transit   = new Transit();
            List <Question> questions = ds.GetQuestions();

            foreach (Question qst in questions)
            {
                if (que.Split(":").ToArray()[0] == qst.Id)
                {
                    transit.Qid    = qst.Id;
                    transit.Qtitle = qst.Title;
                    transit.Qtext  = qst.Text;
                }
            }
            return(View("EditQuestion2", transit));
        }
Example #17
0
        public async Task <IActionResult> Put([FromBody] Transit value, [FromRoute] int id)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != value.TransitId)
            {
                return(BadRequest());
            }

            await _transitRepository.UpdateAsync(value);

            return(Ok(value));
        }
Example #18
0
    private void OnTransit(Transit transit, Transit.TransitState state, float progress)
    {
        if (state == Transit.TransitState.Entering && !tubeAdded)
        {
            tubeAdded = true;

            GameObject tube   = new GameObject("tube");
            MeshFilter filter = tube.AddComponent <MeshFilter>();
            TubeMesh.generateTube(filter.mesh);

            MeshRenderer renderer = tube.AddComponent <MeshRenderer>();
            renderer.receiveShadows    = false;
            renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;

            if (TubeMaterial == null)
            {
                renderer.material.color = Color.red;
            }
            else
            {
                renderer.material = TubeMaterial;
            }

            /*
             * tube = GameObject.CreatePrimitive(PrimitiveType.Mes);
             * tube.GetComponent<MeshRenderer>().material.color = Color.red;
             * scale.x = DefaultDiameter;
             * scale.z = DefaultDiameter;*/

            // position tube between transit's enter and exit positions
            // Assumes tube is oriented along y dimension with ends at y=0 and y=1.
            Vector3   offset = transit.ExitPosition - transit.EnterPosition;
            Vector3   scale  = new Vector3(1f, offset.magnitude, 1f);
            Transform t      = tube.transform;
            t.position   = transit.EnterPosition;
            t.up         = offset;
            t.localScale = scale;
            t.parent     = gameObject.transform;
        }
        else if (state == Transit.TransitState.Finished)
        {
            // will be destroyed automatically at end
        }
    }
Example #19
0
        public IActionResult ShowQLatestSelect([FromForm(Name = "latestX")] int latestX)
        {
            List <Transit>  transitList  = new List <Transit>();
            List <Question> questionList = ds.GetQuestions(latestX);

            foreach (Question que in questionList)
            {
                Transit transit = new Transit();
                transit.Qid             = que.Id;
                transit.Qtitle          = que.Title;
                transit.Qtext           = que.Text;
                transit.Qvote           = que.VoteNumber;
                transit.QsubmissionTime = que.SubmissionTime;
                transitList.Add(transit);
            }
            return(View("ALtListQuestions", transitList));

            return(RedirectToAction("AltListQuestions", transitList));
        }
Example #20
0
    private void OnTransit(Transit transit, Transit.TransitState state, float progress)
    {
        if (state == Transit.TransitState.Entering && !tubeAdded)
        {
            tubeAdded = true;

            GameObject tube   = new GameObject("tube");
            MeshFilter filter = tube.AddComponent <MeshFilter>();

            List <TubePoint> points = new List <TubePoint>();
            CubicBezier      curve  = transit.Curve;

            for (float t = 0f; t < 1f; t += 0.2f)
            {
                points.Add(new TubePoint(curve.position(t), curve.derivative(t), calcRadius(t)));
            }
            points.Add(new TubePoint(curve.position(1), curve.derivative(1), calcRadius(1)));

            /*foreach (TubePoint p in points) {
             *      Debug.Log(p.position + " " + p.derivative + " " + p.radius);
             * }*/

            TubeMesh.generateTubes(filter.mesh, points, 8);

            MeshRenderer renderer = tube.AddComponent <MeshRenderer>();
            renderer.receiveShadows    = false;
            renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;

            if (TubeMaterial == null)
            {
                renderer.material.color = Color.red;
            }
            else
            {
                renderer.material = TubeMaterial;
            }
            tube.transform.parent = gameObject.transform;
        }
        else if (state == Transit.TransitState.Finished)
        {
            // will be destroyed automatically at end
        }
    }
Example #21
0
        public async Task <GenericResponse> AddTransit(Transit transit)
        {
            if (transit == null)
            {
                return(new GenericResponse(false, "No transit has been provided."));
            }

            try
            {
                await unitOfWork.TransitRepository.AddTransitAsync(transit);
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return(new GenericResponse(false, ex.InnerException.Message));
            }
            catch (DbUpdateException ex)
            {
                return(new GenericResponse(false, ex.InnerException.Message));
            }
            return(new GenericResponse(true, "New transit has been created."));
        }
    // Simply LERP the position through the transit. This won't be smooth.
    private void OnTransit(Transit transit, Transit.TransitState state, float progress)
    {
        if (bodyTransform == null)
        {
            bodyTransform = transit.Body.transform;
        }

        switch (state)
        {
        case Transit.TransitState.Entering:
            bodyTransform.position = Vector3.Lerp(transit.StartPosition, transit.EnterPosition, transit.EnterProgress);
            break;

        case Transit.TransitState.InProgress:
            bodyTransform.position = transit.Curve.position(progress);
            break;

        case Transit.TransitState.Exiting:
            bodyTransform.position = Vector3.Lerp(transit.ExitPosition, transit.FinalPosition, transit.ExitProgress);
            break;
        }
    }
Example #23
0
        private void OnConnectionAttemptConcluded(SocketAsyncEventArgs args)
        {
            args.Completed        -= new EventHandler <SocketAsyncEventArgs>(OnConnectEvent_Completed);
            m_ConnectionInProgress = false;

            try
            {
                if (args.SocketError != SocketError.Success)
                {
                    FireConnectedEvent(false, args.SocketError.ToString());
                    return;
                }
            }
            catch (Exception conExc)
            {
                FireConnectedEvent(false, "Unable to connect to server: " + conExc.Message);
                return;
            }

            FireConnectedEvent(true, "Endpoint " + RemoteEndPoint.ToString());

            try
            {
                // send serviceId request
                Log.LogMsg("Sending service ID " + ServiceID.ToString());
                Send(BitConverter.GetBytes(ServiceID), PacketFlags.IsCritical);

                if (!Transit.ListenForDataOnSocket())
                {
                    // ListenForDataOnSocket calls all appropriate kill events
                    KillConnection("Failed to listen on socket.");
                    return;
                }
            }
            catch (Exception con2Exc)
            {
                KillConnection(con2Exc.Message);
            }
        }
Example #24
0
        public IActionResult ShowQWithSelect([FromForm(Name = "wordToSearch")] string word,
                                             [FromForm(Name = "fromTimeToSearch")] DateTime fromTime,
                                             [FromForm(Name = "toTimeToSearch")] DateTime toTime,
                                             [FromForm(Name = "fromVoteSearch")] int fromVote)
        {
            List <Transit>  transitList  = new List <Transit>();
            List <Question> questionList = ds.GetQuestions(word, fromVote, fromTime, toTime);

            foreach (Question que in questionList)
            {
                Transit transit = new Transit();
                transit.Qid             = que.Id;
                transit.Qtitle          = que.Title;
                transit.Qtext           = que.Text;
                transit.Qvote           = que.VoteNumber;
                transit.QsubmissionTime = que.SubmissionTime;
                transitList.Add(transit);
            }
            return(View("ALtListQuestions", transitList));

            return(RedirectToAction("AltListQuestions", transitList));
        }
        private async void saveBtn_Click(object sender, RoutedEventArgs e)
        {
            bool a1 = checkAirport();
            bool a2 = checkTimeTransit();

            bool res = a1 && a2;

            if (res == true)
            {
                Console.WriteLine("ready to post data");

                transitData.flightID    = flightID;
                transitData.transitTime = timeTransit.Text.ToString();

                if (Note.Text == null || Note.Text == "")
                {
                    transitData.transitNote = "không có ghi chú";
                }
                else
                {
                    transitData.transitNote = Note.Text;
                }

                if (mode == (int)transitSign.createTransit)
                {
                    await FlightBusControl.Instance.CreateTransit(transitData);
                }
                else if (mode == (int)transitSign.modifyTransit)
                {
                    await FlightBusControl.Instance.UpdateTransit(transitData);

                    this.DialogResult = true;
                    return;
                }

                this.transitData = new Transit();
                this.resetInformation();
            }
        }
 public bool IsNextTransitPlanned(Transit transit)
 {
     return transits != null && transits.Count > 0 && transits[0] == transit;
 }
Example #27
0
 public async Task <bool> Create(Transit passenger)
 {
     return(await APIHelper <Transit> .Instance.Post(ApiRoutes.Transit.Create, passenger));
 }
Example #28
0
        public void HandleTouch(TouchStatus status, UserInteractionState?userInteractionState = null)
        {
            if (IsCanceled || _effect == null)
            {
                return;
            }

            if (_effect?.IsDisabled ?? true)
            {
                return;
            }

            _effect.HandleTouch(status);
            if (userInteractionState.HasValue)
            {
                _effect.HandleUserInteraction(userInteractionState.Value);
            }

            if (!_effect.NativeAnimation)
            {
                return;
            }

            if (_longTapStarted && !_tapCompleted)
            {
                return;
            }

            var control    = _effect.Control;
            var nativeView = Platform.GetOrCreateRenderer(control)?.NativeView as Widget;

            if (nativeView == null)
            {
                return;
            }

            if (status == TouchStatus.Started)
            {
                var startColor = nativeView.BackgroundColor;
                if (startColor.IsDefault)
                {
                    return;
                }

                var endColor = _effect.NativeAnimationColor.ToNative();;
                if (endColor.IsDefault)
                {
                    startColor = EColor.FromRgba(startColor.R, startColor.G, startColor.B, startColor.A / 2);
                    endColor   = startColor;
                }

                Transit transit = new Transit
                {
                    Repeat   = 1,
                    Duration = .2
                };
                var colorEffect = new ColorEffect(startColor, endColor);
                colorEffect.EffectEnded += (s, e) => { transit?.Dispose(); };
                transit.Objects.Add(nativeView);
                transit.AddEffect(colorEffect);
                transit.Go(.2);
            }
        }
Example #29
0
        public override IResult Parse(object source)
        {
            WorkFlowManagerWebPart workflowManagerWebPart = source as WorkFlowManagerWebPart;

            if (null == workflowManagerWebPart)
            {
                throw new ArgumentException("source is not a WorkFlowManagerWebPart");
            }

            IConfiguration configuration = workflowManagerWebPart.Configuration;

            if (null == configuration)
            {
                throw new ArgumentException("source does not have a configuration");
            }

            WebPartManager Manager = WebPartManager.GetCurrentWebPartManager(workflowManagerWebPart.Page);

            if (configuration.Sections.ContainsKey("flows"))
            {
                WorkFlow.WorkFlow flow = new WorkFlow.WorkFlow();
                flow.Monitor = workflowManagerWebPart.Monitor;
                flow.Title   = "screen flow";
                IConfigurationSection flowsSection = configuration.GetConfigurationSectionReference("flows");
                foreach (IConfigurationElement flowElement in flowsSection.Elements.Values)
                {
                    Job job = new Job();
                    job.Monitor = workflowManagerWebPart.Monitor;
                    job.Title   = flowElement.ConfigKey;
                    if (flowElement.Elements.ContainsKey("conditions"))
                    {
                        foreach (IConfigurationElement conditionElement in flowElement.Elements["conditions"].Elements.Values)
                        {
                            if (flowElement.Elements["conditions"].Attributes.ContainsKey("type"))
                            {
                                ReflectionServices.SetValue(job.Conditions, "Type", flowElement.Elements["conditions"].GetAttributeReference("type").Value.ToString());
                            }
                            if (conditionElement.Attributes.ContainsKey("waitfor") && !("waitfor" == conditionElement.GetAttributeReference("type").Value.ToString()))
                            {
                                throw new InvalidOperationException("Unknown condition type " + conditionElement.GetAttributeReference("type").Value.ToString());
                            }

                            WaitForCondition condition = new WaitForCondition();
                            condition.Monitor = workflowManagerWebPart.Monitor;
                            if (conditionElement.Attributes.ContainsKey("milestone"))
                            {
                                condition.Milestone = conditionElement.GetAttributeReference("milestone").Value.ToString();
                            }
                            if (conditionElement.Attributes.ContainsKey("sender"))
                            {
                                condition.Chronicler = (ReflectionServices.FindControlEx(conditionElement.GetAttributeReference("sender").Value.ToString(), Manager) as IChronicler);
                            }
                            condition.Target = job;
                            job.Conditions.Add(condition);
                            if (conditionElement.Elements.ContainsKey("expression"))
                            {
                                IConfigurationElement expressionElement = conditionElement.GetElementReference("expression");
                                IExpression           expression        = workflowManagerWebPart.ExpressionsManager.Token(expressionElement.GetAttributeReference("type").Value.ToString()) as IExpression;
                                if (null != expression)
                                {
                                    expression.Make(expressionElement, workflowManagerWebPart.ExpressionsManager);
                                    condition.Expression = expression;
                                }
                            }
                        }
                    }

                    if (flowElement.Elements.ContainsKey("transits"))
                    {
                        foreach (IConfigurationElement transitElement in flowElement.GetElementReference("transits").Elements.Values)
                        {
                            if (transitElement.Attributes.ContainsKey("key"))
                            {
                                Transit transit = new Transit();
                                transit.Monitor = workflowManagerWebPart.Monitor;
                                transit.Title   = transitElement.ConfigKey;
                                transit.Key     = transitElement.GetAttributeReference("key").Value.ToString();
                                transit.Storage = workflowManagerWebPart.StatePersistence;
                                if (transitElement.Elements.ContainsKey("expression"))
                                {
                                    IConfigurationElement expressionElement = transitElement.GetElementReference("expression");
                                    IExpression           expression        = workflowManagerWebPart.ExpressionsManager.Token(expressionElement.GetAttributeReference("type").Value.ToString()) as IExpression;
                                    if (null == expression)
                                    {
                                        throw new InvalidOperationException("Token is not an IExpression");
                                    }
                                    expression.Make(expressionElement, workflowManagerWebPart.ExpressionsManager);
                                    transit.Expression = expression;
                                }
                                if (transitElement.Elements.ContainsKey("source"))
                                {
                                    transit.Source = this.CreateTransitPoint(Manager, transitElement.GetElementReference("source"), workflowManagerWebPart.ExpressionsManager);
                                }
                                if (transitElement.Elements.ContainsKey("destination"))
                                {
                                    transit.Destination = this.CreateTransitPoint(Manager, transitElement.GetElementReference("destination"), workflowManagerWebPart.ExpressionsManager);
                                }
                                if (transitElement.Attributes.ContainsKey("persistent"))
                                {
                                    transit.IsPersistent = bool.Parse(transitElement.GetAttributeReference("persistent").Value.ToString());
                                }

                                job.Transits.Add(transit);
                            }
                        }
                    }
                    flow.Jobs.Add(job);
                }
                workflowManagerWebPart.WorkFlows.Add(flow);
            }
            return(null);
        }
Example #30
0
        public void Launch()
        {
            //Calculate launch parameters
            Vector3 lineToLauncher = (launcher.transform.position - transform.position);
            lineToLauncher.y = 0;
            Vector3 ftlDirection = lineToLauncher.normalized;
            float magnitude = lineToLauncher.magnitude;
            float slingshotScaler = Mathf.Min( magnitude / self.MaxDragDistance, 1);
            ftlImpulse *= slingshotScaler;
            ftlDistance *= slingshotScaler;
            ftlDistance += magnitude;
            //Calculate constant slow-down force
            var aveVelocity = ftlImpulse + Game.SPEED_OF_LIGHT / 2;
            ftlTime = ftlDistance/aveVelocity;     //time till we slow "light speed"
            float ftlCounterForce = -ftlImpulse/ftlTime; //constant "drag" force to make that happen

            //Launch in the direction of the launcher
            //state change used to be here, now moved belowss
            rigidbody.AddForce(ftlDirection * ftlImpulse, ForceMode.VelocityChange);
            float timeOfLaunch = Time.fixedTime;

            Transit newState = new Transit(self, ftlCounterForce, timeOfLaunch);
            self.state.ChangeState(newState);
        }
 // Use this for initialization
 void Start()
 {
     p_Transit = GameObject.Find("TrackingSpace").GetComponent <Transit>();
 }
 public void TransitEntered(Transit transit)
 {
     if (IsGoalDefined){
         transits.Remove(transit);
         PlanPathToNextTransitOrGoal();
     }
 }
Example #33
0
        public void HandleTouch(TouchStatus status, TouchInteractionStatus?touchInteractionStatus = null)
        {
            if (IsCanceled || effect == null)
            {
                return;
            }

            if (effect?.IsDisabled ?? true)
            {
                return;
            }

            if (touchInteractionStatus == TouchInteractionStatus.Started)
            {
                effect?.HandleUserInteraction(TouchInteractionStatus.Started);
                touchInteractionStatus = null;
            }

            effect.HandleTouch(status);
            if (touchInteractionStatus.HasValue)
            {
                effect.HandleUserInteraction(touchInteractionStatus.Value);
            }

            if (!effect.NativeAnimation)
            {
                return;
            }

            if (longTapStarted && !tapCompleted)
            {
                return;
            }

            var control = effect.Element;

            if (!(Platform.GetOrCreateRenderer(control)?.NativeView is Widget nativeView))
            {
                return;
            }

            if (status == TouchStatus.Started)
            {
                var startColor = nativeView.BackgroundColor;
                if (startColor.IsDefault)
                {
                    return;
                }

                var endColor = effect.NativeAnimationColor.ToNative();
                if (endColor.IsDefault)
                {
                    startColor = EColor.FromRgba(startColor.R, startColor.G, startColor.B, startColor.A / 2);
                    endColor   = startColor;
                }

                var transit = new Transit
                {
                    Repeat   = 1,
                    Duration = .2
                };
                var colorEffect = new ColorEffect(startColor, endColor);
                colorEffect.EffectEnded += (s, e) => { transit?.Dispose(); };
                transit.Objects.Add(nativeView);
                transit.AddEffect(colorEffect);
                transit.Go(.2);
            }
        }
        public async Task <IHttpActionResult> Get(string originId, string destId, DateTime departureTime)
        {
            using (var client = new HttpClient())
            {
                var response = await client.GetAsync($"https://api.resrobot.se/v2/trip?key=b9c069be-46e8-4d23-a729-573e05222804&originId={originId}&destId={destId}&date={departureTime:yyyy-MM-dd}&time={departureTime:HH:mm}&format=json");

                if (!response.IsSuccessStatusCode)
                {
                    var errorResponse = JObject.Parse(response.Content.ReadAsStringAsync().Result).Value <string>("errorCode");
                    return(BadRequest(errorResponse == "SVC_DATATIME_PERIOD"
                        ? "Din sökning är för långt fram i tiden, var god ändra datum"
                        : "Något gick fel på servern"));
                }

                var content = await response.Content.ReadAsStringAsync();

                var json = JObject.Parse(content).Value <JArray>("Trip");
                if (!json.Any())
                {
                    return(NotFound());
                }
                var trips = new List <Trip>();

                foreach (var item in json)
                {
                    var legs            = item.Value <JObject>("LegList").Value <JArray>("Leg");
                    var jsonOrigin      = legs.First().Value <JObject>("Origin");
                    var jsonDestination = legs.Last().Value <JObject>("Destination");

                    var trip = new Trip
                    {
                        Origin = new Destination
                        {
                            Id          = originId,
                            StationName = jsonOrigin.Value <string>("name"),
                            Latitude    = jsonOrigin.Value <string>("lat"),
                            Longitude   = jsonOrigin.Value <string>("lon")
                        },
                        Destination = new Destination
                        {
                            Id          = destId,
                            StationName = jsonDestination.Value <string>("name"),
                            Latitude    = jsonDestination.Value <string>("lat"),
                            Longitude   = jsonDestination.Value <string>("lon")
                        },
                        Transits      = new List <Transit>(),
                        DepartureTime = DateTime.Parse($"{jsonOrigin.Value<string>("date")} {jsonOrigin.Value<string>("time")}"),
                        ArrivalTime   = DateTime.Parse($"{jsonDestination.Value<string>("date")} {jsonDestination.Value<string>("time")}")
                    };
                    foreach (var leg in legs)
                    {
                        var transit = new Transit();
                        if (leg["Product"] != null)
                        {
                            transit.Transportation = leg["Product"].Value <string>("catOutL");
                            transit.Operator       = leg["Product"].Value <string>("operator") ?? "";
                            transit.Url            = leg["Product"].Value <string>("operatorUrl") ?? "";
                        }
                        else
                        {
                            transit.Transportation = "Walk";
                        }

                        trip.Transits.Add(transit);
                    }
                    try
                    {
                        trip.Forecast = await Forecast(trip.ArrivalTime, trip.Destination);
                    }
                    catch (Exception)
                    {
                        trip.Forecast = null;
                    }
                    trips.Add(trip);
                }
                return(Ok(trips));
            }
        }