Example #1
0
	void DoIdle(){

		if (substate == SubState.Init) {

			gameObject.SetActive(true);
			isJump = false;
			substate = SubState.Active;
		}

		if (substate == SubState.Active) {
			if(!ball)
				ball = GameManager.instance.ball;
			transform.rotation = Quaternion.RotateTowards(transform.rotation, ball.transform.rotation* Quaternion.Euler(new Vector3(0,180,0)), Time.deltaTime * 100f);

			if(GameState.instance.isFlyBall){
				substate = SubState.Deactive;
			}
		}

		if (substate == SubState.Deactive) {
			substate = SubState.Finish;

		}

		if (substate == SubState.Finish) {
			substate = SubState.Init;
			aiState = AIState.Jockey;
		}
	}
Example #2
0
	void DoIdle(){
		
		if (substate == SubState.Init) {
			gameObject.SetActive(true);
		
			substate = SubState.Active;
		}
		
		if (substate == SubState.Active) {
			if(GameState.instance.isAiming){
				GameState.instance.isDisableFlick = true;
				substate = SubState.Deactive;
			}
		}
		
		if (substate == SubState.Deactive) {
			substate = SubState.Finish;
			
		}
		
		if (substate == SubState.Finish) {
			substate = SubState.Init;
			aiState = AIState.Shoot;
		}
	}
 public void ChangeState( SubState newState )
 {
     if ( m_CurrentSubState != newState ){
         for ( int i = 0; i < m_AtmosphereProperties.Length; i++ ){
             m_AtmosphereProperties[i].hasChanged = true;
         }
     }
     m_CurrentSubState = newState;
 }
	public static int LoadScene( string filePath, AGF_LevelLoader.LoadSceneMode mode = AGF_LevelLoader.LoadSceneMode.All, string overrideUserDataHomeFolder = "" ){
		if(GameObject.Find("Directional Light"))
			DestroyImmediate(GameObject.Find("Directional Light"));

		int returnCode = AGF_ReturnCode.Success;
		
		m_LoadSceneMode = mode;
		
		// Get the position of the integration window.
		Rect integrationWindowRect = AGF_IntegrationWindow.window.position;
		
		AGF_EditorSceneLoader window = GetWindowWithRect<AGF_EditorSceneLoader>( new Rect( integrationWindowRect.x + integrationWindowRect.width/2.0f, integrationWindowRect.y + integrationWindowRect.height/2.0f, 1.0f, 1.0f ) );
		window.position = new Rect( integrationWindowRect.x + integrationWindowRect.width/2.0f, integrationWindowRect.y + integrationWindowRect.height/2.0f, 1.0f, 1.0f );
		
		// Check that the integration prefab has all necessary components.
		if ( GameObject.Find ("AGF_LevelLoader") == null ||
		    GameObject.Find ("EventHandler") == null ||
		    GameObject.Find ("AGF_LevelLoader") == null ||
		    GameObject.Find ("AGF_AtmosphereManager") == null ||
		    GameObject.Find ("AGF_TileListManager") == null ||
		    GameObject.Find ("AGF_TerrainManager") == null ||
		    GameObject.Find ("AGF_GibManager") == null ||
		    GameObject.Find ("AGF_GridManager") == null ){
			window.CloseWindow();
			return AGF_ReturnCode.AGFIntegrationPrefabComponentMissing;
		}
		
		m_LevelLoader = GameObject.Find ("AGF_LevelLoader").GetComponent<AGF_LevelLoader>();
		
		// step 2: Init all gameobjects. (Most of these will simply call the Start() methods of the given object.)
		GameObject.Find ("EventHandler").GetComponent<EventHandler>().EditorInit();
		GameObject.Find ("AGF_LevelLoader").GetComponent<AGF_LevelLoader>().EditorInit();
		GameObject.Find ("AGF_AtmosphereManager").GetComponent<AGF_AtmosphereManager>().EditorInit();
		GameObject.Find ("AGF_TileListManager").GetComponent<AGF_TileListManager>().EditorInit();
		GameObject.Find ("AGF_TerrainManager").GetComponent<AGF_TerrainManager>().EditorInit();
		GameObject.Find ("AGF_GibManager").GetComponent<AGF_GibManager>().EditorInit();
		GameObject.Find ("AGF_GridManager").GetComponent<AGF_GridManager>().EditorInit();
		
		// step 3: loading the scene is now possible through the level loader.
		returnCode = m_LevelLoader.LoadScene( filePath, mode, overrideUserDataHomeFolder );
		if ( returnCode != AGF_ReturnCode.Success ){
			window.CloseWindow();	
			return returnCode;
		}
		
		// step 4: wait for an event callback to be received.
		m_CurrentSubState = SubState.LoadingScene;
		
		return returnCode;
	}
Example #5
0
	void DoIdle(){

		if (substate == SubState.Init) {
			transform.rotation = GameManager.instance.ball.transform.rotation;
			transform.Rotate(0,180,0);

			gameObject.SetActive(true);
			isJump = false;
			substate = SubState.Active;
		}

		if (substate == SubState.Active) {
			if(!ball)
				ball = GameManager.instance.ball;

			if(GameState.instance.isFlyBall){
				substate = SubState.Deactive;
				agility = Random.Range(0.5f,1.5f);
			}
			anim.CrossFade("Idle",0);
		}

		if (substate == SubState.Deactive) {
		//	timer +=Time.deltaTime;
		//	if(timer > agility){
				substate = SubState.Finish;
		//		timer = 0;
		//	}

		}

		if (substate == SubState.Finish) {
			substate = SubState.Init;
			int i = Random.Range(0,2);
			switch(i){
			case 0:
				aiState = AIState.Jump1;
				break;
			case 1:
				aiState = AIState.Jump2;
				break;
			case 2:
				aiState = AIState.Jump3;
				break;
			}

		}
	}
Example #6
0
        private void Update()
        {
            if (cur_state == State.Playing)
            {
                return;
            }
            switch (cur_state)
            {
            case State.CheckExtractResource:
                if (cur_sub_state == SubState.Enter)
                {
                    cur_sub_state = SubState.Update;
                    loadingView.SetData(0.0f, "首次解压游戏数据(不消耗流量)");
                    this.gameObject.AddComponent <AssetsHotFixManager>();
                    AssetsHotFixManager.Instance.CheckExtractResource(delegate(float percent){
                        loadingView.SetData(0.3f * percent, "首次解压游戏数据(不消耗流量)");
                    }, delegate() {
                        Debug.Log("Main.cs CheckExtractResource OK!!!");
                        JumpToState(State.UpdateResourceFromNet);
                    });
                }
                break;

            case State.UpdateResourceFromNet:
                if (cur_sub_state == SubState.Enter)
                {
                    cur_sub_state = SubState.Update;
                    loadingView.SetData(0.3f, "从服务器下载最新的资源文件...");
                    AssetsHotFixManager.Instance.UpdateResource(delegate(float percent, string tip){
                        loadingView.SetData(0.3f + 0.5f * percent, tip);
                    }, delegate(string result) {
                        if (result == "")
                        {
                            Debug.Log("Main.cs UpdateResourceFromNet OK!!!");
                        }
                        else
                        {
                            Debug.Log(result);
                        }
                        JumpToState(State.InitAssetBundle);
                    });
                }
                break;

            case State.InitAssetBundle:
                if (cur_sub_state == SubState.Enter)
                {
                    cur_sub_state = SubState.Update;
                    loadingView.SetData(0.8f, "初始化游戏资源...");
                    ResourceManager.GetInstance().Initialize(AppConfig.AssetDir, delegate(float percent){
                        loadingView.SetData(0.8f + 0.2f * percent, "初始化游戏资源...");
                    }, delegate() {
                        Debug.Log("Main.cs ResourceManager Initialize OK!!!");
                        JumpToState(State.StartLogin);
                    });
                }
                break;

            case State.StartLogin:
                if (cur_sub_state == SubState.Enter)
                {
                    cur_sub_state = SubState.Update;
                    loadingView.SetData(1, "初始化游戏资源完毕");
                    XLuaManager.Instance.InitLuaEnv();
                    loadingView.SetActive(false, 0.5f);
                    XLuaManager.Instance.StartLogin(delegate() {
                        Debug.Log("Main.cs XLuaManager StartLogin OK!!!");
                        JumpToState(State.StartGame);
                    });
                }
                break;

            case State.StartGame:
                if (cur_sub_state == SubState.Enter)
                {
                    cur_sub_state = SubState.Update;
                    this.gameObject.AddComponent <UnityMMO.MainWorld>();
                    UnityMMO.MainWorld.Instance.StartGame();
                    JumpToState(State.Playing);
                }
                break;

            case State.Playing:
                break;
            }
        }
