Пример #1
0
        public void AnswerController_Index_Post_ShouldReturnAnswerWithInstanceOfDateTimeSet()
        {
            // Arrange
            var data = new Mock <IUowData>();

            data.Setup(d => d.Answers.All()).Returns(AnswersCollection().AsQueryable());

            var claim = new Claim("test", "id-123");

            var identity = new Mock <ClaimsIdentity>();

            identity.Setup(i => i.FindFirst(It.IsAny <string>())).Returns(claim);

            var principal = new Mock <IPrincipal>();

            principal.Setup(p => p.Identity).Returns(identity.Object);

            var context = new Mock <ControllerContext>();

            context.Setup(c => c.HttpContext.User).Returns(principal.Object);

            AnswerController controller = new AnswerController(data.Object)
            {
                ControllerContext = context.Object
            };

            Answer answer = new Answer();

            // Act
            var result = controller.Index(answer, 1, "ThreadTitle") as ViewResult;

            // Assert
            data.Verify(a => a.Answers.Add(It.Is <Answer>(x => x.Published.GetType() == typeof(DateTime))));
        }
Пример #2
0
        public void AnswerController_Index_Post_ShouldRedirectWithCorrectParamThreadTitle(string threadTitle)
        {
            // Arrange
            var data = new Mock <IUowData>();

            data.Setup(d => d.Answers.All()).Returns(AnswersCollection().AsQueryable());

            var claim = new Claim("test", "id-123");

            var identity = new Mock <ClaimsIdentity>();

            identity.Setup(i => i.FindFirst(It.IsAny <string>())).Returns(claim);

            var principal = new Mock <IPrincipal>();

            principal.Setup(p => p.Identity).Returns(identity.Object);

            var context = new Mock <ControllerContext>();

            context.Setup(c => c.HttpContext.User).Returns(principal.Object);

            AnswerController controller = new AnswerController(data.Object)
            {
                ControllerContext = context.Object
            };

            Answer answer = new Answer();

            // Act
            RedirectToRouteResult result = controller.Index(answer, 13, threadTitle) as RedirectToRouteResult;

            // Assert
            Assert.AreEqual(threadTitle, result.RouteValues["title"]);
        }
        public void ShouldGetAnswers()
        {
            var expectedTitle      = "My expected Answers";
            var answers_controller = new AnswerController();

            System.Net.WebRequest  request    = System.Net.WebRequest.Create("http://localhost:49852/api/questions");
            System.Net.WebResponse response   = request.GetResponse();
            System.IO.Stream       datastream = response.GetResponseStream();
            StreamReader           str        = new StreamReader(datastream);
            string read_resp = str.ReadToEnd();

            str.Close();
            response.Close();

            string[] split = read_resp.Split(',');
            var      title = String.Empty;

            foreach (var te in split)
            {
                var fin_string = te.Replace("{", "").Replace("}", "").Replace("]", "").Replace("[", "").
                                 Replace("\"\"", "").Replace("\"", "");
                title += fin_string;
            }
            Assert.AreEqual(title, expectedTitle);
        }