Example #7
0
        private void ManageControl(object sender, EventArgs args)
        {
            if (isPaused)
            {
                goto skip;
            }

            // To control flow of program
            // Rest of the things will be handeled from here
            if (cnt % 1000 == 0)
            {
                GC.Collect();
            }
            cnt++;
            if (changeState == false && impose)
            {
                state    = stateImposed;
                subState = subStateImposed;
                impose   = false;
            }
            if (!changeState)
            {
                long currentNet = currentStateCounter + currentStateChangeCounter;
                switch (state)
                {
                case State.REST:
                    if (Math.Abs(Cursor.Position.X - cX) < 2)
                    {
                        currentStateCounter++;
                    }
                    else
                    {
                        currentStateCounter = 0;
                        currentStateChangeCounter++;
                    }

                    if (currentStateCounter >= Properties.Settings.Default.WAIT_RUN && Math.Abs(Cursor.Position.X - xPositionCanvas - GetLoc()) > 100 &&
                        (subState == SubState.RESTV1 || subState == SubState.RESTV2))
                    {
                        //currentStateCounter = 0;
                        //currentStateChangeCounter = 0;
                        changeState      = true;
                        xDestinationWalk = (int)cX;
                        if (cX > xPositionCanvas)
                        {
                            direction = Direction.RIGHT;
                        }
                        else
                        {
                            direction = Direction.LEFT;
                        }
                    }
                    if (currentStateCounter >= Properties.Settings.Default.WAIT_RESTCHANGE && (subState == SubState.RESTV1 || subState == SubState.RESTV2))
                    {
                        currentStateCounter       = 0;
                        currentStateChangeCounter = 0;
                        double prob = GetProbability();
                        if (prob <= 0.45)
                        {
                            subState = SubState.RESTV3S;
                        }
                        else if (prob > 0.45 && prob < 0.9)
                        {
                            subState = SubState.RESTV4S;
                        }
                        else if (prob > 0.9)
                        {
                            state = State.FLY;
                            prob  = GetProbability();
                            if (prob > 0.5)
                            {
                                subState = SubState.FLYS1;
                            }
                            else
                            {
                                subState = SubState.FLYS2;
                            }
                        }
                    }
                    //Console.WriteLine(currentNet + " " + currentStateChangeCounter);

                    if (currentStateChangeCounter > 300 && currentNet > 1500 && (subState == SubState.FLYL || subState == SubState.RESTV3L1 ||
                                                                                 subState == SubState.RESTV3L2 || subState == SubState.RESTV4L))
                    {
                        changeState               = true;
                        currentStateCounter       = 0;
                        currentStateChangeCounter = 0;
                    }
                    if (currentNet % 100 == 0)
                    {
                        if (cX > xPositionCanvas)
                        {
                            direction = Direction.RIGHT;
                        }
                        else
                        {
                            direction = Direction.LEFT;
                        }
                    }
                    break;

                case State.WALK:
                    if (Math.Abs(xPositionCanvas + GetLoc() - xDestinationWalk) < 20 ||
                        xPositionCanvas < canvas.Width || xPositionCanvas > Screen.PrimaryScreen.WorkingArea.Width - canvas.Width)
                    {
                        changeState = true;
                    }
                    break;
                }
            }

            cX = Cursor.Position.X;
            int xOffset         = 0;
            int taskBarLocation = Math.Max(0, Screen.PrimaryScreen.WorkingArea.Bottom - (int)canvas.Height + (int)(40 / scale));

            // This Part Controls What Will Be Displayed On Screen
            switch (state)
            {
            case State.REST:
            {
                switch (subState)
                {
                case SubState.RESTV1:
                    if (restV1.Update(cnt, 0, 0))
                    {
                        if (GetProbability() > 0.4)
                        {
                            subState = SubState.RESTV2;
                        }
                        if (changeState)
                        {
                            state = State.WALK;
                            if (GetProbability() > 0.8)
                            {
                                subState = SubState.WALKV1S;
                            }
                            else
                            {
                                subState = SubState.WALKV2S;
                            }
                            changeState = false;
                        }
                    }
                    p1 = restV1.GetLocation(0);
                    p2 = restV1.GetLocation(1);
                    break;

                case SubState.RESTV2:
                    if (restV2.Update(cnt, 0, 0))
                    {
                        double prob = GetProbability();
                        if (prob > 0.8)
                        {
                            subState = SubState.RESTV1;
                        }
                        else if (prob > 0.95)
                        {
                            state = State.ACTION_DANCE;
                        }
                        if (changeState)
                        {
                            state = State.WALK;
                            if (GetProbability() > 0.8)
                            {
                                subState = SubState.WALKV1S;
                            }
                            else
                            {
                                subState = SubState.WALKV2S;
                            }
                            changeState = false;
                        }
                    }
                    p1 = restV2.GetLocation(0);
                    p2 = restV2.GetLocation(1);
                    break;

                case SubState.RESTV3S:
                    xOffset      = -25;
                    yoffsetRest += 9.0 / 25.0;
                    if (restV3S.Update(cnt, 0, 0))
                    {
                        subState = SubState.RESTV3L1;
                    }
                    p1 = restV3S.GetLocation(0);
                    p2 = restV3S.GetLocation(1);
                    break;

                case SubState.RESTV3L1:
                    xOffset     = -25;
                    yoffsetRest = 9;
                    if (restV3L1.Update(cnt, 0, 0))
                    {
                        if (changeState)
                        {
                            subState = SubState.RESTV3E;
                        }
                        else
                        {
                            if (GetProbability() > 0.9)
                            {
                                subState = SubState.RESTV3L2;
                            }
                            else
                            {
                                subState = SubState.RESTV3L1;
                            }
                            changeState = false;
                        }
                    }
                    p1 = restV3L1.GetLocation(0);
                    p2 = restV3L1.GetLocation(1);
                    break;

                case SubState.RESTV3L2:
                    yoffsetRest = 9;
                    xOffset     = -25;
                    if (restV3L2.Update(cnt, 0, 0))
                    {
                        if (changeState)
                        {
                            subState = SubState.RESTV3E;
                        }
                        else
                        {
                            if (GetProbability() > 0.8)
                            {
                                subState = SubState.RESTV3L2;
                            }
                            else
                            {
                                subState = SubState.RESTV3L1;
                            }
                        }
                    }
                    p1 = restV3L2.GetLocation(0);
                    p2 = restV3L2.GetLocation(1);
                    break;

                case SubState.RESTV3E:
                    xOffset      = -25;
                    yoffsetRest -= 9.0 / 25.0;
                    if (restV3E.Update(cnt, 0, 0))
                    {
                        state = State.WALK;
                        if (GetProbability() > 0.8)
                        {
                            subState = SubState.WALKV1S;
                        }
                        else
                        {
                            subState = SubState.WALKV2S;
                        }
                        changeState = false;
                    }
                    p1 = restV3E.GetLocation(0);
                    p2 = restV3E.GetLocation(1);
                    break;

                case SubState.RESTV4S:
                    xOffset      = -25;
                    yoffsetRest -= 10.0 / 40.0;
                    if (yoffsetRest < -10)
                    {
                        yoffsetRest = -10;
                    }
                    if (restV4S.Update(cnt, 0, 0))
                    {
                        subState = SubState.RESTV4L;
                    }
                    p1 = restV4S.GetLocation(0);
                    p2 = restV4S.GetLocation(1);
                    break;

                case SubState.RESTV4L:
                    xOffset     = -25;
                    yoffsetRest = -10;
                    if (restV4L.Update(cnt, 0, 0) && changeState)
                    {
                        subState = SubState.RESTV4E;
                    }
                    p1 = restV4L.GetLocation(0);
                    p2 = restV4L.GetLocation(1);
                    break;

                case SubState.RESTV4E:
                    xOffset      = -25;
                    yoffsetRest += 10.0 / 37.0;
                    if (restV4E.Update(cnt, 0, 0))
                    {
                        state = State.WALK;
                        if (GetProbability() > 0.8)
                        {
                            subState = SubState.WALKV1S;
                        }
                        else
                        {
                            subState = SubState.WALKV2S;
                        }
                        changeState = false;
                    }
                    p1 = restV4E.GetLocation(0);
                    p2 = restV4E.GetLocation(1);
                    break;
                }
                break;
            }

            case State.WALK:
            {
                switch (subState)
                {
                case SubState.WALKV1S:
                    xOffset = -25;
                    if (walkV1S.Update(cnt, 0, 0))
                    {
                        subState = SubState.WALKV1L;
                    }
                    p1 = walkV1S.GetLocation(0);
                    p2 = walkV1S.GetLocation(1);
                    break;

                case SubState.WALKV1L:
                    if (direction == Direction.RIGHT)
                    {
                        xPositionCanvas += 6;
                    }
                    else
                    {
                        xPositionCanvas -= 6;
                    }
                    xOffset = -25;
                    if (walkV1L.Update(cnt, 0, 0) && changeState)
                    {
                        subState = SubState.WALKV1E;
                    }
                    p1 = walkV1L.GetLocation(0);
                    p2 = walkV1L.GetLocation(1);
                    break;

                case SubState.WALKV1E:
                    xOffset = -25;
                    if (walkV1E.Update(cnt, 0, 0))
                    {
                        subState    = SubState.RESTV2;
                        state       = State.REST;
                        changeState = false;
                    }
                    p1 = walkV1E.GetLocation(0);
                    p2 = walkV1E.GetLocation(1);
                    break;

                case SubState.WALKV2S:
                    xOffset = -25;
                    if (walkV2S.Update(cnt, 0, 0))
                    {
                        subState = SubState.WALKV2L;
                    }
                    p1 = walkV2S.GetLocation(0);
                    p2 = walkV2S.GetLocation(1);
                    break;

                case SubState.WALKV2L:
                    if (direction == Direction.RIGHT)
                    {
                        xPositionCanvas += 3;
                    }
                    else
                    {
                        xPositionCanvas -= 3;
                    }
                    xOffset = -25;
                    if (walkV2L.Update(cnt, 0, 0) && changeState)
                    {
                        subState = SubState.WALKV2E;
                    }
                    p1 = walkV2L.GetLocation(0);
                    p2 = walkV2L.GetLocation(1);
                    break;

                case SubState.WALKV2E:
                    xOffset = -25;
                    if (walkV2E.Update(cnt, 0, 0))
                    {
                        state       = State.REST;
                        subState    = SubState.RESTV2;
                        changeState = false;
                    }
                    p1 = walkV2E.GetLocation(0);
                    p2 = walkV2E.GetLocation(1);
                    break;
                }
                break;
            }

            case State.ACTION_DANCE:
            {
                xOffset = -40;
                if (action_Dance.Update(cnt, 0, 0))
                {
                    changeState = false;
                    state       = State.REST;
                    subState    = SubState.RESTV2;
                }
                p1 = action_Dance.GetLocation(0);
                p2 = action_Dance.GetLocation(1);
                break;
            }

            case State.FLY:
            {
                xOffset = -40;
                switch (subState)
                {
                case SubState.FLYS1:
                    if (flyS1.Update(cnt, 0, 0))
                    {
                        subState = SubState.FLYS2;
                    }
                    p1      = flyS1.GetLocation(0);
                    p2      = flyS1.GetLocation(1);
                    yOffset = 0;
                    destY   = 0;
                    break;

                case SubState.FLYS2:
                    if (flyS2.Update(cnt, 0, 0))
                    {
                        subState = SubState.FLYL;
                    }
                    p1       = flyS2.GetLocation(0);
                    p2       = flyS2.GetLocation(1);
                    yOffset -= 3;
                    break;

                case SubState.FLYL:
                {
                    bool stable = true;
                    if (yOffset >= -30)
                    {
                        subState = SubState.FLYE2;
                    }
                    flyL.Update(cnt, 0, 0);

                    // To change the direction of Dino
                    if (Math.Abs(destX - xPositionCanvas) > 50)
                    {
                        if (destX > xPositionCanvas && counter == 0)                     // Counter is used for adding delay
                        {
                            direction = Direction.RIGHT;                                 // But in next part of code its also
                        }
                        else if (counter == 0)                                           // used as input to Sin function
                        {
                            direction = Direction.LEFT;
                        }

                        if (direction == Direction.RIGHT)
                        {
                            xPositionCanvas += 3;
                        }
                        else
                        {
                            xPositionCanvas -= 3;
                        }
                        xPositionCanvas = (int)Math.Min(xPositionCanvas, Screen.PrimaryScreen.WorkingArea.Width * 0.8f);
                        stable          = false;
                    }

                    if (changeState)
                    {
                        yOffset += 2;
                    }
                    else if (yPositionCanvas > destY && Math.Abs(destY - yPositionCanvas) > lim)
                    {
                        lim      = 5;
                        yOffset -= 2;
                        if (yOffset < -taskBarLocation)
                        {
                            yOffset = -taskBarLocation;
                        }
                        stable = false;
                    }
                    else if (yPositionCanvas < destY && Math.Abs(destY - yPositionCanvas) > lim)
                    {
                        lim      = 5;
                        yOffset += 2;
                        if (yOffset > 0)
                        {
                            yOffset = 0;
                        }
                        stable = false;
                    }

                    counter += 10;
                    if (stable)                 // This gives effect of hovering using sin function
                    {
                        yOffset += (int)(2 * Math.Sin(counter / 100.0));
                        lim      = 50;
                    }
                    if (counter > 628)
                    {
                        counter = 0;
                    }
                    p1 = flyL.GetLocation(0);
                    p2 = flyL.GetLocation(1);

                    if (counter == 0 && (!stable || Math.Abs(Cursor.Position.X - xPositionCanvas) > 500))
                    {
                        destX = Cursor.Position.X;
                        destY = Cursor.Position.Y;
                    }
                    break;
                }

                case SubState.FLYE2:
                    if (flyE2.Update(cnt, 0, 0))
                    {
                        subState = SubState.FLYE1;
                    }
                    p1       = flyE2.GetLocation(0);
                    p2       = flyE2.GetLocation(1);
                    yOffset += 4;
                    break;

                case SubState.FLYE1:
                    if (flyE1.Update(cnt, 0, 0))
                    {
                        state       = State.REST;
                        subState    = SubState.RESTV2;
                        changeState = false;
                    }

                    p1 = flyE1.GetLocation(0);
                    p2 = flyE1.GetLocation(1);
                    break;
                }
                break;
            }
            }

            DrawEye(p1, ref dinoBabyEyeBkgL, ref dinoBabyEyePupilL, Direction.LEFT, true);
            DrawEye(p2, ref dinoBabyEyeBkgR, ref dinoBabyEyePupilR, Direction.RIGHT, false);
            yPositionCanvas = Math.Min(taskBarLocation, taskBarLocation + yOffset);

            if (direction == Direction.RIGHT)
            {
                xOffset *= -1;
                xOffset -= 80;
            }
            this.Location = new Point(xPositionCanvas + xOffset, (int)(yPositionCanvas + yoffsetRest));

            if (direction == Direction.RIGHT)
            {
                canvas.FlipBitmap();
            }
            int xC, yC;

            xC = Cursor.Position.X;
            yC = Cursor.Position.Y;
            if (customTransparency == false)
            {
                if (Properties.Settings.Default.FADE_ON_HOVER)
                {
                    if ((xC > xPositionCanvas && xC < xPositionCanvas + canvas.Width) &&
                        (yC > yPositionCanvas && yC < yPositionCanvas + canvas.Height))
                    {
                        if (transparencyLevel > 0.1f)
                        {
                            transparencyLevel -= 0.05f;
                        }
                    }
                    else if (transparencyLevel < 1)
                    {
                        transparencyLevel += 0.008f;
                    }
                    else
                    {
                        transparencyLevel = 1f;
                    }
                }
                else
                {
                    transparencyLevel = 1f;
                }
            }
            if (transparencyLevel != 1f)
            {
                canvas.SetTransparency(transparencyLevel);
            }
            SetBitmap(canvas.GetBitmap());
            canvas.Clear();
            cnt %= 10000000;

skip:
            {
                // Just to skip
                if (isPaused)
                {
                    SetBitmap(canvas.GetBitmap());
                    canvas.Clear();
                }
            }
        }
    void UpdateInput()
    {
        if (!activePlayer)
        {
            return;
        }

        if (Application.platform == RuntimePlatform.Android)
        {
            if (Input.GetKeyDown(KeyCode.Escape))
            {
                Application.Quit();
            }

            int i = 0;
            while (i < Input.touchCount)
            {
                if (Input.GetTouch(i).phase == TouchPhase.Began)
                {
                    Ray        ray = Camera.main.ScreenPointToRay(Input.GetTouch(i).position);
                    RaycastHit _rayHit;

                    if (Physics.Raycast(ray, out _rayHit) && (_rayHit.collider.tag == "Ground" || _rayHit.collider.tag == "Object"))
                    {
                        rayHit      = _rayHit;
                        playerState = PlayerState.Walk;
                        subState    = SubState.Init;
                    }
                }
                ++i;
            }
        }
        else
        {
            if (Input.GetMouseButtonDown(1))
            {
                Ray        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                RaycastHit _rayHit;
                if (Physics.Raycast(ray, out _rayHit) && (_rayHit.collider.tag == "Ground" || _rayHit.collider.tag == "Object"))
                {
                    rayHit      = _rayHit;
                    playerState = PlayerState.Walk;
                    subState    = SubState.Init;
                }
            }

            if (tooglePass)
            {
                Ray        ray2 = Camera.main.ScreenPointToRay(Input.mousePosition);
                RaycastHit _rayHit2;
                if (Physics.Raycast(ray2, out _rayHit2) && (_rayHit2.collider.tag == "Ground"))
                {
                    passTarget = _rayHit2.point;
                    GameManager.instance.cursorAimTarget.transform.position = passTarget;
                }
            }

            if (Input.GetMouseButtonDown(0))
            {
                if (tooglePass)
                {
                    playerState = PlayerState.Pass;
                    subState    = SubState.Init;
                }
            }

            if (haveBall)
            {
                if (shootTimer > 0.5f || Input.GetKeyUp(KeyCode.Space))
                {
                    shootTimer  = 0;
                    playerState = PlayerState.Shoot;
                    subState    = SubState.Init;
                    return;
                }

                if (Input.GetKey(KeyCode.Space))
                {
                    shootTimer += Time.deltaTime;
                    shootPower += maxShootPower / 0.5f * Time.deltaTime;
                }

                if (Input.GetKeyDown(KeyCode.A))
                {
                    tooglePass = !tooglePass;
                }
            }
        }
    }
Example #9
0
        private void Update()
        {
            if (cur_state == State.Playing)
            {
                return;
            }
            switch (cur_state)
            {
            case State.CheckExtractResource:
                if (cur_sub_state == SubState.Enter)
                {
                    cur_sub_state = SubState.Update;
                    this.gameObject.AddComponent <AssetsHotFixManager>();
                    AssetsHotFixManager.Instance.CheckExtractResource(delegate() {
                        Debug.Log("Main.cs CheckExtractResource OK!!!");
                        JumpToState(State.UpdateResourceFromNet);
                    });
                }
                break;

            case State.UpdateResourceFromNet:
                if (cur_sub_state == SubState.Enter)
                {
                    cur_sub_state = SubState.Update;
                    AssetsHotFixManager.Instance.UpdateResource(delegate() {
                        Debug.Log("Main.cs UpdateResourceFromNet OK!!!");
                        JumpToState(State.InitAssetBundle);
                    });
                }
                break;

            case State.InitAssetBundle:
                if (cur_sub_state == SubState.Enter)
                {
                    cur_sub_state = SubState.Update;
                    ResourceManager.GetInstance().Initialize(AppConfig.AssetDir, delegate() {
                        Debug.Log("Main.cs ResourceManager Initialize OK!!!");
                        JumpToState(State.StartLogin);
                    });
                }
                break;

            case State.StartLogin:
                if (cur_sub_state == SubState.Enter)
                {
                    cur_sub_state = SubState.Update;
                    XLuaManager.Instance.InitLuaEnv();
                    XLuaManager.Instance.StartLogin(delegate() {
                        Debug.Log("Main.cs XLuaManager StartLogin OK!!!");
                        JumpToState(State.StartGame);
                    });
                }
                break;

            case State.StartGame:
                if (cur_sub_state == SubState.Enter)
                {
                    cur_sub_state = SubState.Update;
                    Debug.Log("main.cs start game");
                    this.gameObject.AddComponent <UnityMMO.MainWorld>();
                    Debug.Log("main.cs start game2");
                    UnityMMO.MainWorld.Instance.StartGame();
                    Debug.Log("main.cs start game3");
                    JumpToState(State.Playing);
                }
                break;

            case State.Playing:
                break;
            }
        }
Example #10
0
    public override WormAIBaseState Update()
    {
        switch (subState)
        {
        case SubState.WAITING:
            if (elapsedTime >= bb.BelowAttackSettingsPhase.initialWaitTime)
            {
                GameObject playerGO = rsc.enemyMng.SelectPlayerRandom();
                if (playerGO != null)
                {
                    PlayerController player = playerGO.GetComponent <PlayerController>();
                    origin = player.GetNearestHexagon();

                    if (origin != null)
                    {
                        if (!origin.isWormSelectable)
                        {
                            return(head.wanderingState);
                        }

                        head.animator.SetBool("Bite", true);

                        destiny = GetHexagonFacingCenter(origin, destinyHexagonsDistance);

                        bb.CalculateParabola(origin.transform.position, destiny.transform.position);

                        head.agent.enabled = false;

                        rotation       = 0f;
                        destinyInRange = false;
                    }
                    else
                    {
                        return(head.wanderingState);
                    }
                }
                else
                {
                    return(head.wanderingState);
                }

                origin.WormBelowAttackWarning(bb.BelowAttackSettingsPhase.adjacentDamagingCells);

                elapsedTime = 0f;
                head.attackWarningSoundFx.Play();

                subState = SubState.WARNING_PLAYER;
            }
            else
            {
                elapsedTime += Time.deltaTime;
            }

            break;

        case SubState.WARNING_PLAYER:

            if (elapsedTime >= bb.BelowAttackSettingsPhase.warningTime)
            {
                //Position head below entry point
                currentX = bb.GetJumpXGivenY(-WormBlackboard.NAVMESH_LAYER_HEIGHT, false);
                Vector3 startPosition = bb.GetJumpPositionGivenY(-WormBlackboard.NAVMESH_LAYER_HEIGHT, false);
                headTrf.position = startPosition;
                lastPosition     = startPosition;
                head.SetVisible(true);

                origin.WormBelowAttackStart();

                AttackActions();

                bb.isHeadOverground = true;
                subState            = SubState.JUMPING;
            }
            else
            {
                elapsedTime += Time.deltaTime;
            }

            break;

        case SubState.JUMPING:
            //While not again below underground navmesh layer advance
            currentX        += Time.deltaTime * bb.BelowAttackSettingsPhase.jumpSpeed;
            lastPosition     = headTrf.position;
            headTrf.position = bb.GetJumpPositionGivenX(currentX);

            headTrf.LookAt(headTrf.position + (headTrf.position - lastPosition), headTrf.up);

            float angle = bb.BelowAttackSettingsPhase.rotationSpeed * Time.deltaTime;
            headTrf.Rotate(new Vector3(0, 0, angle));
            rotation += angle;

            if (!destinyInRange)
            {
                float distanceToDestiny = (headTrf.position - destiny.transform.position).magnitude;
                if (distanceToDestiny <= destinyInRangeDistance ||
                    (headTrf.position.y < destiny.transform.position.y &&
                     currentX >= 0))    //Safety check. When jump is too fast distance can never be less than range distance
                {
                    destinyInRange = true;
                    JumpExitActions();
                    destiny.WormEnterExit();
                }
            }

            if (headTrf.position.y < -WormBlackboard.NAVMESH_LAYER_HEIGHT)
            {
                bb.isHeadOverground     = false;
                bb.tailReachedMilestone = false;
                bb.FlagCurrentWaypointAsMilestone();
                head.SetVisible(false);

                subState = SubState.EXITING;
            }
            break;

        case SubState.EXITING:
            currentX        += Time.deltaTime * bb.BelowAttackSettingsPhase.jumpSpeed;
            lastPosition     = headTrf.position;
            headTrf.position = bb.GetJumpPositionGivenX(currentX);

            headTrf.LookAt(headTrf.position + (headTrf.position - lastPosition));

            if (bb.tailReachedMilestone)
            {
                //Debug.Break();
                Vector3 pos = headTrf.position;
                pos.y            = -WormBlackboard.NAVMESH_LAYER_HEIGHT;
                headTrf.position = pos;

                return(head.wanderingState);
            }
            break;

        default:
            break;
        }

        return(null);
    }
Example #11
0
    public override HexagonBaseState Update()
    {
        switch (subState)
        {
        case SubState.WAITING:
            if (elapsedTime >= hex.meteorWaitTime)
            {
                meteor = rsc.poolMng.meteorPool.GetObject();
                meteor.transform.position = hex.meteorInitialPosition.position;

                elapsedTime = 0f;
                subState    = SubState.WARNING;
            }
            else
            {
                ReturnToPlace();
                elapsedTime += Time.deltaTime;
            }
            break;

        case SubState.WARNING:
            if (elapsedTime >= hex.meteorWarningTime)
            {
                hex.plane.transform.localScale = Vector3.one;
                hex.StartPlaneInfectionAnimation();

                hex.columnBlinkController.InvalidateMaterials();
                hex.columnBlinkController.BlinkWhiteNoStop(hex.aboveAttackBlinkInterval, hex.aboveAttackBlinkInterval);

                if (!hex.continousPurple.isPlaying)
                {
                    hex.continousPurple.Play();
                }

                meteor.Explode();
                elapsedTime   = 0;
                shakeTime     = 0;
                lastHeightDir = -1;
                subState      = SubState.EXPLODING;
            }
            else
            {
                ReturnToPlace();

                float t = elapsedTime / hex.meteorWarningTime;

                float newScale = Mathf.Lerp(0.1f, 1f, t);
                hex.plane.transform.localScale = new Vector3(newScale, 1f, newScale);
                meteor.transform.position      = Vector3.Lerp(hex.meteorInitialPosition.position, hex.transform.position, t);

                elapsedTime += Time.deltaTime;
            }
            break;


        case SubState.EXPLODING:
            if (elapsedTime >= hex.meteorImpactDuration)
            {
                return(hex.idleState);
            }
            else
            {
                if (hex.meteorImpactMaxShakeHeight > 0)
                {
                    if (shakeTime >= hex.meteorImpactShakeInterval)
                    {
                        shakeTime -= hex.meteorImpactShakeInterval;
                        float randHeight = Random.Range(0, hex.meteorImpactMaxShakeHeight) * lastHeightDir;
                        lastHeightDir *= -1;
                        hex.geometryOffset.transform.position = new Vector3(hex.geometryOffset.transform.position.x, hex.geometryOriginalY + randHeight, hex.geometryOffset.transform.position.z);
                    }
                    else
                    {
                        shakeTime += Time.deltaTime;
                    }
                }

                elapsedTime += Time.deltaTime;
            }

            break;

        default:
            break;
        }

        return(null);
    }
    public override WormAIBaseState Update()
    {
        switch (subState)
        {
        case SubState.KNOCKED_OUT:
            if (elapsedTime >= bb.HealthSettingsPhase.knockOutTime)
            {
                //Restore
                head.recoverSoundFx.Play();
                head.ResetPhase();

                destiny = GetExitHexagon();
                bb.CalculateParabola(headTrf.position, destiny.transform.position);
                speed = (headTrf.position - destiny.transform.position).magnitude / bb.headDestroyedJumpDuration;

                //Calculate start point and prior point
                currentX = bb.GetJumpXGivenY(0, false);
                Vector3 startPosition = bb.GetJumpPositionGivenY(0, false);
                headTrf.position = startPosition;

                lastPosition = bb.GetJumpPositionGivenX(currentX);

                float   fakeNextX    = currentX + Time.deltaTime * 2;
                Vector3 nextPosition = bb.GetJumpPositionGivenX(fakeNextX);
                initialRotation = Quaternion.LookRotation(nextPosition - startPosition, headTrf.up);

                head.animator.SetBool("Stunned", false);
                head.animator.SetBool("MouthOpen", true);
                elapsedTime = 0f;

                head.SetInvulnerable();

                subState = SubState.MOVING_HEAD;
            }
            else
            {
                if (elapsedTime >= 3f && !knockOutTutorialTriggered)
                {
                    knockOutTutorialTriggered        = true;
                    TutorialEventInfo.eventInfo.type = TutorialManager.Type.HIT_BOSS_HEAD;
                    rsc.eventMng.TriggerEvent(EventManager.EventType.SHOW_TUTORIAL, TutorialEventInfo.eventInfo);
                }

                elapsedTime += Time.deltaTime;
            }
            break;

        case SubState.MOVING_HEAD:
            headTrf.rotation = Quaternion.RotateTowards(headTrf.rotation, initialRotation, bb.headDestroyedLookRotationSpeed * Time.deltaTime);

            if (elapsedTime >= bb.headDestoryedBodyWaitTime)
            {
                subState = SubState.JUMPING;
            }
            else
            {
                elapsedTime += Time.deltaTime;
            }
            break;

        case SubState.JUMPING:
            //While not again below underground navmesh layer advance
            currentX        += Time.deltaTime * speed;
            lastPosition     = headTrf.position;
            headTrf.position = bb.GetJumpPositionGivenX(currentX);

            headTrf.LookAt(headTrf.position + (headTrf.position - lastPosition), headTrf.up);

            headTrf.Rotate(new Vector3(0, 0, bb.headDestroyedRotationSpeed * Time.deltaTime));

            if (!destinyInRange)
            {
                float distanceToDestiny = (headTrf.position - destiny.transform.position).magnitude;
                if (distanceToDestiny <= destinyInRangeDistance ||
                    headTrf.position.y < destiny.transform.position.y)     //Safety check. When jump is too fast distance can never be less than range distance
                {
                    destinyInRange = true;

                    JumpExitActions();

                    destiny.WormEnterExit();
                }
            }

            if (headTrf.position.y < -WormBlackboard.NAVMESH_LAYER_HEIGHT)
            {
                SetHeadUnderground();
                head.animator.SetBool("MouthOpen", false);

                subState = SubState.EXITING;
            }
            break;

        case SubState.EXITING:
            currentX        += Time.deltaTime * speed;
            lastPosition     = headTrf.position;
            headTrf.position = bb.GetJumpPositionGivenX(currentX);

            headTrf.LookAt(headTrf.position + (headTrf.position - lastPosition));

            if (bb.tailReachedMilestone)
            {
                Vector3 pos = headTrf.position;
                pos.y            = -WormBlackboard.NAVMESH_LAYER_HEIGHT;
                headTrf.position = pos;

                return(head.wanderingState);
            }
            break;

        default:
            break;
        }

        return(null);
    }
 protected void smCloseTcpConnection()
 {
     if (this.socketStream != null)
     {
         this.socketStream.Close();
         this.socketStream = null;
     }
     if (this.socket != null)
     {
         this.socket.Close();
         this.socket = null;
     }
     this.subState = SubState.Disconnected;
 }
 public void Clear()
 {
     _priState   = null;
     _subState   = null;
     _lastChange = null;
 }
Example #15
0
        protected override void OnUpdate(float dt)
        {
            base.OnUpdate(dt);
            switch (m_state)
            {
            case SubState.Waiting:
            {
                // Wait for camera press
                if (CheckCameraButton())
                {
                    m_state = SubState.Capturing;
                    m_timer = 0.0f;
                }
                else if (CheckBack())
                {
                    BackToEditor();
                }
                break;
            }

            case SubState.Capturing:
            {
                // Take the screenshot
                // Stop the action
                CameraController.AllowUserZoom   = false;
                CameraController.AllowUserRotate = false;

                // Clear the screen
                m_cameraHUD.ShowViewfinder = false;
                m_prompt.Visible           = false;

                // Request the screenshot
                m_screenshot = Game.QueueScreenshot(THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT);
                m_state      = SubState.CameraFlash;
                break;
            }

            case SubState.CameraFlash:
            {
                // Wait for screenshot, then flash
                if (m_screenshot.Status != Status.Waiting)
                {
                    // Do the effects
                    Game.Audio.PlayMusic(null, 0.0f);
                    m_cameraHUD.Flash();
                    m_state = SubState.Approving;
                    m_timer = FLASH_DURATION;
                }
                break;
            }

            case SubState.Approving:
            {
                // Wait for a timer, then prompt to save the screenshot
                if (m_timer > 0.0f)
                {
                    m_timer -= dt;
                    if (m_timer <= 0.0f)
                    {
                        // Create the texture
                        var screenshot = m_screenshot.Result;
                        var bitmap     = new BitmapTexture(screenshot.Bitmap);
                        bitmap.Filter = true;

                        // Show the dialog
                        var dialog = DialogBox.CreateImageQueryBox(
                            Game.Language.Translate("menus.create_thumbnail.confirm_prompt"),
                            bitmap,
                            427.0f,
                            240.0f,
                            new string[] {
                                Game.Language.Translate("menus.yes"),
                                Game.Language.Translate("menus.no"),
                            }
                            );
                        dialog.OnClosed += delegate(object sender, DialogBoxClosedEventArgs e)
                        {
                            // Handle the result
                            if (e.Result == 0)
                            {
                                // Yes
                                // Save the screenshot
                                var screenshotPath = AssetPath.ChangeExtension(m_levelSavePath, "png");
                                if (m_mod != null)
                                {
                                    var fullPath = Path.Combine(m_mod.Path, "assets/" + screenshotPath);
                                    screenshot.Save(fullPath);
                                }
                                else
                                {
                                    var fullPath = Path.Combine(App.AssetPath, "main/" + screenshotPath);
                                    screenshot.Save(fullPath);
                                }
                                Assets.Reload(screenshotPath);

                                // Save the camera position
                                Level.Info.CameraPitch    = MathHelper.RadiansToDegrees(CameraController.Pitch);
                                Level.Info.CameraYaw      = MathHelper.RadiansToDegrees(CameraController.Yaw);
                                Level.Info.CameraDistance = CameraController.Distance;
                                m_modified = true;

                                // Return
                                BackToEditor();
                            }
                            else if (e.Result == 1)
                            {
                                // No
                                TryAgain();
                            }
                            else
                            {
                                // Escape
                                BackToEditor();
                            }

                            // Dispose things we no longer need
                            bitmap.Dispose();
                            screenshot.Dispose();
                        };
                        ShowDialog(dialog);
                    }
                }
                break;
            }
            }
        }