Пример #4
0
        public async Task GetUser_WhenDataIsNull_ShouldReturn_InternalServerError()
        {
            var logger   = Mock.Of <ILogger <AnswerController> >();
            var mediator = new Mock <IMediator>();

            mediator.Setup(x => x.Send(It.IsAny <GetUserQuery>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync((GetUserQuery.UserViewModel)null);

            var controller = new AnswerController(logger, mediator.Object);

            controller.ControllerContext = new ControllerContext
            {
                HttpContext = new DefaultHttpContext()
            };

            var response = await controller.GetUser();

            response.ShouldNotBeNull();
            response.ShouldBeOfType <ObjectResult>();

            var data = response as ObjectResult;

            data.StatusCode.ShouldBe(500);
            data.Value.ShouldBeOfType <ProblemDetails>();

            var details = data.Value as ProblemDetails;

            details.Detail.ShouldBe("Unknown error reading user data");
            details.Title.ShouldBe("Internal Server Error");
            details.Status.ShouldBe(500);
        }
 public void SetUp()
 {
     _fixture               = new Fixture().Customize(new AutoMoqCustomization());
     _queryDispatcherMock   = _fixture.Freeze <Mock <IQueryDispatcher> >();
     _commandDispatcherMock = _fixture.Freeze <Mock <ICommandDispatcher> >();
     _controller            = new AnswerController(_queryDispatcherMock.Object, _commandDispatcherMock.Object, new AnswerViewModelConverter(), new AnswerDtoConverter());
 }
Пример #6
0
        public async Task GetUser_WhenDataIsFound_ShouldReturn_OkSuccess()
        {
            var logger   = Mock.Of <ILogger <AnswerController> >();
            var mediator = new Mock <IMediator>();

            mediator.Setup(x => x.Send(It.IsAny <GetUserQuery>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(new GetUserQuery.UserViewModel {
                Name = "a", Token = "b"
            });

            var controller = new AnswerController(logger, mediator.Object)
            {
                ControllerContext = new ControllerContext {
                    HttpContext = new DefaultHttpContext()
                }
            };

            var response = await controller.GetUser();

            response.ShouldNotBeNull();
            response.ShouldBeOfType <OkObjectResult>();

            var data = response as OkObjectResult;

            data.StatusCode.ShouldBe((int)HttpStatusCode.OK);
            data.Value.ShouldBeOfType <GetUserQuery.UserViewModel>();

            var details = data.Value as GetUserQuery.UserViewModel;

            details.Name.ShouldBe("a");
            details.Token.ShouldBe("b");
        }
Пример #7
0
        public async Task GetUser_WhenAppSettingsIsMissing_ShouldReturn_InternalServerError()
        {
            var logger   = Mock.Of <ILogger <AnswerController> >();
            var mediator = new Mock <IMediator>();

            mediator.Setup(x => x.Send(It.IsAny <GetUserQuery>(), It.IsAny <CancellationToken>()))
            .ThrowsAsync(new ApplicationSettingsInvalidException("missing"));


            var controller = new AnswerController(logger, mediator.Object)
            {
                ControllerContext = new ControllerContext {
                    HttpContext = new DefaultHttpContext()
                }
            };

            var response = await controller.GetUser();

            response.ShouldNotBeNull();
            response.ShouldBeOfType <ObjectResult>();

            var data = response as ObjectResult;

            data.StatusCode.ShouldBe(500);
            data.Value.ShouldBeOfType <ProblemDetails>();

            var details = data.Value as ProblemDetails;

            details.Detail.ShouldBe("missing");
            details.Title.ShouldBe("Server configuration invalid");
            details.Status.ShouldBe(500);
        }
Пример #8
0
        public void Answer_MoodIdNotFound_Returns404()
        {
            var id     = Guid.NewGuid();
            var moodId = 5;
            var survey = new Survey()
            {
                Id = id
            };
            var moods = new List <Models.Mood>()
            {
                new Models.Mood()
                {
                    Id = 10
                }, new Models.Mood()
                {
                    Id = 20
                }
            };
            var details = "Test details";

            var surveysMock = new Mock <ISurveyService>();

            surveysMock.Setup(s => s.FindAsync(id.ToString())).ReturnsAsync(survey);

            var dbMock       = new Mock <IApplicationDBContext>();
            var moodDataMock = new Mock <DbSet <Models.Mood> >().SetupData(moods);

            dbMock.Setup(db => db.Moods).Returns(moodDataMock.Object);

            var subject = new AnswerController(dbMock.Object, surveysMock.Object, Mock.Of <IDateTimeService>(), Mock.Of <ISecurity>());

            var result = subject.Create(id.ToString(), moodId, details).Result;

            Assert.IsInstanceOfType(result, typeof(HttpNotFoundResult));
        }
Пример #9
0
        public void Results_WrongUser_Returns403()
        {
            var id     = Guid.NewGuid();
            var survey = new Survey()
            {
                Id = id, Owner = new ApplicationUser()
                {
                    UserName = "******"
                }
            };

            var surveysMock = new Mock <ISurveyService>();

            surveysMock.Setup(s => s.FindAsync(id.ToString())).ReturnsAsync(survey);

            var dbMock = new Mock <IApplicationDBContext>();

            dbMock.SetupGet(db => db.Answers).Returns(new Mock <DbSet <Answer> >().SetupData().Object);

            var securityMock = new Mock <ISecurity>();

            securityMock.SetupGet(s => s.UserName).Returns("Peter");
            securityMock.SetupGet(s => s.IsAuthenticated).Returns(true);

            var subject = new AnswerController(dbMock.Object, surveysMock.Object, Mock.Of <IDateTimeService>(), securityMock.Object);

            var result = subject.Results(id.ToString()).Result;

            Assert.IsInstanceOfType(result, typeof(HttpStatusCodeResult));
            Assert.AreEqual(403, (result as HttpStatusCodeResult).StatusCode);
        }
Пример #10
0
 public void RestartGame()
 {
     SceneManager.LoadScene(startGameLevel);
     AnswerController.ResumeGame();
     DistanceManager.pointsPerSecondsLast          = 0;
     AnswerCorrectManager.answerCorrectCountStatic = 0;
 }
Пример #11
0
        public void AnswerController_Index_Post_ShouldCallDataSaveChanges()
        {
            // Arrange
            var data = new Mock <IUowData>();

            data.Setup(d => d.Answers.All()).Returns(AnswersCollection().AsQueryable());

            var claim = new Claim("test", "id-123");

            var identity = new Mock <ClaimsIdentity>();

            identity.Setup(i => i.FindFirst(It.IsAny <string>())).Returns(claim);

            var principal = new Mock <IPrincipal>();

            principal.Setup(p => p.Identity).Returns(identity.Object);

            var context = new Mock <ControllerContext>();

            context.Setup(c => c.HttpContext.User).Returns(principal.Object);

            AnswerController controller = new AnswerController(data.Object)
            {
                ControllerContext = context.Object
            };

            Answer answer = new Answer();

            // Act
            var result = controller.Index(answer, 1, "ThreadTitle") as ViewResult;

            // Assert
            data.Verify(d => d.SaveChanges(), Times.Once);
        }
Пример #12
0
        protected void AnswerSubmitButton_OnClick(object sender, EventArgs e)
        {
            var logginedUser = HttpContext.Current.User.Identity;

            if (logginedUser.IsAuthenticated) // only logedin users can answer to question
            {
                int questionId;

                if (int.TryParse(Request.QueryString["QuestionID"], out questionId) && questionId > 0)
                {
                    using (var control = new AnswerController())
                    {
                        control.AnswerToQuestion(questionId, AnswerBodyTextBox.Text);
                    }

                    AnswerBodyTextBox.Text = "";
                    QuestionDetailFormView.DataBind();
                    AnswersList.DataBind();
                }
                else
                {
                    ErrorMessage.InnerText = "Please try again later";
                    ErrorDiv.Visible       = true;
                }
            }
            else
            {
                var currentUrl = HttpUtility.UrlEncode(Request.Url.PathAndQuery);
                Response.Redirect($"~/Login.aspx?ReturnUrl={currentUrl}");
            }
        }
Пример #13
0
        public void Results_IdOK_ReturnsViewWithViewModel()
        {
            var id     = Guid.NewGuid();
            var survey = new Survey()
            {
                Id = id, Owner = new ApplicationUser()
                {
                    UserName = "******"
                }
            };
            var moods = new[] { new Models.Mood()
                                {
                                    Id = 1
                                }, new Models.Mood()
                                {
                                    Id = 2
                                } };
            var answer1 = new Answer()
            {
                MoodId = 1, SurveyId = id
            };
            var answer2 = new Answer()
            {
                MoodId = 2, SurveyId = id
            };
            var answers = new List <Answer>()
            {
                answer1, answer2
            };

            var surveysMock = new Mock <ISurveyService>();

            surveysMock.Setup(s => s.FindAsync(id.ToString())).ReturnsAsync(survey);

            var dbMock         = new Mock <IApplicationDBContext>();
            var moodDataMock   = new Mock <DbSet <Models.Mood> >().SetupData(moods);
            var answerDataMock = new Mock <DbSet <Answer> >().SetupData(answers);;

            dbMock.Setup(db => db.Moods).Returns(moodDataMock.Object);
            dbMock.Setup(db => db.Answers).Returns(answerDataMock.Object);

            var securityMock = new Mock <ISecurity>();

            securityMock.SetupGet(s => s.UserName).Returns("Tyler");
            securityMock.SetupGet(s => s.IsAuthenticated).Returns(true);

            var subject = new AnswerController(dbMock.Object, surveysMock.Object, Mock.Of <IDateTimeService>(), securityMock.Object);

            var result = subject.Results(id.ToString()).Result;

            Assert.IsInstanceOfType(result, typeof(ViewResult));
            var model = (result as ViewResult).Model as ResultsViewModel;

            Assert.IsNotNull(model);
            Assert.AreSame(survey, model.Survey);
            Assert.AreEqual(2, model.Answers.Count());
            Assert.AreSame(answer1, model.Answers.ToList()[0]);
            Assert.AreSame(answer2, model.Answers.ToList()[1]);
        }
Пример #14
0
 protected void Train()
 {
     if (answerControlle == null)
     {
         answerControlle = new AnswerController(this.store);
     }
     this.NavigationController.PushViewController(answerControlle, true);
 }
        public void ShouldGetAnswers()
        {
            var expectedTitle      = "My expected Answers";
            var answers_controller = new AnswerController();
            var result             = (AnswerViewModel)answers_controller.Index().ViewData.Model;

            Assert.That(result.AnswerTitle, Is.EqualTo(expectedTitle));
        }
        public void ShouldGetAnswer_Content()
        {
            var expected_answer = "Cuba";
            var controller      = new AnswerController();

            var result = (AnswerViewModel)controller.Index().ViewData.Model;

            Assert.That(result.AnswerText, Is.EqualTo(expected_answer));
        }
Пример #17
0
        public void SetUp()
        {
            _answerService    = new Mock <ICrudInterface <AnswerDto> >();
            _answerController = new AnswerController(_answerService.Object);

            _answer = new AnswerDto {
                Id = "answer1", AnswerText = "Hello", IsCorrect = true, QuestionId = "question1"
            };
        }
Пример #18
0
        public void GetAllAnswers_ShouldReturnAllAnswers()
        {
            var testAnswer = GetTestAnswer();
            var controller = new AnswerController();

            var result = controller.GetAnswers().ToList <Answer>();

            Assert.IsNotNull(result);
        }
Пример #19
0
        private void SetupController()
        {
            var request = new Mock <HttpRequestBase>();

            _controller = new AnswerController(_unitOfWork.Object);
            _user       = new Mock <IPrincipal>();

            _controller.MockContext(request, _user);
            _identity = _user.MockIdentity(_answer1.AppUserId);
        }
Пример #20
0
    public void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.tag == "BoxTeste")
        {
            AnswerController.PauseGame();
            GameObject postDeath = GameObject.Instantiate(postDeathPrefabs);

            try
            {
                string queryVerify = $"SELECT * FROM [Player] WHERE [Nickname] = '{MainMenu.nickname}'";

                var verifyNickname = myDB.ExecuteQuery(queryVerify);

                while (verifyNickname.Read())
                {
                    verifyNicks.Add(verifyNickname.GetString(1));
                }

                verifyNicks.Count.ToString();

                if (verifyNicks.Count.Equals(0))
                {
                    Debug.Log("Inserir dados desse Nickname: " + verifyNicks.Count);

                    string query =
                        $"INSERT INTO [Player](ID_Player, Nickname, Distancia_Percorrida, Respostas_Corretas) VALUES(null, '{MainMenu.nickname}', {DistanceManager.pointsPerSecondsLast}, {AnswerCorrectManager.answerCorrectCountStatic})";

                    myDB.ExecuteQuery(query);

                    Debug.Log("DISTANCIA: " + DistanceManager.pointsPerSecondsLast);
                    Debug.Log("PERGUNTAS CORRETAS: " + AnswerCorrectManager.answerCorrectCountStatic);
                    Debug.Log("NICKNAME: " + MainMenu.nickname);
                }
                else
                {
                    Debug.Log("Fazer Update desse nickname: " + verifyNicks.Count);

                    string queryUpdate =
                        $"UPDATE [Player] SET [Distancia_Percorrida] = {DistanceManager.pointsPerSecondsLast}, [Respostas_Corretas] = {AnswerCorrectManager.answerCorrectCountStatic} WHERE [Nickname] = '{MainMenu.nickname}'";

                    myDB.ExecuteQuery(queryUpdate);

                    Debug.Log("DISTANCIA: " + DistanceManager.pointsPerSecondsLast);
                    Debug.Log("PERGUNTAS CORRETAS: " + AnswerCorrectManager.answerCorrectCountStatic);
                    Debug.Log("NICKNAME: " + MainMenu.nickname);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
    }
Пример #21
0
        public void Setup()
        {
            _context            = new iKnowContext();
            _contextAfterAction = new iKnowContext();
            _controller         = new AnswerController(new UnitOfWork(new iKnowContext()));

            _currentUser = new Mock <IPrincipal>();
            _controller.MockContext(new Mock <HttpRequestBase>(), _currentUser);

            _firstUserInDb = _context.Users.First();
            _currentUser.MockIdentity(_firstUserInDb.Id);
        }
Пример #22
0
        protected void AcceptAnswer_OnClick(object sender, EventArgs e)
        {
            var linkButton = (LinkButton)sender;
            var answerId   = int.Parse(linkButton.CommandArgument);

            using (var control = new AnswerController())
            {
                control.SetAcceptedAnswer(answerId);
            }

            AnswersList.DataBind();
        }
Пример #23
0
    // Use this for initialization
    void Start()
    {
        AnswerController = new AnswerController(AnswerGroupHelper.instance.AnswerGroups[0]);

        ShakingController.OnShaked += () =>
        {
            if (isLockShowActive)
            {
                return;
            }
            GetAnswer();
        };
    }
Пример #24
0
        public void Edit_IdInvalid_Returns404()
        {
            var mockAnswers = new Mock <DbSet <Answer> >().SetupData();
            var mockDb      = new Mock <IApplicationDBContext>();

            mockDb.SetupGet(d => d.Answers).Returns(mockAnswers.Object);

            var subject = new AnswerController(mockDb.Object, Mock.Of <ISurveyService>(), Mock.Of <IDateTimeService>(), Mock.Of <ISecurity>());

            var result = subject.Edit(3, null).Result;

            Assert.IsInstanceOfType(result, typeof(HttpNotFoundResult));
        }
Пример #25
0
        public void AnswerController_Index_ShouldReturnCorrectPartialView()
        {
            // Arrange
            var data = new Mock <IUowData>();

            AnswerController controller = new AnswerController(data.Object);

            // Act
            var result = controller.Index() as PartialViewResult;

            // Assert
            Assert.AreEqual("_Answer", result.ViewName);
        }
Пример #26
0
    private IEnumerator TestQuestions2()
    {
        yield return(new WaitForSeconds(0.01f));

        QuestionBoardStorer.Instance.QuestionBoardController.InitInAn();
        yield return(new WaitForSeconds(1f));

        q = QuestionGenerator.Instance.GetNew();
        QuestionBoardStorer.Instance.QuestionBoardController.SetQuestion(q);
        acUp   = AnswersFactory.Instance.CreateUp(q.correctAnswerType, q.correctAnswerContent);
        acDown = AnswersFactory.Instance.CreateDown(q.incorrectAnswerType, q.incorrectAnswerContent);
        StartCoroutine(TestQuestions3());
    }
Пример #27
0
        public void Answer_IdsOK_CreatesAnswerAndReturnsModel()
        {
            var id     = Guid.NewGuid();
            var moodId = 10;
            var survey = new Survey()
            {
                Id = id
            };
            var moods = new List <Models.Mood>()
            {
                new Models.Mood()
                {
                    Id = moodId
                }, new Models.Mood()
                {
                    Id = 20
                }
            };
            var time    = DateTime.Now;
            var details = "Test details";

            var timeMock = new Mock <IDateTimeService>();

            timeMock.Setup(t => t.Now()).Returns(time);

            var surveysMock = new Mock <ISurveyService>();

            surveysMock.Setup(s => s.FindAsync(id.ToString())).ReturnsAsync(survey);

            var dbMock          = new Mock <IApplicationDBContext>();
            var moodDataMock    = new Mock <DbSet <Models.Mood> >().SetupData(moods);
            var answersDataMock = new Mock <DbSet <Answer> >();

            dbMock.Setup(db => db.Moods).Returns(moodDataMock.Object);
            dbMock.Setup(db => db.Answers).Returns(answersDataMock.Object);

            var subject = new AnswerController(dbMock.Object, surveysMock.Object, timeMock.Object, Mock.Of <ISecurity>());

            var result = subject.Create(id.ToString(), moodId, details).Result;

            Assert.IsInstanceOfType(result, typeof(JsonResult));
            Assert.IsInstanceOfType((result as JsonResult).Data, typeof(Answer));
            var answer = (result as JsonResult).Data as Answer;

            Assert.AreSame(survey, answer.Survey);
            Assert.AreSame(moods[0], answer.Mood);
            Assert.AreEqual(time, answer.Time);

            answersDataMock.Verify(d => d.Add(It.Is <Answer>(a => a.Mood == moods[0] && a.Survey == survey && a.Time == time && a.Details == details)));
            dbMock.Verify(db => db.SaveChangesAsync());
        }
Пример #28
0
        public void AnswerController_Index_Post_ShouldReturnBadRequestWhenIdIsNull()
        {
            // Arrange
            var data = new Mock <IUowData>();

            AnswerController controller = new AnswerController(data.Object);
            Answer           answer     = new Answer();

            // Act
            var result = controller.Index(answer, null, "ThreadTitle") as HttpStatusCodeResult;

            // Assert
            Assert.AreEqual(400, result.StatusCode);
        }
Пример #29
0
        public AnswerControllerTests()
        {
            _dataAccessMock         = new Mock <IQuizDataAccess <DataEntity.Answer> >();
            _topicRepositoryMock    = new Mock <ITopicRepository>();
            _questionRepositoryMock = new Mock <IQuestionRepository>();
            _answerRepository       = new Mock <IAnswerRepository>();


            _quizManager = new QuizManager.QuizManager(
                _topicRepositoryMock.Object,
                _questionRepositoryMock.Object,
                _answerRepository.Object);

            _answerController = new AnswerController(_quizManager);
        }
Пример #30
0
        public void Results_IdNotFound_Returns404()
        {
            var id = Guid.NewGuid();

            var surveysMock = new Mock <ISurveyService>();

            surveysMock.Setup(s => s.FindAsync(id.ToString())).ReturnsAsync((Survey)null);

            var dbMock = new Mock <IApplicationDBContext>();

            var subject = new AnswerController(dbMock.Object, surveysMock.Object, Mock.Of <IDateTimeService>(), Mock.Of <ISecurity>());

            var result = subject.Results(id.ToString()).Result;

            Assert.IsInstanceOfType(result, typeof(HttpNotFoundResult));
        }
Пример #31
0
    void Update()
    {
        //if (manager != null && manager.IsInteractionInited() && !manager.isDisableCursor())
        //DebugGUI.guiText.text = newCursorPos.ToString();
        if (manager.IsSceneReady())
        {

            //if (Kmanager == null)
            //    Kmanager = KinectManager.Instance;

            //if (Kmanager.IsUserDetected())
            //{

            Idle_Timer = 0;
            Vector3 screenNormalPos = Vector3.zero;
            Vector3 screenPixelPos = Vector3.zero;
            screenNormalPos = isLeftHandDrag ? manager.GetLeftHandScreenPos() : manager.GetRightHandScreenPos();

            FirstHandposZ = screenNormalPos.z;
            screenNormalPos.z = -2.5f;
            // convert the normalized screen pos to 3D-world pos
            screenPixelPos.x = (int)(screenNormalPos.x * Camera.main.pixelWidth);
            screenPixelPos.y = (int)(screenNormalPos.y * Camera.main.pixelHeight);
            // World Cursor Position
            Vector3 newCursorPos = Camera.main.ScreenToWorldPoint(screenPixelPos);
            newCursorPos.z = -2.5f;
            // Smoothing moving linear average
            newCursorPos = ExponentialWeightedAvg(newCursorPos);
            newCursorPos = Vector3.Lerp(handCursor.transform.position, newCursorPos, dragSpeed * Time.deltaTime);

            if (newCursorPos != Vector3.zero)
            {
                // Check for Collision
                //     Hitctr = 0;
                //foreach (GameObject Iobj in ClickableObjects)
                //{
                //    if ((EName == Iobj.name) && (Iobj.name.IndexOf("icon") < 0))
                //        Iobj.transform.localScale = ClickableObjsVectors[Hitctr];
                //    Hitctr++;
                //}

                Ray rayCenter = Camera.main.ScreenPointToRay(screenPixelPos);
                RaycastHit hit;

                Debug.DrawRay(rayCenter.origin, rayCenter.direction * 1000, Color.green);

        //                if (xButton != null)
        //                    xButton.CursorOver("asdf");
                // Revised
                ClickTimeDiff = 0;

                if (Physics.Raycast(rayCenter, out hit))
                {
                    isclicking = false;

                    //if (hit.collider.name == "next" || hit.collider.name == "skip" || hit.collider.name == "play" || hit.collider.name == "modaldimNext" || hit.collider.name == "play_again" || hit.collider.name == "exit" || hit.collider.name == "manila" || hit.collider.name == "bohol" || hit.collider.name == "cagayan")
        //                    if (hit.collider)
                    if(hit.collider)
                        print(hit.collider.name);

                    if (hit.collider.gameObject.GetComponent<AnswerController>())
                    {
                        EName = hit.collider.name;
                        GameObject obj = hit.collider.gameObject;
                        xButton = obj.GetComponent<AnswerController>();
                        xButton.CursorOver(EName);
                        //modalDim = obj.transform.parent.Find(hit.collider.name).gameObject;
                        //xButton = obj.transform.parent.Find(hit.collider.name).gameObject.GetComponent<prod_buttons>();
        //                        xButton.sizeUp();

                        hitPointPos = obj.renderer.bounds.center;
                        hitPointPos.z = -2.5f;

                        hitPointPos = hit.collider.gameObject.transform.position;
                        //if (obj.name.IndexOf("icon") < 0)
                        //        obj.transform.localScale *= 1.2f;

                        float tmpshoulder_hand_diff = isLeftHandDrag ? JointDistance(Kmanager.GetJointPosition(manager.GetUserID(), (int)KinectWrapper.NuiSkeletonPositionIndex.ShoulderLeft), Kmanager.GetJointPosition(manager.GetUserID(), (int)KinectWrapper.NuiSkeletonPositionIndex.HandLeft)) : JointDistance(Kmanager.GetJointPosition(manager.GetUserID(), (int)KinectWrapper.NuiSkeletonPositionIndex.ShoulderRight), Kmanager.GetJointPosition(manager.GetUserID(), (int)KinectWrapper.NuiSkeletonPositionIndex.HandRight));

                        if (tmpshoulder_hand_diff < shoulder_hand_diff1)
                            shoulder_hand_diff1 = tmpshoulder_hand_diff;

                        if (FirstHandposZ < SaveFirstDetectedHandPosZ)
                            SaveFirstDetectedHandPosZ = FirstHandposZ;

                        if (!ObjisHit)
                        {
                            ClickTimer1 = Time.time;
                            icon_hit = false;
                            shoulder_hand_diff1 = isLeftHandDrag ? JointDistance(Kmanager.GetJointPosition(manager.GetUserID(), (int)KinectWrapper.NuiSkeletonPositionIndex.ShoulderLeft), Kmanager.GetJointPosition(manager.GetUserID(), (int)KinectWrapper.NuiSkeletonPositionIndex.HandLeft)) : JointDistance(Kmanager.GetJointPosition(manager.GetUserID(), (int)KinectWrapper.NuiSkeletonPositionIndex.ShoulderRight), Kmanager.GetJointPosition(manager.GetUserID(), (int)KinectWrapper.NuiSkeletonPositionIndex.HandRight));
                            SaveFirstDetectedHandPosZ = FirstHandposZ;
                            //anim.Play("RightHandHover");
                            hitObject = obj;

                            if (obj.name.IndexOf("icon") >= 0)
                            {
                                icon_hit = true;
                                isgrip = false;
                            }
                            click_once = false;
                            ObjisHit = true;
                        }
                        //else

                        ClickTimer2 = Time.time;

                        ClickTimeDiff = ClickTimer2 - ClickTimer1;

                    }
                    else {
                        FindObjectOfType<AnswerController>().CursorOver("shrink down");
                    }
        //                    else if (hit.collider.name == "paper" || hit.collider.name == "modal_dialog")
        //                    {
        //                        ObjisHit = false;
        //
        //                        EName = hit.collider.name;
        //                        GameObject obj = hit.collider.gameObject;
        //                        modalDim = obj.transform.parent.Find(hit.collider.name).gameObject;
        //                        hitPointPos = hit.collider.gameObject.transform.position;
        //                        if (obj.transform.parent.Find("modaldimNext") != null)
        //                        {
        //                            EName = "modaldimNext";
        //                            //DebugGUI.guiText.text = "Modal Next";
        //                        }
        //                        else if (obj.transform.parent.Find("next") != null)
        //                        {
        //                            xButton = obj.transform.parent.Find("next").gameObject;
        //                            EName = "next";
        //                        }
        //                        else if (obj.transform.parent.Find("play") != null)
        //                        {
        //                            xButton = obj.transform.parent.Find("play").gameObject;
        //                            EName = "next";
        //                        }
        //                        icon_hit = true;
        //                    }

                    // 2 Type of checking if press was made
                    // 1.) get the before and after z poistion of the hands to check if press was made
                    HandposDiffZ = FirstHandposZ - SaveFirstDetectedHandPosZ;
                    // 2.) Get the joint distance of hands vs shoulder to check if press was made
                    shoulder_hand_diff2 = isLeftHandDrag ? JointDistance(Kmanager.GetJointPosition(manager.GetUserID(), (int)KinectWrapper.NuiSkeletonPositionIndex.ShoulderLeft), Kmanager.GetJointPosition(manager.GetUserID(), (int)KinectWrapper.NuiSkeletonPositionIndex.HandLeft)) : JointDistance(Kmanager.GetJointPosition(manager.GetUserID(), (int)KinectWrapper.NuiSkeletonPositionIndex.ShoulderRight), Kmanager.GetJointPosition(manager.GetUserID(), (int)KinectWrapper.NuiSkeletonPositionIndex.HandRight));
                    //if (HandposDiffZ > 0.1f)
                    //    isclicking = true;
                    //Vector3 v3 = (v2 - v1).magnitude;

                }
                else
                {

                    if (ObjisHit)
                    {

                        ObjisHit = false;
                        click_once = false;
                    }

                }
            }
            else
            {
                isPressed = false;
                //newCursorPos = Vector3.zero;
            }
            // Revised
            ClickandTime = false;
            if (ClickTimeDiff >= 1.5f)
                ClickandTime = true;
            //DebugGUI.guiText.text = " DIFF : " + HandposDiffZ.ToString();
            if (manager.IsLeftHandPrimary())
            {
                //  Idle_Timer = 0;
                isLeftHandDrag = true;
                // if the left hand is primary, check for left hand grip
                if (manager.GetLastLeftHandEvent() == InteractionWrapper.InteractionHandEventType.Grip)
                {
                    //DebugGUI.guiText.text = "X Pos : " + (x_pos - screenNormalPos.x).ToString();
                    if ((icon_hit) && (ObjisHit))
                    {
                        startTime = Time.time;
                        anim.Play("LeftHandGrip");
                        isPressed = false;

                        if (!isgrip)
                        {
                            x_pos = screenNormalPos.x;
                            isgrip = true;
                        }

                        if (x_pos - screenNormalPos.x > 0.3f)
                        { // Swipe left

                            //DoEvents("arrow_right", hitPointPos);
                            isgrip = false;
                        }
                        else if (x_pos - screenNormalPos.x < -0.3f)
                        { // Swipe right

                            //DoEvents("arrow_left", hitPointPos);
                            isgrip = false;
                        }

                    }
                    else
                    {
                        isgrip = false;
                        isPressed = false;
                        anim.Play("LeftHandIdle");
                    }
                }
                // Detect Click gesture . Get all possible gesture.
                //else if (((((HandposDiffZ >= Click_Sensitive) || ((shoulder_hand_diff2 - shoulder_hand_diff1) >= 0.03f)) && ClickTimeDiff > 0.5f) || ClickandTime) && (!icon_hit))
                else if (((HandposDiffZ >= Click_Sensitive) || ((shoulder_hand_diff2 - shoulder_hand_diff1) >= 0.12f)) && (!icon_hit))
                {

                    isgrip = false;
                    if (ObjisHit)
                    {
                        //ObjisHit = false;
                        if (!click_once)
                        {
                            click_once = true;
                            anim.Play("LeftHandClick");
                            DebugGUI.guiText.text = "Collider : " + EName;
                            isPressed = true;
                            ClickandTime = false;
                        }
                        else
                        {
                            if (anim.GetCurrentAnimatorStateInfo(0).normalizedTime > 1 && !anim.IsInTransition(0) && click_once)
                            {
                                //Debug.Log("Done With animation");
                                DoEvents(EName, hitPointPos);
                                anim.Play("LeftHandIdle");
                                isPressed = false;
                                HandposDiffZ = 0;
                                ObjisHit = false;
                                click_once = false;

                            }
                        }
                    }
                    else
                    {
                        if (ObjisHit)
                        {
                            anim.Play("LeftHandIdle");
                            DebugGUI.guiText.text = "HOVER : ";
                        }
                    }
                }
                else
                {
                    isgrip = false;
                    isPressed = false;
                    anim.Play("LeftHandIdle");
                }
            }
            else if (manager.IsRightHandPrimary())
            {

                //  Idle_Timer = 0;
                isLeftHandDrag = false;
                // if the right hand is primary, check for right hand grip
                if (manager.GetLastRightHandEvent() == InteractionWrapper.InteractionHandEventType.Grip)
                {
                    DebugGUI.guiText.text = "GRIP";
                    if (icon_hit)
                    {
                        startTime = Time.time;
                        anim.Play("RightHandGrip");
                        isPressed = false;

                        if (!isgrip)
                        {
                            x_pos = screenNormalPos.x;
                            isgrip = true;
                        }

                        if (x_pos - screenNormalPos.x > 0.3f)
                        { // Swipe left
                            //DoEvents(EName, hitPointPos);
                            isgrip = false;
                        }

                    }
                    //else
                    //{
                    //    isgrip = false;
                    //    isPressed = false;
                    //    anim.Play("RightHandIdle");
                    //}
                }
                //else if (((((HandposDiffZ >= Click_Sensitive) || ((shoulder_hand_diff2 - shoulder_hand_diff1) >= 0.03f)) && ClickTimeDiff > 0.5f) || ClickandTime) && (!icon_hit))
                else if (((HandposDiffZ >= Click_Sensitive) || ((shoulder_hand_diff2 - shoulder_hand_diff1) >= 0.12f)) && (!icon_hit))
                {

                    isgrip = false;
                    if (ObjisHit)
                    {
                        //ObjisHit = false;
                        if (!click_once)
                        {
                            isPressed = true;
                            handCursor.transform.position = hitObject.renderer.bounds.center;
                            DoEvents(EName, hitPointPos);
                            anim.Play("RightHandClick");
                            click_once = true;
                            //click_once = true;
                            //anim.Play("RightHandClick");
                            //DebugGUI.guiText.text = "Collider : " + EName;
                            //isPressed = true;
                            //ClickandTime = false;
                        }
                        else
                        {
                            if (anim.GetCurrentAnimatorStateInfo(0).normalizedTime > 1 && !anim.IsInTransition(0) && click_once)
                            {
                                //Debug.Log("Done With animation");
                                anim.Play("RightHandIdle");
                                isPressed = false;
                                if (ObjisHit)
                                {

                                    ObjisHit = false;
                                    click_once = false;
                                }
                                //DoEvents(EName, hitPointPos);
                                //anim.Play("RightHandIdle");
                                //isPressed = false;
                                //HandposDiffZ = 0;
                                //ObjisHit = false;
                                //click_once = false;

                            }
                        }
                    }
                    else
                    {
                        if (ObjisHit)
                        {
                            anim.Play("RightHandIdle");
                            DebugGUI.guiText.text = "HOVER : ";
                        }
                    }
                    //else
                    //{
                    //    //if (!isPressed)
                    //    //{
                    //        isPressed = false;
                    //        anim.Play("RightHandIdle");
                    //    //}
                    //}

                }
                else
                {
                    if (!ObjisHit)
                    {
                        isPressed = false;
                        anim.Play("RightHandIdle");
                    }
                    else
                        anim.Play("RightHandIdle");
                    isgrip = false;

                }

            }
            else
            {
                //Reset everything to original size
                isgrip = false;
                Hitctr = 0;
                foreach (GameObject obj in ClickableObjects)
                {
                    if ((EName == obj.name) && (obj.name.IndexOf("icon") < 0))
                        obj.transform.localScale = ClickableObjsVectors[Hitctr];
                    Hitctr++;
                }
                anim.Play("RightHandIdle");
                isPressed = false;

            }

            //if (!isPressed)
            handCursor.transform.position = newCursorPos;

        }
        else
        {
            if (manager == null)
                manager = InteractionManager.Instance;

        }
    }
Пример #32
0
 protected void Train()
 {
     if (answerControlle == null)
         answerControlle = new AnswerController (this.store);
     this.NavigationController.PushViewController (answerControlle, true);
 }