Example #16
0
 void Start()
 {
     CurrentSubState = SubState.None;
 }
Example #17
0
 void onContinueTimer()
 {
     subState = SubState.Normal;
 }
Example #18
0
 void onPauseTimer()
 {
     subState = SubState.Pause;
 }
    public override WormAIBaseState Update()
    {
        switch (subState)
        {
        //Underground path
        case SubState.UNDERGROUND_START:
            GameObject playerGO = rsc.enemyMng.SelectPlayerRandom();
            if (playerGO != null)
            {
                PlayerController player = playerGO.GetComponent <PlayerController>();
                origin = player.GetNearestHexagon();

                if (origin != null)
                {
                    if (!origin.isWormSelectable)
                    {
                        return(head.wanderingState);
                    }

                    destiny = GetHexagonFacingCenter(origin, 2);
                    bb.CalculateParabola(origin.transform.position, destiny.transform.position);

                    head.agent.enabled = false;
                }
                else
                {
                    return(head.wanderingState);
                }
            }
            else
            {
                return(head.wanderingState);
            }

            origin.WormEnterExit();

            elapsedTime = 0f;
            head.attackWarningSoundFx.Play();

            subState = SubState.WARNING_PLAYER;

            break;

        case SubState.WARNING_PLAYER:

            if (elapsedTime >= bb.MeteorAttackSettingsPhase.warningTime)
            {
                //Position head below entry point
                currentX = bb.GetJumpXGivenY(-WormBlackboard.NAVMESH_LAYER_HEIGHT, false);
                Vector3 startPosition = bb.GetJumpPositionGivenY(-WormBlackboard.NAVMESH_LAYER_HEIGHT, false);
                headTrf.position = startPosition;
                lastPosition     = startPosition;
                head.SetVisible(true);

                elapsedTime         = 0f;
                bb.isHeadOverground = true;
                subState            = SubState.HEAD_EXIT;
            }
            else
            {
                elapsedTime += Time.deltaTime;
            }

            break;

        case SubState.HEAD_EXIT:
            if (headTrf.position.y < 2)
            {
                currentX        += Time.deltaTime * bb.MeteorAttackSettingsPhase.enterHeadSpeed;
                lastPosition     = headTrf.position;
                headTrf.position = bb.GetJumpPositionGivenX(currentX);

                headTrf.LookAt(headTrf.position + (headTrf.position - lastPosition), headTrf.up);

                elapsedTime += Time.deltaTime;
            }
            else
            {
                elapsedTime += bb.MeteorAttackSettingsPhase.warningTime;
                subState     = SubState.OPENING_MOUTH;
            }

            break;

        //Overground path
        case SubState.OVERGROUND_START:
            destiny = GetExitHexagon();
            bb.CalculateParabola(headTrf.position, destiny.transform.position);
            subState = SubState.OPENING_MOUTH;
            break;

        //Common path
        case SubState.OPENING_MOUTH:
            if (elapsedTime >= 1.5f)
            {
                elapsedTime = 0;
                //head.fireSpray.transform.position = head.headModel.transform.position + (Vector3.up * 0.5f);
                //head.fireSpray.transform.LookAt(head.fireSpray.transform.position + Vector3.up, head.transform.up);
                //head.fireSpray.Play();
                subState = SubState.SHOOTING;
            }
            else
            {
                elapsedTime += Time.deltaTime;
            }
            break;

        case SubState.SHOOTING:
            if (totalShots < bb.MeteorAttackSettingsPhase.numberOfThrownMeteors)
            {
                if (elapsedTime <= 0)
                {
                    MeteorController meteor = rsc.poolMng.meteorPool.GetObject();
                    meteor.transform.position = head.meteorSpawnPoint.position;
                    meteor.GoUp(bb.MeteorAttackSettingsPhase.speedOfThrownMeteors);

                    rsc.rumbleMng.Rumble(0, 0.15f, 0, 0.6f);
                    rsc.camerasMng.PlayEffect(0, 0.1f, 0.3f);

                    ++totalShots;
                    elapsedTime = timeBetweenShots;
                }
                else
                {
                    elapsedTime -= Time.deltaTime;
                }
            }
            else
            {
                speed = (headTrf.position - destiny.transform.position).magnitude / bb.MeteorAttackSettingsPhase.jumpDuration;

                //Calculate start point and prior point
                currentX = bb.GetJumpXGivenY(headTrf.position.y, false);
                Vector3 startPosition = bb.GetJumpPositionGivenY(headTrf.position.y, false);
                headTrf.position = startPosition;

                lastPosition = bb.GetJumpPositionGivenX(currentX);

                float   fakeNextX    = currentX + Time.deltaTime * 2;
                Vector3 nextPosition = bb.GetJumpPositionGivenX(fakeNextX);
                initialRotation = Quaternion.LookRotation(nextPosition - startPosition, headTrf.up);

                head.fireSpray.Stop();

                elapsedTime = 0;
                if (underground)
                {
                    head.animator.SetBool("MouthOpen", false);
                }
                else
                {
                    head.animator.SetBool("MouthOpenTrans", false);
                    head.animator.SetBool("Jump", true);
                }
                subState = SubState.CLOSING_MOUTH;
            }
            break;

        case SubState.CLOSING_MOUTH:
            headTrf.rotation = Quaternion.RotateTowards(headTrf.rotation, initialRotation, bb.headDestroyedLookRotationSpeed * Time.deltaTime);
            if (elapsedTime >= 1)
            {
                elapsedTime = 0;
                subState    = SubState.JUMPING;
                head.animator.SetBool("Jump", false);
            }
            else
            {
                elapsedTime += Time.deltaTime;
            }
            break;

        case SubState.JUMPING:
            //While not again below underground navmesh layer advance
            currentX        += Time.deltaTime * speed;
            lastPosition     = headTrf.position;
            headTrf.position = bb.GetJumpPositionGivenX(currentX);

            headTrf.LookAt(headTrf.position + (headTrf.position - lastPosition), headTrf.up);

            headTrf.Rotate(new Vector3(0, 0, bb.MeteorAttackSettingsPhase.rotationSpeed * Time.deltaTime));

            if (!destinyInRange)
            {
                float distanceToDestiny = (headTrf.position - destiny.transform.position).magnitude;
                if (distanceToDestiny <= destinyInRangeDistance ||
                    headTrf.position.y < destiny.transform.position.y)     //Safety check. When jump is too fast distance can never be less than range distance
                {
                    destinyInRange = true;

                    JumpExitActions();

                    destiny.WormEnterExit();
                }
            }

            if (headTrf.position.y < -WormBlackboard.NAVMESH_LAYER_HEIGHT)
            {
                SetHeadUnderground();

                subState = SubState.EXITING;
            }
            break;

        case SubState.EXITING:
            currentX        += Time.deltaTime * speed;
            lastPosition     = headTrf.position;
            headTrf.position = bb.GetJumpPositionGivenX(currentX);

            headTrf.LookAt(headTrf.position + (headTrf.position - lastPosition));

            if (bb.tailReachedMilestone)
            {
                Vector3 pos = headTrf.position;
                pos.y            = -WormBlackboard.NAVMESH_LAYER_HEIGHT;
                headTrf.position = pos;

                //Trigger meteor rain
                MeteorAttackEventInfo info = MeteorAttackEventInfo.eventInfo;
                WormBlackboard.MeteorAttackSettings settings = bb.MeteorAttackSettingsPhase;

                info.meteorInitialBurst = settings.meteorInitialBurst;
                info.meteorRainDuration = settings.meteorRainDuration;
                info.meteorInterval     = settings.meteorInterval;
                info.meteorsPerInterval = settings.meteorsPerInterval;
                info.meteorWaitTime     = settings.meteorWaitTime;
                info.meteorWarningTime  = settings.meteorWarningTime;

                rsc.eventMng.TriggerEvent(EventManager.EventType.METEOR_RAIN_START, info);
                subState = SubState.WAITING_METEOR_RAIN;
            }
            break;

        case SubState.WAITING_METEOR_RAIN:
            //Wait
            break;

        case SubState.METEOR_RAIN_ENDED:
            return(head.wanderingState);

        default:
            break;
        }

        return(null);
    }
        protected void smOpenTcpConnection()
        {
            // create and init socket
            this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            this.socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
            this.socket.SendTimeout = WSConst.SendTimeout;
            this.socket.ReceiveTimeout = WSConst.ReceiveTimeout;

            // connect to server
            this.socket.Connect(this.serverEndpoint);

            // get data stream
            if (this.serverUri.Scheme == WSConst.SchemeWSS)
            {
                this.socketStream = new SslStreamEx(this.socket);
                ((SslStreamEx)this.socketStream).AuthenticateAsClient(this.serverUri.Host);
            }
            else
            {
                this.socketStream = new NetworkStream(this.socket, true);
            }

            // go to next state
            this.subState = SubState.SendHandshake;
        }
        /// <summary>
        /// Connect - Begins the asynchronous (non-blocking) connection process.
        /// </summary>
        /// <param name="serverUrl">Url of server to connect to.</param>
        public void Connect(string serverUrl)
        {
            if (this.State == WebSocketState.Initialized || this.State == WebSocketState.Disconnected)
            {
                try
                {
                    this.serverUri = new UriEx(serverUrl);

                    IPHostEntry hostEntry = Dns.GetHostEntry(this.serverUri.Host);
                    IPAddress ipAddress = hostEntry.AddressList[0];
                    this.serverEndpoint = new IPEndPoint(ipAddress, this.serverUri.Port);

                    // start the connection process
                    Logger.WriteDebug(this.loggerID, "Connecting to " + serverUrl + " ...");
                    this.state = WebSocketState.Connecting;
                    this.subState = SubState.OpenTcpConnection;
                    this.runStateMachine.Set();
                }
                catch (Exception ex)
                {
                    this.OnError(WSErrorCode.NativeError, ex.Message, ex.StackTrace);
                }
            }
        }
        //------------------------------------------------------------------------------
        // Method: Update
        // Author: Neil Holmes & Andrew Green
        // Summary: allows the state to run logic, always called regardless of sub state
        //          although default functionality is provided the user is free to override
        //          this if they wish
        //------------------------------------------------------------------------------
        public virtual void Update(bool otherStateHasFocus, bool coveredByOtherScreen)
        {
            // store whether we have focus or not, for future reference
            this.otherStateHasFocus = otherStateHasFocus;

            // are we currently exiting this state?
            if (isExiting)
            {
                // yup we are exiting, make sure that the state is transitioning off
                subState = SubState.TransitionOff;

                // update the transition and check if it has completed
                if (!UpdateTransition(TransitionDirection.Off))
                {
                    // transition has finished - remove the state!
                    gameStateManager.RemoveGameState(this);
                }
            }
            else if (coveredByOtherScreen)
            {
                // if the state is currently being 'covered' by another, it should transition off
                if (UpdateTransition(TransitionDirection.Off))
                {
                    // still busy transitioning, ensure it's sub state is set correctly
                    subState = SubState.TransitionOff;
                }
                else
                {
                    // transition finished, set the the states sub-state to 'hidden'
                    subState = SubState.Hidden;
                }
            }
            else
            {
                // if we get here the state should either be transitioning on or be 'active'
                if (UpdateTransition(TransitionDirection.On))
                {
                    // still transitioning, ensure sub-state is set correctly
                    subState = SubState.TransitionOn;
                }
                else
                {
                    // transition has finished - ensure sub state is set to 'active'
                    subState = SubState.Active;
                }
            }
        }
 protected void smDisconnected()
 {
     this.state = WebSocketState.Disconnected;
     this.subState = SubState.Disconnected;
 }
    public override WormAIBaseState Update()
    {
        switch (subState)
        {
        //Wait for head Fx and animation
        case SubState.WAITING_HEAD:
            if (elapsedTime >= bb.headDestroyedWaitTime)
            {
                if (!shouldTriggerMeteor)
                {
                    destiny = GetExitHexagon();
                    bb.CalculateParabola(headTrf.position, destiny.transform.position);
                    speed = (headTrf.position - destiny.transform.position).magnitude / bb.headDestroyedJumpDuration;

                    //Calculate start point and prior point
                    currentX = bb.GetJumpXGivenY(0, false);
                    Vector3 startPosition = bb.GetJumpPositionGivenY(0, false);
                    headTrf.position = startPosition;

                    lastPosition = bb.GetJumpPositionGivenX(currentX);

                    float   fakeNextX    = currentX + Time.deltaTime * 2;
                    Vector3 nextPosition = bb.GetJumpPositionGivenX(fakeNextX);
                    initialRotation = Quaternion.LookRotation(nextPosition - startPosition, headTrf.up);
                }

                head.animator.SetBool("Hit", false);

                bb.ConsolidateBodyParts();
                subState = SubState.WAITING_BODY;

                elapsedTime = 0f;
            }
            else
            {
                elapsedTime += Time.deltaTime;
            }
            break;

        //Wait for body parts destruction
        case SubState.WAITING_BODY:

            if (bb.wormCurrentPhase < bb.wormMaxPhases - 1 && !shouldTriggerMeteor)
            {
                headTrf.rotation = Quaternion.RotateTowards(headTrf.rotation, initialRotation, bb.headDestroyedLookRotationSpeed * Time.deltaTime);
            }

            if (elapsedTime >= bb.headDestoryedBodyWaitTime)
            {
                if (bb.wormCurrentPhase == bb.wormMaxPhases - 1)
                {
                    return(head.dyingState);
                }
                else
                {
                    head.StartNewPhase();
                    head.SetMaterial(rsc.coloredObjectsMng.GetWormHeadMaterial(bb.headCurrentChargeLevel));
                    //rsc.eventMng.TriggerEvent(EventManager.EventType.WORM_HEAD_ACTIVATED, EventInfo.emptyInfo);

                    if (shouldTriggerMeteor)
                    {
                        bb.meteorInmediate = true;
                        return(head.meteorAttackState);
                    }
                    else
                    {
                        head.animator.SetBool("MouthOpen", true);
                        subState = SubState.JUMPING;
                    }
                }
            }
            else
            {
                elapsedTime += Time.deltaTime;
            }
            break;

        case SubState.JUMPING:
            //While not again below underground navmesh layer advance
            currentX        += Time.deltaTime * speed;
            lastPosition     = headTrf.position;
            headTrf.position = bb.GetJumpPositionGivenX(currentX);

            headTrf.LookAt(headTrf.position + (headTrf.position - lastPosition), headTrf.up);

            headTrf.Rotate(new Vector3(0, 0, bb.headDestroyedRotationSpeed * Time.deltaTime));

            if (!destinyInRange)
            {
                float distanceToDestiny = (headTrf.position - destiny.transform.position).magnitude;
                if (distanceToDestiny <= destinyInRangeDistance ||
                    headTrf.position.y < destiny.transform.position.y)     //Safety check. When jump is too fast distance can never be less than range distance
                {
                    destinyInRange = true;

                    JumpExitActions();

                    destiny.WormEnterExit();
                }
            }

            if (headTrf.position.y < -WormBlackboard.NAVMESH_LAYER_HEIGHT)
            {
                SetHeadUnderground();
                head.animator.SetBool("MouthOpen", false);

                subState = SubState.EXITING;
            }
            break;

        case SubState.EXITING:
            currentX        += Time.deltaTime * speed;
            lastPosition     = headTrf.position;
            headTrf.position = bb.GetJumpPositionGivenX(currentX);

            headTrf.LookAt(headTrf.position + (headTrf.position - lastPosition));

            if (bb.tailReachedMilestone)
            {
                Vector3 pos = headTrf.position;
                pos.y            = -WormBlackboard.NAVMESH_LAYER_HEIGHT;
                headTrf.position = pos;

                return(head.wanderingState);
            }
            break;

        default:
            break;
        }

        return(null);
    }
        protected void smReceive()
        {
            int bytesRead = 0;
            this.lastRcvdFrame = null;

            // start activity timer
            if (this.activityTimerEnabled)
            {
                this.activityTimer.Start(this.waitActivityTimeout, ActivityTimerState.WaitingForMessage);
            }

            while (this.State == WebSocketState.Connected)
            {
                // process data in buffer
                if (this.bytesInBuffer > 0)
                {
                    if (WSFrame.TryParse(this.receiveBuffer, 0, this.bytesInBuffer, this.options.MaxReceiveFrameLength, out this.lastRcvdFrame) == true)
                    {
                        // restart activity timer
                        if (this.activityTimerEnabled)
                        {
                            this.activityTimer.Restart(ActivityTimerState.WaitingForMessage);
                        }

                        // remove data-frame from buffer
                        Array.Copy(this.receiveBuffer, this.lastRcvdFrame.FrameData.Length, this.receiveBuffer, 0, this.bytesInBuffer - this.lastRcvdFrame.FrameData.Length);
                        this.bytesInBuffer = this.bytesInBuffer - this.lastRcvdFrame.FrameData.Length;

                        // take action based on opcode
                        switch (this.lastRcvdFrame.OpCode)
                        {
                            case WSFrameType.Continuation:
                                // TODO - implement continuation frames
                                break;
                            case WSFrameType.Text:
                                this.LogBufferContent("Text frame received: ", this.lastRcvdFrame.FrameData, 0, this.lastRcvdFrame.FrameData.Length);
                                this.OnTextReceived(this.lastRcvdFrame.PayloadText);
                                break;
                            case WSFrameType.Binary:
                                this.LogBufferContent("Data frame received: ", this.lastRcvdFrame.FrameData, 0, this.lastRcvdFrame.FrameData.Length);
                                this.OnDataReceived(this.lastRcvdFrame.PayloadBytes);
                                break;
                            case WSFrameType.Close:
                                this.LogBufferContent("Close frame received: ", this.lastRcvdFrame.FrameData, 0, this.lastRcvdFrame.FrameData.Length);
                                // based on RFC6455 we must stop sending and receiving messages after Close response is sent
                                this.activityTimer.Stop();
                                this.state = WebSocketState.Disconnecting;
                                this.subState = SubState.CloseTcpConnection;
                                this.smSendCloseResponse();
                                return;
                            case WSFrameType.Ping:
                                this.LogBufferContent("Ping frame received: ", this.lastRcvdFrame.FrameData, 0, this.lastRcvdFrame.FrameData.Length);
                                this.smSendPongMessage();
                                break;
                            case WSFrameType.Pong:
                                this.LogBufferContent("Pong frame received: ", this.lastRcvdFrame.FrameData, 0, this.lastRcvdFrame.FrameData.Length);
                                // no need to do anything
                                break;
                            default:
                                this.LogBufferContent("Unknown frame received: ", this.lastRcvdFrame.FrameData, 0, this.lastRcvdFrame.FrameData.Length);
                                break;
                        }
                    }
                }

                // send queued messages
                if (this.DequeueAndSendMessages() && this.activityTimerEnabled)
                {
                    this.activityTimer.Restart(ActivityTimerState.MessageSent);
                }

                // get more data
                if (this.socket.Poll(this.waitReceiveTimeout, SelectMode.SelectRead) == true && this.socket.Available > 0)
                {
                    bytesRead = this.socketStream.Read(this.receiveBuffer, this.bytesInBuffer, this.receiveBuffer.Length - this.bytesInBuffer);
                    this.bytesInBuffer += bytesRead;
                    continue;
                }

                // check activity timer
                if (this.activityTimer.HasTimedOut)
                {
                    switch ((ActivityTimerState)this.activityTimer.State)
                    {
                        case ActivityTimerState.MessageSent:
                        case ActivityTimerState.WaitingForMessage:
                            this.smSendPingMessage();
                            activityTimer.Restart(ActivityTimerState.WaitingForPingResponse);
                            break;
                        case ActivityTimerState.WaitingForPingResponse:
                            Logger.WriteError(this.loggerID, string.Concat("Ping response timed out."));
                            activityTimer.Stop();
                            this.state = WebSocketState.Disconnecting;
                            this.subState = SubState.CloseTcpConnection;
                            break;
                    }
                }
            }
        }
Example #26
0
    public override WormAIBaseState Update()
    {
        switch (subState)
        {
        case SubState.WAITING:
            if (elapsedTime >= bb.WanderingSettingsPhase.initialWaitTime)
            {
                head.agent.enabled = false;

                currentWP = route.wayPoints[WPIndex].transform.position;
                nextWP    = route.wayPoints[WPIndex + 1].transform.position;

                currentWPUG = currentWP - bb.navMeshLayersDistance;
                nextWPUG    = nextWP - bb.navMeshLayersDistance;

                headTrf.position = currentWPUG;
                headTrf.LookAt(nextWPUG, Vector3.up);
                bb.CalculateWorldEnterBezierPoints(headTrf);
                head.SetVisible(true);

                //Rotate head
                Vector3 headUp = currentWPUG - nextWPUG;
                headTrf.LookAt(currentWP, headUp);

                t = 0;

                HexagonController hexagon = route.wayPoints[WPIndex].GetComponent <HexagonController>();
                hexagon.WormEnterExit();

                EnterExitActions();
                head.animator.SetBool("MouthOpen", true);

                bb.isHeadOverground = true;
                bb.applySinMovement = true;

                subState = SubState.ENTERING;
            }
            else
            {
                elapsedTime += Time.deltaTime;
            }

            break;

        case SubState.ENTERING:
            if (t <= 2)
            {
                shouldMove    = Time.deltaTime * bb.WanderingSettingsPhase.wanderingSpeed;
                actuallyMoved = 0;
                lastPosition  = headTrf.position;
                Vector3 newPos = Vector3.zero;

                while (actuallyMoved < shouldMove && t <= 2)
                {
                    newPos = bb.GetEnterCurvePosition(currentWPUG, nextWP, t);

                    actuallyMoved = (newPos - lastPosition).magnitude;

                    t += Time.deltaTime / duration;
                }
                headTrf.position = newPos;
                headTrf.LookAt(headTrf.position + (headTrf.position - lastPosition));
            }
            else
            {
                ++WPIndex;
                currentWP = route.wayPoints[WPIndex].transform.position;

                head.agent.areaMask = WormBlackboard.NAVMESH_FLOOR_LAYER;
                head.agent.enabled  = true;
                head.agent.speed    = bb.WanderingSettingsPhase.wanderingSpeed;
                head.agent.SetDestination(currentWP);

                head.animator.SetBool("MouthOpen", false);

                bb.meteorInmediate = true;
                elapsedTime        = 0;

                subState = SubState.FOLLOWING_PATH;
            }

            break;

        case SubState.FOLLOWING_PATH:

            if (bb.AboveAttackSettingsPhase.active && head.CheckPlayerInSight(bb.AboveAttackSettingsPhase.exposureMinHexagons, bb.AboveAttackSettingsPhase.exposureMaxHexagons, false))
            {
                bb.aboveAttackCurrentExposureTime += Time.deltaTime;

                if (!angryEyes)
                {
                    angryEyes = true;
                    head.WatchingPlayer();
                }
            }
            else
            {
                if (angryEyes)
                {
                    angryEyes = false;
                    head.NotWatchingPlayer();
                }
            }

            if (bb.attacksEnabled && bb.AboveAttackSettingsPhase.active && bb.aboveAttackCurrentExposureTime >= bb.AboveAttackSettingsPhase.exposureTimeNeeded &&
                bb.aboveAttackCurrentCooldownTime >= bb.AboveAttackSettingsPhase.cooldownTime &&
                head.CheckPlayerInSight(bb.AboveAttackSettingsPhase.attackMinHexagons, bb.AboveAttackSettingsPhase.attackMaxHexagons, true))
            {
                if (bb.playerInSight != null)
                {
                    HexagonController destiny = bb.playerInSight.GetNearestHexagon();

                    if (destiny != null && destiny.isWormSelectable)
                    {
                        if (angryEyes)
                        {
                            angryEyes = false;
                            head.NotWatchingPlayer();
                        }
                        return(head.aboveAttackState);
                    }
                }
            }

            //Not reached next waypoint
            if (elapsedTime >= 6f)
            {
                head.agent.enabled = false;

                destiny = GetExitHexagon();
                bb.CalculateParabola(headTrf.position, destiny.transform.position);
                speed = (headTrf.position - destiny.transform.position).magnitude / bb.headDestroyedJumpDuration;

                //Calculate start point and prior point
                currentX = bb.GetJumpXGivenY(0, false);
                Vector3 startPosition = bb.GetJumpPositionGivenY(0, false);
                headTrf.position = startPosition;

                lastPosition = bb.GetJumpPositionGivenX(currentX);

                float   fakeNextX    = currentX + Time.deltaTime * 2;
                Vector3 nextPosition = bb.GetJumpPositionGivenX(fakeNextX);
                headTrf.rotation = Quaternion.LookRotation(nextPosition - startPosition, headTrf.up);

                subState = SubState.JUMPING;
            }
            else
            {
                elapsedTime += Time.deltaTime;

                if (!head.agent.hasPath || (head.agent.hasPath && head.agent.remainingDistance <= 0.25))
                {
                    if (WPIndex == route.wayPoints.Length - 2)
                    {
                        head.agent.enabled = false;

                        currentWP = route.wayPoints[WPIndex].transform.position;
                        nextWP    = route.wayPoints[WPIndex + 1].transform.position;

                        currentWPUG = currentWP - bb.navMeshLayersDistance;
                        nextWPUG    = nextWP - bb.navMeshLayersDistance;

                        headTrf.LookAt(nextWP, Vector3.up);

                        bb.CalculateWorldExitBezierPoints(headTrf);

                        t = 0;

                        HexagonController hexagon = route.wayPoints[WPIndex + 1].GetComponent <HexagonController>();
                        hexagon.WormEnterExit();

                        if (angryEyes)
                        {
                            angryEyes = false;
                            head.NotWatchingPlayer();
                        }

                        head.animator.SetBool("MouthOpen", true);
                        bb.meteorInmediate = false;

                        subState = SubState.EXITING;
                    }
                    else
                    {
                        elapsedTime = 0;
                        ++WPIndex;
                        currentWP = route.wayPoints[WPIndex].transform.position;
                        head.agent.SetDestination(currentWP);
                    }
                }
            }

            break;

        case SubState.EXITING:
            if (t <= 2)
            {
                shouldMove    = Time.deltaTime * bb.WanderingSettingsPhase.wanderingSpeed;
                actuallyMoved = 0;
                lastPosition  = headTrf.position;
                Vector3 newPos = Vector3.zero;

                if (t >= 1.6f && !exitRumble)
                {
                    exitRumble = true;
                    EnterExitActions();
                }

                while (actuallyMoved < shouldMove && t <= 2)
                {
                    newPos        = bb.GetExitCurvePosition(currentWP, nextWPUG, t);
                    actuallyMoved = (newPos - lastPosition).magnitude;

                    t += Time.deltaTime / duration;
                }
                headTrf.position = newPos;
                headTrf.LookAt(headTrf.position + (headTrf.position - lastPosition));
            }
            else
            {
                SetUndergroundDirection();
                SetHeadUnderground();
                head.animator.SetBool("MouthOpen", false);

                subState = SubState.WAITING_FOR_TAIL;
            }

            break;

        case SubState.WAITING_FOR_TAIL:

            //move head until tail is undeground
            if (!bb.tailReachedMilestone)
            {
                MoveUndergroundDirection();
            }
            else
            {
                bb.applySinMovement = false;

                if (bb.shouldMeteorBeTriggedAfterWandering)
                {
                    return(head.meteorAttackState);
                }
                //If some random condition attack, else new wandering state
                else if (bb.attacksEnabled && bb.BelowAttackSettingsPhase.active &&
                         Random.Range(0f, 1f) <= bb.BelowAttackSettingsPhase.chancesOfBelowAttackAfterWandering / 100)
                {
                    return(head.belowAttackState);
                }
                else
                {
                    SetInitialState();
                }
            }

            break;


        //Failsafe exit
        case SubState.JUMPING:
            //While not again below underground navmesh layer advance
            currentX        += Time.deltaTime * speed;
            lastPosition     = headTrf.position;
            headTrf.position = bb.GetJumpPositionGivenX(currentX);

            headTrf.LookAt(headTrf.position + (headTrf.position - lastPosition), headTrf.up);

            if (!destinyInRange)
            {
                float distanceToDestiny = (headTrf.position - destiny.transform.position).magnitude;
                if (distanceToDestiny <= destinyInRangeDistance ||
                    headTrf.position.y < destiny.transform.position.y)     //Safety check. When jump is too fast distance can never be less than range distance
                {
                    destinyInRange = true;

                    JumpExitActions();

                    destiny.WormEnterExit();
                }
            }

            if (headTrf.position.y < -WormBlackboard.NAVMESH_LAYER_HEIGHT)
            {
                SetHeadUnderground();
                head.animator.SetBool("MouthOpen", false);

                subState = SubState.JUMP_EXITING;
            }
            break;

        case SubState.JUMP_EXITING:
            currentX        += Time.deltaTime * speed;
            lastPosition     = headTrf.position;
            headTrf.position = bb.GetJumpPositionGivenX(currentX);

            headTrf.LookAt(headTrf.position + (headTrf.position - lastPosition));

            if (bb.tailReachedMilestone)
            {
                Vector3 pos = headTrf.position;
                pos.y            = -WormBlackboard.NAVMESH_LAYER_HEIGHT;
                headTrf.position = pos;

                return(head.wanderingState);
            }
            break;

        default:
            break;
        }

        return(null);
    }
    private void Start()
    {
        // initialize all of the property trackers, and add them to the array.
        m_CurrentSkybox = new SkyboxProperties();
        m_CurrentHaze = new HazeProperties();
        m_CurrentBasicFog = new BasicFogProperties();
        m_CurrentFillLight = new BasicLightProperties( lightKit.Find("Fill light") );
        m_CurrentBackLight = new BasicLightProperties( lightKit.Find("Bounce light") );
        m_CurrentKeyLight = new KeyLightProperties( lightKit.Find("Directional light") );
        m_CurrentAmbientLight = new AmbientLightProperties();
        m_CurrentLightKit = GameObject.Find ("MainLightKit").transform;

        m_AtmosphereProperties = new AtmosphereProperties[]{ m_CurrentSkybox, m_CurrentHaze, m_CurrentBasicFog, m_CurrentFillLight, m_CurrentBackLight, m_CurrentKeyLight, m_CurrentAmbientLight };

        // initialize the texture list.
        loadedSkyboxes = new Dictionary<string, Dictionary<string, Texture2D>>();

        // setup the default atmosphere configuration.
        SetupDefaultConfiguration();

        // register for events.
        //		EventHandler.instance.addEventListener( ComplexEventObj.ChangeGridArea, this.gameObject, "OnChangeGridArea" );
        //		EventHandler.instance.addEventListener( BasicEventObj.ToggleThemeRenderSettings, this.gameObject, "OnToggleThemeRenderSettings" );

        // set the default state to 'on'.
        m_CurrentSubState = SubState.Init;
        this.ChangeState( SubState.On ); // this process will trigger all "hasChanged" flags to be set to true.
    }
    public override WormAIBaseState Update()
    {
        if (destiny == null)
        {
            return(head.wanderingState);
        }

        switch (subState)
        {
        case SubState.WARNING_PLAYER:
            headTrf.rotation = Quaternion.RotateTowards(headTrf.rotation, initialRotation, 90 / bb.AboveAttackSettingsPhase.warningTime * Time.deltaTime);

            if (elapsedTime >= bb.AboveAttackSettingsPhase.warningTime)
            {
                head.jumpAttackSoundFx.Play();
                subState = SubState.JUMPING;
            }
            else
            {
                elapsedTime += Time.deltaTime;
            }

            break;

        case SubState.JUMPING:
            //While not again below underground navmesh layer advance
            currentX        += Time.deltaTime * speed;
            lastPosition     = headTrf.position;
            headTrf.position = bb.GetJumpPositionGivenX(currentX);

            headTrf.LookAt(headTrf.position + (headTrf.position - lastPosition), headTrf.up);

            if (rotation < bb.AboveAttackSettingsPhase.selfRotation)
            {
                float angle = bb.AboveAttackSettingsPhase.selfRotation / bb.AboveAttackSettingsPhase.jumpDuration * Time.deltaTime;
                headTrf.Rotate(new Vector3(0, 0, angle));
                rotation += angle;
            }

            if (!destinyInRange)
            {
                float distanceToDestiny = (headTrf.position - destiny.transform.position).magnitude;
                if (distanceToDestiny <= destinyInRangeDistance ||
                    headTrf.position.y < destiny.transform.position.y)     //Safety check. When jump is too fast distance can never be less than range distance
                {
                    destinyInRange = true;
                    AttackActions();
                    destiny.WormAboveAttackStart();
                }
            }

            if (headTrf.position.y < -WormBlackboard.NAVMESH_LAYER_HEIGHT)
            {
                SetHeadUnderground();
                subState = SubState.EXITING;
            }
            break;

        case SubState.EXITING:
            currentX        += Time.deltaTime * speed;
            lastPosition     = headTrf.position;
            headTrf.position = bb.GetJumpPositionGivenX(currentX);

            headTrf.LookAt(headTrf.position + (headTrf.position - lastPosition));

            if (bb.tailReachedMilestone)
            {
                Vector3 pos = headTrf.position;
                pos.y            = -WormBlackboard.NAVMESH_LAYER_HEIGHT;
                headTrf.position = pos;

                return(head.wanderingState);
            }
            break;

        default:
            break;
        }

        return(null);
    }
Example #29
0
    //private void LateUpdate()
    //{
    //    if (Input.GetMouseButtonDown(0))
    //    {

    //        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    //        RaycastHit hit;
    //        if (Physics.Raycast(ray, out hit,100))
    //        {
    //            print(hit.transform.name);
    //        }
    //    }

    //}
    void Update()
    {
        if (currentState == State.Playing)
        {
            return;
        }
        switch (currentState)
        {
        case State.GameTips:
        {
            if (currentSubState == SubState.Enter)
            {
                currentSubState = SubState.Update;
#if UNITY_EDITOR
                //如果EDITOR模式就跳过之前的
                sliderView.gameObject.SetActive(true);
                sliderView.ShowSlider();
#else
                uiTip.gameObject.SetActive(true);
                uiTip.Show(() =>
                    {
                        uiTip.Hide(() =>
                        {
                            uiTip.gameObject.SetActive(false);
                            sliderView.gameObject.SetActive(true);
                            sliderView.ShowSlider();
                        });
                        sliderView.gameObject.SetActive(true);
                    });
#endif

                JumpToState(State.CheckExtractResource);
            }
            break;
        }

        case State.CheckExtractResource:
        {
            if (currentSubState == SubState.Enter)
            {
                currentSubState = SubState.Update;

                sliderView.Reset("解压文件中", () =>
                    {
                        StopCoroutine(coroutine);
                        JumpToState(State.UpdateResourceFromNet);
                    });
                coroutine = StartCoroutine(Extract(sliderView.SetData));
            }
            break;
        }

        case State.UpdateResourceFromNet:
        {
            if (currentSubState == SubState.Enter)
            {
                currentSubState = SubState.Update;
                sliderView.Reset("下载文件中", () =>
                    {
                        StopCoroutine(coroutine);
                        JumpToState(State.InitAssetBundle);
                    });
                coroutine = StartCoroutine(Download(sliderView.SetData));
            }
            break;
        }

        case State.InitAssetBundle:
        {
            if (currentSubState == SubState.Enter)
            {
                currentSubState = SubState.Update;
                sliderView.Reset("初始化中", () =>
                    {
                        StopCoroutine(coroutine);
                        JumpToState(State.StartLogin);
                    });
                coroutine = StartCoroutine(GameInit(sliderView.SetData));
            }
            break;
        }

        case State.StartLogin:
        {
            if (currentSubState == SubState.Enter)
            {
                currentSubState = SubState.Update;
                LuaBehaviour.Instance.LuaEnvInit();
                NPCManager.Instance.NpcInit();
                sliderView.OnSliderHided += () =>
                {
                    LuaBehaviour.Instance.CallLuaEvent("EnterLogin");

                    //sliderView.Hide();
                };
                sliderView.HideSlider();
            }

            break;
        }
        }
    }
Example #30
0
    void UpdateStates()
    {
        if (playerDistance < activeDistance)
        {
            if (dState == DistanceState.Inactive && sState != SubState.WaitingForReactivation)
            {
                EnableTextAndImage();
            }

            if (playerDistance < switchDistance)
            {
                dState = DistanceState.Active;
            }
            else
            {
                dState = DistanceState.Middle;
            }
        }
        else
        {
            if (dState != DistanceState.Inactive)
            {
                DisableTextAndImage();
            }

            dState = DistanceState.Inactive;
        }

        if (dState == DistanceState.Active)
        {
            switch (sState)
            {
            case SubState.Writing:
                if (iLetter >= fileText[iParagraph].Length)
                {
                    sState = SubState.WaitingForNext;
                }
                else if (ControlManager.Instance.GetButtonDown("Submit"))
                {
                    iLetter = fileText[iParagraph].Length;
                    sState  = SubState.WaitingForNext;
                }
                else
                {
                    iLetter++;
                }

                break;

            case SubState.WaitingForNext:

                if (ControlManager.Instance.GetButtonDown("Submit"))
                {
                    NextDialogue();
                }

                break;

            case SubState.WaitingForReactivation:

                if (ControlManager.Instance.GetButtonDown("Submit"))
                {
                    RestartDialogue();
                }

                break;

            default:
                break;
            }
        }
    }
    void DoWalk()
    {
        if (subState == SubState.Init)
        {
            subState   = SubState.Active;
            shootPower = 3;
        }
        if (subState == SubState.Active)
        {
            Debug.Log("HIT " + rayHit.collider.tag);
            isMove     = true;
            moveTarget = rayHit.point + new Vector3(0.0f, 0.0f, 0.0f);
            if (rayHit.collider.tag == "Object")
            {
                Debug.Log("HIT OBJECT" + rayHit.collider.gameObject.name);
                currentObject = rayHit.collider.gameObject;
                playerState   = PlayerState.Shoot;
                subState      = SubState.Init;
            }
            else
            {
                cursor.gameObject.SetActive(true);
                cursor.gameObject.transform.position = moveTarget + new Vector3(0, 0.1f, 0);
            }

            if (isMove)
            {
                //transform.rotation = Quaternion.RotateTowards(transform.rotation,Quaternion.Euler(moveTarget), Time.deltaTime * 0.1f);

                if (haveBall)
                {
                    agent.speed       = speed * 1.5f;
                    agent.destination = Ball.instance.gameObject.transform.position;
                }
                else
                {
                    if (BolHelper.Distance(this.gameObject, Ball.instance.gameObject) < 0.5f)
                    {
                        haveBall = true;
                        Ball.instance.currentPlayer = this;
                    }
                    agent.speed       = speed;
                    agent.destination = moveTarget;
                }
                distance = Vector3.Distance(transform.position, moveTarget);
                //if(agent.remainingDistance < 0.01f){
                if (distance < 0.1f)
                {
                    cursor.gameObject.SetActive(false);
                    isMove      = false;
                    playerState = PlayerState.Idle;
                    subState    = SubState.Init;
                }
            }
        }
        if (subState == SubState.Deactive)
        {
        }
        if (subState == SubState.Finish)
        {
        }
    }
Example #32
0
	void DoCeleb3(){
		
		if (substate == SubState.Init) {
			
			substate = SubState.Active;
		}
		
		if (substate == SubState.Active) { 
			
		}
		
		if (substate == SubState.Deactive) {
			
		}
		
		if (substate == SubState.Finish) {
			
		}
	}
Example #33
0
 void JumpToState(State new_state)
 {
     cur_state     = new_state;
     cur_sub_state = SubState.Enter;
     Debug.Log("new_state : " + new_state.ToString());
 }
        protected void smSendHandshake()
        {
            /* Implements RFC6455 websocket specification
             *
             *  GET <target path> HTTP/1.1\r\n
             *  Host: <target web address>\r\n
             *  Upgrade: websocket\r\n
             *  Connection: upgrade\r\n
             *  Origin: <optional name of origin>\r\n
             *  Sec-WebSocket-Version: 13\r\n
             *  Sec-WebSocket-Extensions: <zero or more websocket extensions>\r\n
             *  Sec-WebSocket-Protocol: <zero or more higher level protocols>\r\n
             *  Sec-WebSocket-Key: <generated key>\r\n
             *  \r\n
             *
            */

            // create security key
            this.securityKey = this.GetSecurityKey();

            // create headers
            StringBuilder sb = new StringBuilder();
            sb.Append(string.Concat("GET ", this.serverUri.GetPathAndQuery(), " HTTP/1.1", WSConst.HeaderEOL));
            sb.Append(string.Concat("Host: ", this.serverUri.Host, WSConst.HeaderEOL));
            sb.Append(string.Concat("Upgrade: webSocket", WSConst.HeaderEOL));
            sb.Append(string.Concat("Connection: upgrade", WSConst.HeaderEOL));
            if (this.origin.Length > 0)
            {
                sb.Append(string.Concat("Origin: ", this.origin, WSConst.HeaderEOL));
            }
            if (this.extensions.Length > 0)
            {
                sb.Append(string.Concat("Sec-WebSocket-Extensions: ", this.extensions, WSConst.HeaderEOL));
            }
            if (this.subProtocol.Length > 0)
            {
                sb.Append(string.Concat("Sec-WebSocket-Protocol: ", this.subProtocol, WSConst.HeaderEOL));
            }
            sb.Append(string.Concat("Sec-WebSocket-Version: ", WSConst.ProtocolVersion, WSConst.HeaderEOL));
            sb.Append(string.Concat("Sec-WebSocket-Key: ", this.securityKey, WSConst.HeaderEOL));
            sb.Append(WSConst.HeaderEOL);
            string headers = sb.ToString();

            // send headers
            byte[] headerBytes = headers.ToByteArray();
            this.socketStream.Write(headerBytes, 0, headerBytes.Length);

            Logger.WriteDebug(this.loggerID, string.Concat("Handshake sent: ", headers));

            // go to next state
            this.subState = SubState.WaitForHandshake;
        }
Example #35
0
	private void Start(){
		// initialize all of the property trackers, and add them to the array.
		m_CurrentSkybox = new SkyboxProperties();
		m_CurrentHaze = new HazeProperties();
		m_CurrentBasicFog = new BasicFogProperties();
		
		m_AtmosphereProperties = new AtmosphereProperties[]{ m_CurrentSkybox, m_CurrentHaze, m_CurrentBasicFog};

		
		// initialize the texture list.
		loadedSkyboxes = new Dictionary<string, Dictionary<string, Texture2D>>();
		
		// setup the default atmosphere configuration.
		SetupDefaultConfiguration();

		// set the default state to 'on'.
		m_CurrentSubState = SubState.Init;
		this.ChangeState( SubState.On ); // this process will trigger all "hasChanged" flags to be set to true.
	}
        protected void smWaitForHandshake()
        {
            /* Implements RFC6455 websocket specification
            *
            *  HTTP/1.1 101 Switching Protocols\r\n
            *  Upgrade: websocket\r\n
            *  Connection: upgrade\r\n
            *  Sec-WebSocket-Extensions: <zero or more websocket extensions>\r\n
            *  Sec-WebSocket-Protocol: <zero or more higher level protocols>\r\n
            *  Sec-WebSocket-Accept: <response key>\r\n
            *  <other headers, cookies, etc>
            *  \r\n
            *
            */

            int bytesRead = 0;
            this.bytesInBuffer = 0;
            this.posHeaderEOF = 0;
            this.bytesInBuffer = 0;

            // TODO - modify to extract individual headers as they arrive in the buffer
            if (this.socket.Poll(this.waitHandshakeTimeout, SelectMode.SelectRead) == true && this.socket.Available > 0)
            {
                do
                {
                    bytesRead = this.socketStream.Read(this.receiveBuffer, this.bytesInBuffer, this.receiveBuffer.Length - this.bytesInBuffer);
                    if (bytesRead > 0)
                    {
                        this.bytesInBuffer += bytesRead;
                        this.posHeaderEOF = this.receiveBuffer.IndexOf(WSConst.HeaderEOF);
                        if (posHeaderEOF >= 0)
                        {
                            this.LogBufferContent("Handshake received: ", this.receiveBuffer, 0, this.bytesInBuffer);
                            this.subState = SubState.ProcessHandshake;
                            return;
                        }
                    }
                }
                while (this.socket.Available > 0 && this.bytesInBuffer < this.receiveBuffer.Length);
            }

            Logger.WriteError(this.loggerID, "Handshake not received.");
            this.subState = SubState.Failed;
        }
Example #37
0
 // Start is called before the first frame update
 void Start()
 {
     state = SubState.idle;
 }
 private void MeteorRainEnded(EventInfo eventInfo)
 {
     subState = SubState.METEOR_RAIN_ENDED;
 }
        protected void smWaitCloseResponse()
        {
            int bytesRead = 0;
            this.posHeaderEOF = 0;
            this.bytesInBuffer = 0;

            if (this.socket.Poll(this.waitCloseMsgTimeout, SelectMode.SelectRead) == true && this.socket.Available > 0)
            {
                do
                {
                    bytesRead = this.socketStream.Read(this.receiveBuffer, this.bytesInBuffer, this.receiveBuffer.Length - this.bytesInBuffer);
                    if (bytesRead > 0)
                    {
                        this.bytesInBuffer += bytesRead;
                        if (WSFrame.TryParse(this.receiveBuffer, 0, this.bytesInBuffer, this.options.MaxReceiveFrameLength, out this.lastRcvdFrame) == true)
                        {
                            // remove data-frame from buffer
                            Array.Copy(this.receiveBuffer, this.lastRcvdFrame.FrameData.Length, this.receiveBuffer, 0, this.bytesInBuffer - this.lastRcvdFrame.FrameData.Length);
                            this.bytesInBuffer = this.bytesInBuffer - this.lastRcvdFrame.FrameData.Length;

                            // check for close frame
                            if (this.lastRcvdFrame.OpCode == WSFrameType.Close)
                            {
                                this.LogBufferContent("Close frame received: ", this.lastRcvdFrame.FrameData, 0, this.lastRcvdFrame.FrameData.Length);
                                this.subState = SubState.CloseTcpConnection;
                                return;
                            }

                            this.LogBufferContent("Data frame received: ", this.lastRcvdFrame.FrameData, 0, this.lastRcvdFrame.FrameData.Length);
                        }
                    }
                }
                while (this.socket.Available > 0 && this.bytesInBuffer < this.receiveBuffer.Length);
            }

            Logger.WriteError(this.loggerID, "Close frame not received.");
            this.subState = SubState.Failed;
        }
Example #40
0
	void DoShoot(){
		
		if (substate == SubState.Init) {
			substate = SubState.Active;
		}
		
		if (substate == SubState.Active) {
			timer += Time.deltaTime;
			if(timer >= anim.GetClip("Shoot").length -1.7f){

				audioSource.PlayOneShot(shootSFX);
				audioSource.PlayOneShot(grassSFX);
				GameManager.instance.grassFX.Emit(10);
				timer = 0;
				GameState.instance.isShooting = true;
				substate = SubState.Deactive;
			}




		}
		
		if (substate == SubState.Deactive) {
			timer += Time.deltaTime;
			if(timer >= 0.5f){
					
				timer = 0;
				substate = SubState.Finish;
			}
		}
		
		if (substate == SubState.Finish) {

			aiState = AIState.Idle;
			substate = SubState.Init;
		}
	}
 protected void WSStateMachine()
 {
     while (this.runThreadLoop)
     {
         try
         {
             switch (this.state)
             {
                 case WebSocketState.Initialized:
                     // idle
                     this.runStateMachine.WaitOne();	// wait to be signalled
                     break;
                 case WebSocketState.Connecting:
                     // attempt to connect to server
                     this.OnConnectionStateChanged();
                     this.smConnect();
                     break;
                 case WebSocketState.Connected:
                     // receive and parse incoming data
                     this.OnConnectionStateChanged();
                     this.smReceive();
                     break;
                 case WebSocketState.Disconnecting:
                     // disconnect from server
                     this.OnConnectionStateChanged();
                     this.smDisconnect();
                     break;
                 case WebSocketState.Disconnected:
                     // idle
                     this.OnConnectionStateChanged();
                     this.runStateMachine.WaitOne();	// wait to be signalled
                     break;
                 default:
                     // shouldn't get here
                     throw new NotSupportedException("ReadyState " + this.State.ToString() + " is invalid.");
             }
         }
         catch (Exception ex)
         {
             if (this.socketStream != null)
             {
                 this.socketStream.Close();
                 this.socketStream = null;
             }
             if (this.socket != null)
             {
                 this.socket.Close();
                 this.socket = null;
             }
             this.OnError(WSErrorCode.NativeError, ex.Message, ex.StackTrace);
             this.state = WebSocketState.Disconnected;
             this.subState = SubState.Disconnected;
         }
     }
 }
Example #42
0
	void DoStartGame(){
		
		if(substate == SubState.Init){
			DisableAllPanel();
			if(UIManager.instance.state == UIManager.State.Arcade)
				labelText.text = "Ball";
			if(UIManager.instance.state == UIManager.State.TimeAttack)
				labelText.text = "Time";
			if(UIManager.instance.state == UIManager.State.OneBall){
			
			}
			GameObject bgm = GameObject.Find("audioBGM");
			if(bgm)
				Destroy(bgm);
			CloudDataController.instance.SetStat();
			PlayerStatistic.instance.SaveGame();
			StartCoroutine(CloudDataController.instance.PostStats());
			panelStartGame.SetActive(true);
			substate = SubState.Active;
		}
		
		if(substate == SubState.Active){
			substate = SubState.Deactive;
		}
		
		if(substate == SubState.Deactive){
			substate = SubState.Finish;
		}
		
		if(substate == SubState.Finish){
			
		}
		
	}
 /// <summary>
 /// Disconnect - Begins the asynchronous (non-blocking) disconnection process.
 /// </summary>
 /// <param name="statusCode">WebSocket close status code (from RFC6455)</param>
 /// <param name="reason">Optional reason text.</param>
 public void Disconnect(UInt16 statusCode, string reason = null)
 {
     if (this.state == WebSocketState.Initialized)
     {
         this.state = WebSocketState.Disconnected;
         this.subState = SubState.Disconnected;
     }
     else if (this.state == WebSocketState.Connecting || this.state == WebSocketState.Connected)
     {
         Logger.WriteDebug(this.loggerID, "Disconnecting...");
         this.closeStatus = statusCode;
         this.closeReason = reason;
         this.state = WebSocketState.Disconnecting;
         this.subState = SubState.SendCloseFrame;
     }
 }
Example #44
0
	void DoBeginGame(){

		if(substate == SubState.Init){
			if(inGameState == InGameState.BeginGame && !GameState.instance.isFlyBall){ 
				GameManager.instance.EnableControl();
			}
			DisableAllPanel();
			PlayerStatistic.instance.SaveGame();
			panelInGame.SetActive(true);
			substate = SubState.Active;
		
		}
		
		if(substate == SubState.Active){
			//substate = SubState.Deactive;
		}
		
		if(substate == SubState.Deactive){
			substate = SubState.Finish;
		}
		
		if(substate == SubState.Finish){
			
		}
		
	}
 protected void smConnected()
 {
     Logger.WriteDebug(this.loggerID, "Connected");
     this.state = WebSocketState.Connected;
     this.subState = SubState.Connected;
 }
Example #46
0
	void DoLoseGame(){
		
		if(substate == SubState.Init){
			DisableAllPanel();
			PlayerStatistic.instance.SaveGame();
			panelLoseGame.SetActive(true);
		}
		
		if(substate == SubState.Active){
			substate = SubState.Deactive;
		}
		
		if(substate == SubState.Deactive){
			substate = SubState.Finish;
		}
		
		if(substate == SubState.Finish){
			
		}
		
	}
 protected void smDisconnectFailed()
 {
     if (this.socketStream != null)
     {
         this.socketStream.Close();
         this.socketStream = null;
     }
     if (this.socket != null)
     {
         this.socket.Close();
         this.socket = null;
     }
     this.state = WebSocketState.Disconnected;
     this.subState = SubState.Disconnected;
 }
Example #48
0
	void DoGameOver(){
		
		if(substate == SubState.Init){
			CloudDataController.instance.SetStat();
			DisableAllPanel();
			PlayerStatistic.instance.SaveGame();
			panelGameOver.SetActive(true);
		}
		
		if(substate == SubState.Active){
			substate = SubState.Deactive;
		}
		
		if(substate == SubState.Deactive){
			substate = SubState.Finish;
		}
		
		if(substate == SubState.Finish){
			
		}
		
	}
        protected void smProcessHandshake()
        {
            /* Implements RFC6455 websocket specification
             *
             *  HTTP/1.1 101 Switching Protocols\r\n
             *  Upgrade: websocket\r\n
             *  Connection: upgrade\r\n
             *  Sec-WebSocket-Extensions: <zero or more websocket extensions>\r\n
             *  Sec-WebSocket-Protocol: <zero or more higher level protocols>\r\n
             *  Sec-WebSocket-Accept: <response key>\r\n
             *  \r\n
             *
            */

            // get response headers
            ArrayList headers = this.receiveBuffer.Split(WSConst.HeaderEOL, 0, this.posHeaderEOF + WSConst.HeaderEOF.Length, false);

            //  for debugging
            //	this.socketBuffer = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: upgrade\r\nSec-WebSocket-Extensions: ext1, ext3\r\nSec-WebSocket-Protocol: prot2!#%'-_@~$*+.^|\r\nSec-WebSocket-Accept: Kfh9QIsMVZcl6xEPYxPHzW8SZ8w=\r\n\r\n" + "\x81\x53{\"event\":\"pusher:connection_established\",\"data\":\"{\\\"socket_id\\\":\\\"23086.813011\\\"}\"}");
            //	this.bytesInBuffer = this.socketBuffer.Length;
            //	this.posHeaderEOF = this.socketBuffer.IndexOf(WSConstants.HeaderEOF);
            //	ArrayList headers = this.socketBuffer.Split(WSConstants.HeaderEOL, 0, this.posHeaderEOF + WSConstants.HeaderEOF.Length, false);

            // remove headers from socket buffer
            if (this.posHeaderEOF >= 0)
            {
                this.posHeaderEOF += WSConst.HeaderEOF.Length;
                Array.Copy(this.receiveBuffer, this.posHeaderEOF, this.receiveBuffer, 0, this.bytesInBuffer - this.posHeaderEOF);
                this.bytesInBuffer = this.bytesInBuffer - this.posHeaderEOF;
            }

            // log response headers
            if (Logger.GetLogLevel() == LogLevel.Debug)
            {
                for (int i = 0; i < headers.Count; i++)
                {
                    Logger.WriteDebug(this.loggerID, string.Concat("Handshake header: ", headers[i]));
                }
            }

            // validate response headers
            Regex regex = null;
            string header = "";
            bool isDone = false;
            bool responseIsValid = false;
            int headerIndex = 0;
            int step = 0;
            while (!isDone)
            {
                Continue:
                step++;

                switch (step)
                {
                    case 1:
                        // check for response code 101
                        for (headerIndex = 0; headerIndex < headers.Count; headerIndex++)
                        {
                            header = ((string)headers[headerIndex]);
                            regex = new Regex(@"http/\d+\.\d+\s+101", RegexOptions.IgnoreCase);
                            if (regex.IsMatch(header))
                            {
                                headers.RemoveAt(headerIndex);
                                goto Continue;
                            }
                            else
                            {
                                // TODO - process other response codes per RFC2616
                            }
                        }
                        break;
                    case 2:
                        // check for 'upgrade: websocket'
                        for (headerIndex = 0; headerIndex < headers.Count; headerIndex++)
                        {
                            header = ((string)headers[headerIndex]);
                            regex = new Regex(@"upgrade:\s+websocket", RegexOptions.IgnoreCase);
                            if (regex.IsMatch(header))
                            {
                                headers.RemoveAt(headerIndex);
                                goto Continue;
                            }
                        }
                        break;
                    case 3:
                        // check for 'connection: upgrade'
                        for (headerIndex = 0; headerIndex < headers.Count; headerIndex++)
                        {
                            header = ((string)headers[headerIndex]);
                            regex = new Regex(@"connection:\s+upgrade", RegexOptions.IgnoreCase);
                            if (regex.IsMatch(header))
                            {
                                headers.RemoveAt(headerIndex);
                                goto Continue;
                            }
                        }
                        break;
                    case 4:
                        // check that 'sec-websocket-extensions:' list is valid
                        // TODO - validate extensions header
                        goto Continue;
                        /*
                        if (this.extensionList.Length == 0)
                        {
                            goto Continue;
                        }
                        for (headerIndex = 0; headerIndex < headers.Count; headerIndex++)
                        {
                            header = ((string)headers[headerIndex]);
                            regex = new Regex(@"(sec-websocket-extensions):\s+(.+)", RegexOptions.IgnoreCase);
                            Match match = regex.Match(header);
                            if (match.Success && this.IsValidExtensionsResponse(match.Groups[2].Value))
                            {
                                headers.RemoveAt(headerIndex);
                                goto Continue;
                            }
                        }
                        break;
                        */
                    case 5:
                        // check that 'sec-websocket-protocol:' list is valid
                        if (this.subProtocol.Length == 0)
                        {
                            goto Continue;
                        }
                        for (headerIndex = 0; headerIndex < headers.Count; headerIndex++)
                        {
                            header = ((string)headers[headerIndex]);
                            regex = new Regex(@"sec-websocket-protocol:\s+([A-Za-z0-9!#%'-_@~\$\*\+\.\^\|]+$)", RegexOptions.IgnoreCase);
                            Match match = regex.Match(header);
                            if (match.Success && this.IsValidProtocolResponse(match.Groups[1].Value))
                            {
                                headers.RemoveAt(headerIndex);
                                goto Continue;
                            }
                        }
                        break;
                    case 6:
                        // check that 'sec-websocket-accept: secKey' is valid
                        for (headerIndex = 0; headerIndex < headers.Count; headerIndex++)
                        {
                            header = ((string)headers[headerIndex]);
                            regex = new Regex(@"sec-websocket-accept:\s+([A-Za-z0-9+/=]+)", RegexOptions.IgnoreCase);
                            Match match = regex.Match(header);
                            if (match.Success && this.IsValidSecurityResponse(match.Groups[1].Value))
                            {
                                headers.RemoveAt(headerIndex);
                                goto Continue;
                            }
                        }
                        break;
                    case 7:
                        // TODO - check for cookie header
                        goto Continue;
                    case 8:
                        // done
                        responseIsValid = true;
                        break;
                }

                // stop looping
                isDone = true;
            }

            // TODO - cleanup headers list
            headers.Clear();
            headers = null;

            if (!responseIsValid)
            {
                Logger.WriteError(this.loggerID, "Handshake response is invalid");
                this.subState = SubState.Failed;
                return;
            }

            // go to next state
            this.subState = SubState.Connected;
        }
Example #50
0
	void DoSplash(){

		if(substate == SubState.Init){
			DisableAllPanel();
			panelSplash.SetActive(true);
			substate = SubState.Active;
		}

		if(substate == SubState.Active){
			substate = SubState.Deactive;
		}

		if(substate == SubState.Deactive){
			substate = SubState.Finish;
		}

		if(substate == SubState.Finish){
			
		}

	}
 protected void smSendCloseFrame()
 {
     WSFrame wsFrame = WSFrame.CreateFrame(WSFrameType.Close, this.options.MaskingEnabled, ArrayUtil.Concat(this.closeStatus, this.closeReason));
     this.LogBufferContent("Sending close frame: ", wsFrame.FrameData, 0, wsFrame.FrameData.Length);
     this.socketStream.Write(wsFrame.FrameData, 0, wsFrame.FrameData.Length);
     this.subState = SubState.WaitForCloseResponse;
 }
Example #52
0
 public bool IsState(SubState state)
 {
     return(ActiveState == state);
 }
        //------------------------------------------------------------------------------
        // Function: GameState
        // Author: Neil Holmes & Andrew Green
        // Summary: main constructor
        //------------------------------------------------------------------------------
        public GameState(Game game, PlayerIndex? controllingPlayer)
        {
            // store a reference to the game that owns this game state
            this.game = game;

            // get the display manager service
            displayManager = (DisplayManager)game.Services.GetService(typeof(DisplayManager));

            // get the game state manager service
            gameStateManager = (GameStateManager)game.Services.GetService(typeof(GameStateManager));

            // get the game timer system service
            timerSystem = (TimerSystem)game.Services.GetService(typeof(TimerSystem));

            // get the game input manager service
            inputManager = (InputManager)game.Services.GetService(typeof(InputManager));

            // store the player that has control of this game state
            this.controllingPlayer = controllingPlayer;

            // set the default sub-state of the state to be transitioning on
            subState = SubState.TransitionOn;

            // by default, transition has not finished
            transitionAmount = 1.0f;

            // by default, we are not exiting ;)
            isExiting = false;
        }
Example #54
0
    //private void LateUpdate()
    //{
    //    if (Input.GetMouseButtonDown(0))
    //    {

    //        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    //        RaycastHit hit;
    //        if (Physics.Raycast(ray, out hit,100))
    //        {
    //            print(hit.transform.name);
    //        }
    //    }

    //}
    void Update()
    {
        if (currentState == State.Playing)
        {
            return;
        }
        switch (currentState)
        {
        case State.GameTips:
        {
            if (currentSubState == SubState.Enter)
            {
                currentSubState = SubState.Update;
#if UNITY_EDITOR
                //如果EDITOR模式就跳过之前的
                sliderView.gameObject.SetActive(true);
                sliderView.ShowSlider();
                obj.SetActive(true);
#else
                uiTip.gameObject.SetActive(true);
                Camera.main.gameObject.SetActive(true);
                uiTip.Show(() =>
                    {
                        obj.SetActive(true);
                        uiTip.Hide(() =>
                        {
                            uiTip.gameObject.SetActive(false);
                            sliderView.gameObject.SetActive(true);
                            sliderView.ShowSlider();
                        });
                        sliderView.gameObject.SetActive(true);
                    });
#endif
                sliderView.OnSliderShowed += () =>
                {
                    JumpToState(State.CheckExtractResource);
                };
            }
            break;
        }

        case State.CheckExtractResource:
        {
            if (currentSubState == SubState.Enter)
            {
                currentSubState = SubState.Update;

                sliderView.Reset("检查文件中", SliderMode.Fraction, () =>
                    {
                        StopCoroutine(coroutine);
                        JumpToState(State.UpdateResourceFromNet);
                    });
                coroutine = StartCoroutine(gameObject.GetComponent <HotFixManager>().Check(sliderView.SetData));
            }
            break;
        }

        case State.UpdateResourceFromNet:
        {
            if (currentSubState == SubState.Enter)
            {
                currentSubState = SubState.Update;
                sliderView.Reset("下载文件中", SliderMode.Download, () =>
                    {
                        StopCoroutine(coroutine);
                        GetComponent <HotFixManager>().UpdateAssetInfo();
                        JumpToState(State.InitAssetBundle);
                    });
                coroutine = StartCoroutine(gameObject.GetComponent <HotFixManager>().Download(sliderView.AddData));
            }
            break;
        }

        case State.InitAssetBundle:
        {
            if (currentSubState == SubState.Enter)
            {
                currentSubState = SubState.Update;
                sliderView.Reset("初始化中", SliderMode.Percent, () =>
                    {
                        StopCoroutine(coroutine);
                        JumpToState(State.StartLogin);
                    });
                coroutine = StartCoroutine(GameInit(sliderView.AddData));
            }
            break;
        }

        case State.StartLogin:
        {
            if (currentSubState == SubState.Enter)
            {
                currentSubState = SubState.Update;
                LuaBehaviour.Instance.LuaEnvInit();
                this.gameObject.AddComponent <GameObjectManager>();
                this.gameObject.AddComponent <EntityManager>();
                NPCManager.Instance.NpcInit();
                sliderView.OnSliderHided += () =>
                {
                    LuaBehaviour.Instance.CallLuaEvent("EnterLogin");
                };
                sliderView.HideSlider();
            }

            break;
        }
        }
    }
Example #55
0
 void JumpToState(State state)
 {
     currentState    = state;
     currentSubState = SubState.Enter;
     Debug.Log($"GameState jump to {currentState}");
 }
        private void Update()
        {
            if (cur_state == State.Playing)
            {
                return;
            }

            switch (cur_state)
            {
            case State.None:
                break;

            case State.CheckExtractResource:
                if (cur_sub_state == SubState.Enter)
                {
                    cur_sub_state = SubState.Update;
                    Debug.LogWarning("首次解压游戏数据(不消耗流量)");
                    //loadingView.SetData(0.0f, "首次解压游戏数据(不消耗流量)");
                    this.gameObject.AddComponent <AssetHotFixManager>();
                    AssetHotFixManager.Instance.CheckExtractResource(delegate(float percent)
                    {
                        Debug.LogWarning("首次解压游戏数据(不消耗流量)进度:" + 0.3f * percent);
                        //loadingView.SetData(0.3f * percent, "首次解压游戏数据(不消耗流量)");
                    }, delegate()
                    {
                        Debug.Log("Main.cs CheckExtractResource OK!!!");
                        JumpToState(State.UpdateResourceFromNet);
                    });
                }
                break;

            case State.UpdateResourceFromNet:
                if (cur_sub_state == SubState.Enter)
                {
                    cur_sub_state = SubState.Update;
                    //loadingView.SetData(0.3f, "从服务器下载最新的资源文件...");
                    Debug.LogWarning("从服务器下载最新的资源文件...");
                    AssetHotFixManager.Instance.UpdateResource(delegate(float percent, string tip)
                    {
                        Debug.LogWarning(string.Format("进度:{0} - 提示语 {1}", 0.3f + 0.5f * percent, tip));
                        //loadingView.SetData(0.3f + 0.5f * percent, tip);
                    }, delegate(string result)
                    {
                        if (result == "")
                        {
                            Debug.Log("Main.cs UpdateResourceFromNet OK!!!");
                        }
                        else
                        {
                            Debug.Log(result);
                        }
                        JumpToState(State.InitAssetBundle);
                    });
                }
                break;

            case State.InitAssetBundle:
                if (cur_sub_state == SubState.Enter)
                {
                    cur_sub_state = SubState.Update;
                    //loadingView.SetData(0.8f, "初始化游戏资源...");
                    Debug.LogWarning("InitAssetBundle:初始化游戏资源...");
                    JumpToState(State.StartLogin);
                }
                break;

            case State.StartLogin:
                if (cur_sub_state == SubState.Enter)
                {
                    cur_sub_state = SubState.Update;
                    Debug.LogWarning("StartLogin:初始化游戏资源完毕...");
                    //loadingView.SetData(1, "初始化游戏资源完毕");
                    //XLuaManager.Instance.InitLuaEnv();
                    // loadingView.SetActive(false, 0.5f);
                    //XLuaManager.Instance.StartLogin(delegate ()
                    //{
                    //    Debug.Log("Main.cs XLuaManager StartLogin OK!!!");
                    JumpToState(State.StartGame);

                    XLuaResourceManager.Instance().OnInitialized(AppConst.AssetDir, delegate()
                    {
                        Debug.Log("AssetBundleManifest 加载完成");
                        UnltyLuaSceneManager.Instance.LoadScene(SceneEnem.MAIN);
                    });

                    //});
                }
                break;

            case State.StartGame:
                Debug.LogWarning("StartGame:开始游戏...");
                JumpToState(State.Playing);
                break;

            case State.Playing:


                break;

            default:
                break;
            }
        }