Esempio n. 1
0
    private void Start()
    {
        // Cache transform
        trans = transform;
        // Cache & set up rigidbody
        rb             = GetComponent <Rigidbody>();
        rb.drag        = 0;
        rb.useGravity  = false;
        rb.isKinematic = false;

        // Bail out if we don't have an object to orbit around
        if (orbitAround == null)
        {
            Debug.LogWarning("Satellite has no object to orbit around");
            return;
        }

        // Update the ellipse with initial value
        if (ellipse == null)
        {
            Reset();
        }
        ellipse.Update(orbitAround.position, transform.position, apsisDistance, circularOrbit);

        // Calculate starting orbit state
        orbitState = new OrbitState(startingAngle, this, ellipse);

        // Position the orbiter
        trans.position = ellipse.GetPosition(startingAngle, orbitAround.position);

        // Add starting velocity
        rb.AddForce(orbitState.velocity, ForceMode.VelocityChange);
        StartCoroutine("Orbit");
    }
 public override void OnHit()
 {
     if (moonState == OrbitState.shooting)
     {
         moonState = OrbitState.retracting;
     }
 }
Esempio n. 3
0
 // Use this for initialization
 void Awake()
 {
     attackState = new AttackState(this);
     chaseState  = new ChaseState(this);
     evadeState  = new EvadeState(this);
     orbitState  = new OrbitState(this);
 }
Esempio n. 4
0
 protected override void OnStateEntry(Entity host, RealmTime time, ref object state)
 {
     state = new OrbitState
     {
         Speed  = speed + speedVariance * (float)(Random.NextDouble() * 2 - 1),
         Radius = radius + radiusVariance * (float)(Random.NextDouble() * 2 - 1)
     };
 }
Esempio n. 5
0
 protected override void OnStateEntry(Entity host, RealmTime time, ref object state)
 {
     state = new OrbitState
     {
         Speed  = (speed - (speed * 2.5f / (time.TickCount / (time.TotalElapsedMs / 1000f))) + speedVariance * (float)(Random.NextDouble() * 2 - 1)),
         Radius = radius + radiusVariance * (float)(Random.NextDouble() * 2 - 1)
     };
 }
Esempio n. 6
0
 protected override void OnStateEntry(Entity host, RealmTime time, ref object state)
 {
     state = new OrbitState
     {
         Speed  = speed,
         Radius = radius
     };
 }
Esempio n. 7
0
 protected override void OnStateEntry(Entity host, RealmTime time, ref object state)
 {
     state = new OrbitState
     {
         Speed = speed + speedVariance*(float) (Random.NextDouble()*2 - 1),
         Radius = radius + radiusVariance*(float) (Random.NextDouble()*2 - 1)
     };
 }
    private void ShootFragment(Rigidbody2D frag, Collider2D fragCollider, Vector2 startPos)
    {
        switch (asteroidState)
        {
        case OrbitState.orbit:
        {
            if (!frag.isKinematic)
            {
                frag.velocity           = Vector2.zero;
                frag.transform.position = origin.position + startPos.y * frag.transform.up + startPos.x * frag.transform.right;         //Reset the position in case it overshot the minDistance
                frag.isKinematic        = true;
                fragCollider.enabled    = false;
            }
            break;
        }

        case OrbitState.shooting:
        {
            if ((origin.position - frag.transform.position).magnitude < maxDistance)
            {
                //If the moon is below maxDistance it gets shot further
                frag.velocity = -(origin.position - frag.transform.position).normalized * punchSpeed;
            }
            else
            {
                //If the moon has reached maxDistance it starts retracting
                asteroidState = OrbitState.retracting;
            }
            break;
        }

        case OrbitState.retracting:
        {
            if ((origin.position - frag.transform.position).magnitude > Mathf.Abs(startPos.magnitude))
            {
                //If the moon is above minDistance it keeps retracting
                frag.velocity = (origin.position - frag.transform.position).normalized * retractSpeed;
            }
            else
            {
                //If the moon has reached minDistance stop it and set it to kinematic
                frag.velocity           = Vector2.zero;
                frag.transform.position = origin.position + startPos.y * frag.transform.up + startPos.x * frag.transform.right;         //Reset the position in case it overshot the minDistance
                asteroidState           = OrbitState.orbit;
                frag.isKinematic        = true;
                fragCollider.enabled    = false;
            }
            break;
        }
        }
    }
Esempio n. 9
0
        protected override void TickCore(Entity host, RealmTime time, ref object state)
        {
            //var en = host.GetNearestEntity(20, null);
            //var player = en as Player;

            //if (en == null)
            //{
            //    return;
            //}

            OrbitState s = (OrbitState)state;

            Status = CycleStatus.NotStarted;

            if (host.HasConditionEffect(ConditionEffectIndex.Paralyzed))
            {
                return;
            }

            Entity entity = host.GetNearestEntity(acquireRange, target);

            if (entity != null)
            {
                double angle;
                if (host.Y == entity.Y && host.X == entity.X) //small offset
                {
                    angle = Math.Atan2(host.Y - entity.Y + (Random.NextDouble() * 2 - 1),
                                       host.X - entity.X + (Random.NextDouble() * 2 - 1));
                }
                else
                {
                    angle = Math.Atan2(host.Y - entity.Y, host.X - entity.X);
                }
                float angularSpd = host.GetSpeed(s.Speed) / s.Radius;
                angle -= angularSpd * (time.thisTickTimes / 1000f);

                double  x    = entity.X + Math.Cos(angle) * radius;
                double  y    = entity.Y + Math.Sin(angle) * radius;
                Vector2 vect = new Vector2((float)x, (float)y) - new Vector2(host.X, host.Y);
                vect.Normalize();
                vect *= host.GetSpeed(s.Speed) * (time.thisTickTimes / 1000f);

                host.ValidateAndMove(host.X + vect.X, host.Y + vect.Y);
                host.UpdateCount++;

                Status = CycleStatus.InProgress;
            }

            state = s;
        }
Esempio n. 10
0
        protected override void TickCore(Entity host, RealmTime time, ref object state)
        {
            OrbitState s = (OrbitState)state;

            Status = CycleStatus.NotStarted;

            if (host.HasConditionEffect(ConditionEffectIndex.Paralyzed))
            {
                return;
            }

            Entity entity = host.GetNearestEntity(acquireRange, target);

            if (entity != null)
            {
                double angle;
                if (host.Y == entity.Y && host.X == entity.X)
                {
                    angle = Math.Atan2(host.Y - entity.Y + (Random.NextDouble() * 2 - 1), host.X - entity.X + (Random.NextDouble() * 2 - 1));
                }
                else
                {
                    angle = Math.Atan2(host.Y - entity.Y, host.X - entity.X);
                }

                float angularSpd = host.GetSpeed(s.Speed, time) / s.Radius;

                angle += angularSpd;

                double x = entity.X + (_ == 0 ? Math.Cos(angle) * radius : Math.Sin(angle) * radius);
                double y = entity.Y + (_ == 0 ? Math.Sin(angle) * radius : Math.Cos(angle) * radius);

                Vector2 vect = new Vector2((float)x, (float)y) - new Vector2(host.X, host.Y);

                vect.Normalize();
                vect *= host.GetSpeed(s.Speed, time);

                host.ValidateAndMove(host.X + vect.X, host.Y + vect.Y);
                host.UpdateCount++;

                Status = CycleStatus.InProgress;
            }

            state = s;
        }
Esempio n. 11
0
    void Start()
    {
        //Make sure all components are initialized first
        this.Anim          = this.GetComponent <Animator>();
        this.Rb            = this.GetComponent <Rigidbody>();
        this.PlayerCol     = this.GetComponent <CapsuleCollider>();
        this.Cam           = this.transform.parent.GetComponentInChildren <Camera>();
        this.Interactables = new List <Interactable>();
        this.Particle      = this.GetComponentInChildren <ParticleSystem>();
        this.Audio         = this.GetComponent <AudioSource>();

        //Then state info
        this.SetState(state = new OrbitState(this));
        this.isVulnerable   = true;
        this.layerMask      = LayerMask.GetMask("Ground");

        GetMaterialsForDamageFlicker();
    }
Esempio n. 12
0
        protected override void OnStateEntry(realm.Entity host, realm.RealmTime time, ref object state)
        {
            int orbitDir;

            if (orbitClockwise == null)
            {
                orbitDir = (Random.Next(1, 3) == 1) ? 1 : -1;
            }
            else
            {
                orbitDir = ((bool)orbitClockwise) ? 1 : -1;
            }

            state = new OrbitState()
            {
                Speed     = speed + speedVariance * (float)(Random.NextDouble() * 2 - 1),
                Radius    = radius + radiusVariance * (float)(Random.NextDouble() * 2 - 1),
                Direction = orbitDir
            };
        }
    public override bool Shoot(bool isFirePressed)
    {
        if (isFirePressed && canAttack && moonState == OrbitState.orbit && !fireHeld)
        {
            fireHeld  = true;
            moonState = OrbitState.shooting;
            for (int i = 0; i < weaponParts.Length; i++)
            {
                weaponParts[i].isKinematic = false; //Unlock the moons position
                weaponColliders[i].enabled = true;
            }
        }
        //Check for Trigger Release
        //else if (!isFirePressed && moonState == OrbitState.shooting)
        //{
        //    //In case the moon is mid-punch, retract it
        //    moonState = OrbitState.retracting;
        //}

        if (!isFirePressed && fireHeld)
        {
            fireHeld = false;
        }

        for (int i = 0; i < weaponParts.Length; i++)
        {
            if (weaponColliders != null)
            {
                ShootFragment(weaponParts[i], weaponColliders[i], weaponMinPos[i]);
            }
        }

        if (moonState == OrbitState.orbit)
        {
            return(true);
        }
        else
        {
            return(false);
        }
    }
Esempio n. 14
0
        protected override void TickCore(Entity host, RealmTime time, ref object state)
        {
            OrbitState s = (OrbitState)state;

            Status = CycleStatus.NotStarted;

            if (host.HasConditionEffect(ConditionEffects.Paralyzed))
            {
                return;
            }

            var entity = host.AttackTarget ?? host.GetNearestEntity(acquireRange, target);

            if (entity != null)
            {
                double angle;
                if (host.Y == entity.Y && host.X == entity.X)//small offset
                {
                    angle = Math.Atan2(host.Y - entity.Y + (Random.NextDouble() * 2 - 1), host.X - entity.X + (Random.NextDouble() * 2 - 1));
                }
                else
                {
                    angle = Math.Atan2(host.Y - entity.Y, host.X - entity.X);
                }
                var angularSpd = s.Direction * host.GetSpeed(s.Speed) / s.Radius;
                angle += angularSpd * (time.ElaspedMsDelta / 1000f);

                double  x    = entity.X + Math.Cos(angle) * s.Radius;
                double  y    = entity.Y + Math.Sin(angle) * s.Radius;
                Vector2 vect = new Vector2((float)x, (float)y) - new Vector2(host.X, host.Y);
                vect.Normalize();
                vect *= host.GetSpeed(s.Speed) * (time.ElaspedMsDelta / 1000f);

                host.ValidateAndMove(host.X + vect.X, host.Y + vect.Y);

                Status = CycleStatus.InProgress;
            }

            state = s;
        }
Esempio n. 15
0
        protected override void TickCore(Entity host, RealmTime time, ref object state)
        {
            OrbitState s = (OrbitState)state;

            if (host.HasConditionEffect(ConditionEffectIndex.Paralyzed))
            {
                return;
            }

            Player entity = host.GetPlayerOwner();

            if (entity != null)
            {
                double angle;
                if (host.Y == entity.Y && host.X == entity.X)     //small offset
                {
                    angle = Math.Atan2(host.Y - entity.Y + (Random.NextDouble() * 2 - 1),
                                       host.X - entity.X + (Random.NextDouble() * 2 - 1));
                }
                else
                {
                    angle = Math.Atan2(host.Y - entity.Y, host.X - entity.X);
                }
                float angularSpd = host.GetSpeed(s.Speed) / s.Radius;
                angle += angularSpd * (time.thisTickTimes / 1000f);

                double  x    = entity.X + Math.Cos(angle) * radius;
                double  y    = entity.Y + Math.Sin(angle) * radius;
                Vector2 vect = new Vector2((float)x, (float)y) - new Vector2(host.X, host.Y);
                vect.Normalize();
                vect *= host.GetSpeed(s.Speed) * (time.thisTickTimes / 1000f);

                host.ValidateAndMove(host.X + vect.X, host.Y + vect.Y);
                host.UpdateCount++;
            }
            state = s;
        }
Esempio n. 16
0
    void Update()
    {
        if (fc)
        {
            if (fc.interplanetaryFlight && Input.GetButtonDown("Orbit"))
            {
                fc.interplanetaryFlight = false;
                entryVelocity           = fc.rb.velocity;
                shipEntryHeading        = entryVelocity.normalized;

                angular = Quaternion.FromToRotation(
                    fc.transform.forward,
                    shipEntryHeading
                    ).eulerAngles.magnitude;

                //Debug.Log(angular);

                fc.rb.Sleep();

                Vector3 planetToShipDirection = (fc.transform.position - planet.position);

                flightAltitude = Vector3.Dot(planetToShipDirection, -1f * Vector3.forward);

                planetToShipDirection = planetToShipDirection.normalized;
                angularSpeed          = 360f * entryVelocity.magnitude / (2 * Mathf.PI * flightAltitude);
                axis = Vector3.Cross(planetToShipDirection, shipEntryHeading);

                orbitState = OrbitState.Entering;
            }
            else if (Input.GetButtonUp("Orbit") && !fc.interplanetaryFlight)
            {
                orbitState = OrbitState.Exiting;
            }

            if (!fc.interplanetaryFlight)
            {
                angularSpeed = Mathf.Lerp(angularSpeed, targetAngularSpeed, attackSpeed * Time.deltaTime);
                float angle = angularSpeed * Time.deltaTime;


                Quaternion rotation = Quaternion.Euler(angle * axis);

                Vector3 planetToShipDirection = (fc.transform.position - planet.position).normalized;
                Vector3 curDirection          = rotation * planetToShipDirection;
                tangent = Vector3.Cross(axis, planetToShipDirection);

                fc.transform.position = planet.transform.position + flightAltitude * curDirection;
                fc.transform.Rotate(axis, angle, Space.World);

                //Angular rotation
                angular += Input.GetAxis("Horizontal");
                fc.transform.rotation = Quaternion.LookRotation(tangent, planetToShipDirection);
                fc.transform.Rotate(planetToShipDirection, angular, Space.World);

                //Orbit axis rotation
                float axisMomentum = Input.GetAxis("Vertical") *
                                     Vector3.Dot(fc.transform.forward, tangent);


                if (orbitState == OrbitState.Entering)
                {
                    orbitState = OrbitState.Orbiting;
                }
                else if (orbitState == OrbitState.Exiting && InOrbitExitArea)
                {
                    fc.LeaveOrbit(angularSpeed * 2 * Mathf.PI * flightAltitude / 360f * shipEntryHeading);
                }
            }
        }
    }
Esempio n. 17
0
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here
            kbState = Keyboard.GetState();

            #region Song stuff
            // play the current song
            if (playing == false)
            {
                currentSong.Play();
                songTime = 0;
                playing = true;
            }

            // increment song timer
            songTime += gameTime.ElapsedGameTime.TotalMilliseconds;

            // upon completing the song, pick a new one
            if (songTime >= (currentSong.Duration.TotalMilliseconds - Constants.SONG_OFFSET))
            {
                playing = false;
                if (currentSong == sounds["long collision"])
                {
                    nextSong = ranSong.Next(7);
                    switch (nextSong)
                    {
                        #region switch songs
                        case 0:
                            currentSong = sounds["base"];
                            break;
                        case 1:
                            currentSong = sounds["base"];
                            break;
                        case 2:
                            currentSong = sounds["pious"];
                            break;
                        case 3:
                            currentSong = sounds["rising"];
                            break;
                        case 4:
                            currentSong = sounds["mta"];
                            break;
                        case 5:
                            currentSong = sounds["faster"];
                            break;
                        case 6:
                            currentSong = sounds["alchemist"];
                            break;
                        #endregion
                    }
                }
                else
                {
                    currentSong = sounds["long collision"];
                }
            }
            #endregion

            switch (gameState)
            {
                #region Case: Title
                case GameState.Title: // title splash

                    if (this.SingleKeyPress(Keys.Enter))
                    {
                        // start the game
                        CheckLevelCount();
                        currentLevel = 1;
                        gameState = GameState.Map;
                    }
                    break;
                #endregion

                #region Case: Map
                case GameState.Map:
                    // update the level selector
                    levelSelect.Update(kbState, prevKBState);
                    // get changed level info
                    currentLevel = levelSelect.currentLevel;
                    maxLevel = levelSelect.maxLevel;

                    // select a level
                    if (SingleKeyPress(Keys.Enter) && levelSelect.screenState == LevelSelect.ScreenState.Select)
                    {
                        // check if previous level has been cleared, or if is LV1
                        if (currentLevel == 1 || (currentLevel > 1 && levelSelect.cleared[currentLevel - 1]))
                        {
                            gameState = GameState.Load;
                        }
                    }

                    // return to the title
                    else if (SingleKeyPress(Keys.S))
                    {
                        levelSelect.screenState = LevelSelect.ScreenState.Select;
                        gameState = GameState.Title;
                    }

                    // view the high scores
                    else if (SingleKeyPress(Keys.Q))
                    {
                        gameState = GameState.HighScores;
                    }

                    // enter the map editor
                    else if (SingleKeyPress(Keys.Space))
                    {
                        gameState = GameState.Edit;
                    }
                    break;
                #endregion

                #region Case: Load
                case GameState.Load: // load selected level
                    // make a new loader
                    levelLoader = new LevelLoader();
                    // load the file
                    levelLoader.Load(currentLevel + ".txt");
                    // set locations based on file
                    player = levelLoader.SetStart(player);
                    goal = levelLoader.SetFinish(goal);
                    walls = levelLoader.SetWalls();
                    poles = levelLoader.SetPoles();
                    balloons = levelLoader.SetBalloons();

                    //setting the animation variable in the balloons
                //they get their own animation because they need to act independantly
                    for (int i = 0; i < balloons.Count; i++)
                    {
                        balloons[i].Anim = new Animation(GraphicsDevice, spriteBatch, 5, 100,images["balloon"]);
                    }
                        
                    // reset player
                    player.XSpeed = Constants.START_SPEED;
                    player.YSpeed = Constants.START_SPEED;
                    player.Angle = Constants.START_ANGLE;
                    player.Charge = 0;

                    // start the level
                    gameState = GameState.Level;

                    //reseting the timer
                    totalSecs = 0;
                    totalMins = 0;
                    totalMils = 0;

                    // set random level background
                    int num = ranSong.Next(4);
                    switch (num)
                    {
                        #region switch bkg
                        case 0:
                            if (levelSelect.cleared[currentLevel] == false)
                            {
                                images["active"] = images["r1_dark"];
                            }
                            else
                            {
                                images["active"] = images["r1_light"];
                            }
                            break;
                        case 1:
                            if (levelSelect.cleared[currentLevel] == false)
                            {
                                images["active"] = images["r2_dark"];
                            }
                            else
                            {
                                images["active"] = images["r2_light"];
                            }
                            break;
                        case 2:
                            if (levelSelect.cleared[currentLevel] == false)
                            {
                                images["active"] = images["r3_dark"];
                            }
                            else
                            {
                                images["active"] = images["r3_light"];
                            }
                            break;
                        case 3:
                            if (levelSelect.cleared[currentLevel] == false)
                            {
                                images["active"] = images["r4_dark"];
                            }
                            else
                            {
                                images["active"] = images["r4_light"];
                            }
                            break;
                        #endregion
                    }
                    // check for 'boss level'
                    if (currentLevel == 7 && levelSelect.cleared[7] == false)
                    {
                        images["active"] = images["lvl7_dark"];
                    }
                    else if (currentLevel == 7 && levelSelect.cleared[7])
                    {
                        images["active"] = images["lvl7_light"];
                    }

                    break;
                #endregion

                #region Case: Pause
                case GameState.Pause: // pause menu
                    if (this.SingleKeyPress(Keys.Enter))
                    {
                        // unpause the game
                        gameState = GameState.Level;
                    }
                    else if (this.SingleKeyPress(Keys.A))
                    {
                        // reset the level (reload)
                        gameState = GameState.Load;
                    }
                    else if (this.SingleKeyPress(Keys.D))
                    {
                        // return to the map
                        gameState = GameState.Map;
                    }
                    break;
                #endregion

                #region Case: Level
                case GameState.Level: // play the level
                    //setting the old position
                    tail3.prevLocation = new Rectangle((tail2.prevLocation.X + 6), (tail2.prevLocation.Y + 6),
                        12, 12);
                    tail2.prevLocation = new Rectangle((tail1.prevLocation.X + 12), (tail1.prevLocation.Y + 12),
                        25, 25);
                    tail1.prevLocation = new Rectangle(player.PrevLocation.X, player.PrevLocation.Y, 50, 50);
                    player.PrevLocation = new Rectangle(player.XPos, player.YPos, 50, 50);
                        
                        // timer stuff
                        totalSecs += gameTime.ElapsedGameTime.TotalSeconds;
                        totalMins += gameTime.ElapsedGameTime.TotalMinutes;
                        totalMils += gameTime.ElapsedGameTime.TotalMilliseconds;

                        #region pause the level
                        if (this.SingleKeyPress(Keys.Enter))
                        {
                            gameState = GameState.Pause;
                        }
                        #endregion

                        #region check if the player has completed the level
                        else if (playerRect.Intersects(goalRect))
                        {
                            //adding to the score
                            levelScore = String.Format("{0:0.00}", totalSecs);

                            if (getScore.ScoreList.ContainsKey(currentLevel))
                            {
                                getScore.ScoreList[currentLevel] = totalSecs - (balloonPop*.5);
                            }
                            else
                            {
                                getScore.ScoreList.Add(currentLevel, totalSecs - (balloonPop*.5));
                            }
                           

                            //HM: making it pause for a second so people can see the lightbulb glow :)
                            Thread.Sleep(1000);
                            if (currentLevel+1  == maxLevel)
                            {
                                for (int i = 1; i <= getScore.ScoreList.Count(); i++)
                                {
                                    endScore += getScore.ScoreList[i];
                                }
                                totalScore = String.Format("{0:0.00}", endScore);
                                getScore.WriteScores("HighScores.txt");
                                gameState = GameState.GameFinish;
                            }
                            else
                            {
                                gameState = GameState.LevelComplete;
                            }
                        }
                       
                        #endregion

                        #region orbiting
                        else if (orbitState != OrbitState.None)
                        {
                            #region instances for when player is leaving orbit
                            if (SingleKeyPress(Keys.A) && player.Charge != 1)
                            {
                                player.Charge = 1;
                                orbitState = OrbitState.None;
                            }
                            else if (SingleKeyPress(Keys.S))
                            {
                                player.Charge = 0;
                                orbitState = OrbitState.None;
                            }
                            else if (SingleKeyPress(Keys.D) && player.Charge != -1)
                            {
                                player.Charge = -1;
                                orbitState = OrbitState.None;
                            }
                            #endregion

                            // otherwise, call the orbit methods & collision/speed limit
                            else
                            {
                                #region Orbit state in which player orbit around the pole both counter clockwise and clockwise
                                switch (orbitState)
                                {
                                    case OrbitState.Orbit:
                                        switch (player.Charge)
                                        {
                                            case -1:
                                            {
                                                //Call orbit method so that player can orbit around positive pole
                                                mechanics.Orbit(pos, player);
                                                //Increment player position based on the speed calculations from orbit method
                                                player.XPos += player.XSpeed;
                                                player.YPos += player.YSpeed;
                                                break;
                                            }
                                            case 1:
                                            {
                                                //Call orbit method so that player can orbit around negative pole
                                                mechanics.Orbit(neg, player);
                                                //Increment player position based on the speed calculations from orbit method
                                                player.XPos += player.XSpeed;
                                                player.YPos += player.YSpeed;
                                                break;
                                            }
                                            default:
                                            {
                                                orbitState = OrbitState.None;
                                                break;
                                            }
                                        }
                                        break;

                                    default: break;
                                }
                            #endregion

                                #region NEW METHOD FOR WALL COLLISIONS
                                int i = 0;
                                bool wallIsHit = false;
                                while (wallIsHit == false && i < (walls.Count - 1))
                                {
                                    wallIsHit = mechanics.Bounce(walls[i], player);
                                    if (wallIsHit)
                                    {
                                        sounds["collision"].Play();
                                        player = mechanics.WallCollision(player);
                                    }
                                    i++;
                                }
                                #endregion

                                #region check for max speed
                                if (player.XSpeed > Constants.MAX_SPEED)
                                {
                                    player.XSpeed = Constants.MAX_SPEED;
                                }
                                else if (player.XSpeed < -(Constants.MAX_SPEED))
                                {
                                    player.XSpeed = -(Constants.MAX_SPEED);
                                }
                                if (player.YSpeed > Constants.MAX_SPEED)
                                {
                                    player.YSpeed = Constants.MAX_SPEED;
                                }
                                else if (player.YSpeed < -(Constants.MAX_SPEED))
                                {
                                    player.YSpeed = -(Constants.MAX_SPEED);
                                }
                                #endregion
                            }
                        }
                        #endregion

                        #region Moving
                        else
                        {
                            #region find nearest pos and neg poles
                            pos = new Poles(0, 0, 0); // closest pos pole
                            neg = new Poles(0, 0, 0); // closest neg plole
                            int dis = 0; // distance between player and current pole
                            int pDis = 0; // distance between player and closest pos pole
                            int nDis = 0; // distance between player and closest neg pole
                            foreach (Poles pole in poles)
                            {
                                // calculate distance between player and current pole
                                dis = (int)(Math.Pow((pole.XPos - player.XPos), 2) + Math.Pow((pole.YPos - player.YPos), 2));
                                // check if current pos and neg poles have been set
                                if (pos.Charge == 0 && pole.Charge == 1)
                                {
                                    // set base comparision for pos pole
                                    pos = pole;
                                    pDis = dis;

                                }
                                else if (neg.Charge == 0 && pole.Charge == -1)
                                {
                                    // set base comparison for neg pole
                                    neg = pole;
                                    nDis = dis;
                                }
                                // check current pole against current pos and neg
                                switch (pole.Charge)
                                {
                                    case 1: if (dis < pDis)
                                        {
                                            // set new nearest pos pole
                                            pos = pole;
                                            pDis = dis;

                                        }
                                        break;
                                    case -1: if (dis < nDis)
                                        {
                                            // set new nearest ned pole
                                            neg = pole;
                                            nDis = dis;

                                        }
                                        break;
                                    default: break;
                                }
                            }
                            #endregion

                            #region switch the player's charge
                            if (this.SingleKeyPress(Keys.S))
                            {
                                // change charge to neutral
                                player.Charge = 0;
                            }
                            else if (this.SingleKeyPress(Keys.A))
                            {
                                // change charge to positive
                                player.Charge = 1;
                            }
                            else if (this.SingleKeyPress(Keys.D))
                            {
                                // change charge to negative
                                player.Charge = -1;
                            }
                            #endregion

                            #region player acceleration
                            if (player.Charge == 0)
                            {
                                // neutral charge
                                player.YSpeed = mechanics.Gravity(player.YSpeed);
                            }
                            else if (player.Charge == 1)
                            {
                                // positive charge
                                player = mechanics.Attraction(neg, player);

                                // stick to opposite-charge pole
                                if (mechanics.PoleCollision(neg, player))
                                {
                                    //player.XSpeed = 0;
                                    //player.YSpeed = 0;
                                    //Set orbitState to orbit
                                    orbitState = OrbitState.Orbit;
                                }

                                // repulse from same-charge pole
                                else if (mechanics.PoleCollision(pos, player))
                                {
                                    mechanics.Repulsion(pos, player);
                                }
                            }
                            else if (player.Charge == -1)
                            {
                                // negative charge
                                player = mechanics.Attraction(pos, player);

                                // stick to opposite-charge pole
                                if (mechanics.PoleCollision(pos, player))
                                {
                                    //player.XSpeed = 0;
                                    //player.YSpeed = 0;
                                    //Set orbitState to orbit
                                    orbitState = OrbitState.Orbit;
                                }

                                // repulse from same-charge pole
                                else if (mechanics.PoleCollision(neg, player))
                                {
                                    mechanics.Repulsion(neg, player);
                                }
                            }
                            #endregion

                            #region NEW METHOD FOR WALL COLLISIONS
                            int i = 0;
                            bool wallIsHit = false;
                            while (wallIsHit == false && i < (walls.Count - 1))
                            {
                                wallIsHit = mechanics.Bounce(walls[i], player);
                                if (wallIsHit)
                                {
                                    sounds["collision"].Play();
                                    player = mechanics.WallCollision(player);
                                }
                                i++;
                            }
                            #endregion

                            #region check for max speed
                            if (player.XSpeed > Constants.MAX_SPEED)
                            {
                                player.XSpeed = Constants.MAX_SPEED;
                            }
                            else if (player.XSpeed < -(Constants.MAX_SPEED))
                            {
                                player.XSpeed = -(Constants.MAX_SPEED);
                            }
                            if (player.YSpeed > Constants.MAX_SPEED)
                            {
                                player.YSpeed = Constants.MAX_SPEED;
                            }
                            else if (player.YSpeed < -(Constants.MAX_SPEED))
                            {
                                player.YSpeed = -(Constants.MAX_SPEED);
                            }
                            #endregion

                            // calculate new position
                            player.XPos += player.XSpeed;
                            player.YPos += player.YSpeed;
                        }
                        #endregion

                        // keep the player on the screen
                        BorderCollision();

                        break;
                #endregion

                #region Case: Level Complete
                case GameState.LevelComplete:
                        // leave this screen
                        if (SingleKeyPress(Keys.Enter))
                        {
                            levelSelect.cleared[(currentLevel)] = true;
                            // increment currently selected level, if possible
                            if (currentLevel < (maxLevel - 1))
                            {
                                currentLevel++;
                                levelSelect.currentLevel = currentLevel;
                            }
                            // return to the map
                            gameState = GameState.Map;
                        }
                        
                        break;
                #endregion

                #region Case: Edit
                case GameState.Edit:
                    // check if the editor is in use
                    if (mapMaker != null)
                    {
                        // return to the map and close the editor
                        if (mapMaker.mapState == MapMaker.MapState.Editing && SingleKeyPress(Keys.Escape))
                        {
                            mapMaker = null;
                            CheckLevelCount();
                            levelSelect.CheckCompletedLevels();
                            gameState = GameState.Map;
                        }

                        // otherwise, update the editor
                        else
                        {
                            mapMaker.Update(kbState, prevKBState);
                        }
                    }

                    // if there is no editor
                    else
                    {
                        mapMaker = new MapMaker(images, text);
                    }
                    break;
                #endregion

                #region Case: GameFinish
                case GameState.GameFinish:
                    if (this.SingleKeyPress(Keys.Enter))
                    {
                        gameState = GameState.HighScores;
                    }
                    break;

                #endregion

                #region Case: HighScore
                case GameState.HighScores:
                    // Open the high score list
                    getScore.LoadScores("HighScores.txt");
                    if (SingleKeyPress(Keys.W))
                    {
                        gameState = GameState.Map;
                        levelSelect.screenState = LevelSelect.ScreenState.Select;
                    }
                    else if (SingleKeyPress(Keys.E))
                    {
                        gameState = GameState.Map;
                        levelSelect.screenState = LevelSelect.ScreenState.Instructions;
                    }
                    else if (SingleKeyPress(Keys.S))
                    {
                        gameState = GameState.Title;
                    }
                    break;
                #endregion
            }

            // save the current keyboard state for reference next frame
            prevKBState = kbState;

            base.Update(gameTime);
        }
Esempio n. 18
0
        protected override void Initialize()
        {
            gameState = new GameState();
            gameState = GameState.Title;
            orbitState = new OrbitState();
            orbitState = OrbitState.None;
            kbState = new KeyboardState();
            prevKBState = new KeyboardState();
            player = new Character();
            mechanics = new Mechanics();
            poles = new List<Poles>();
            walls = new List<Wall>();
            balloons = new List<Balloon>();
            goal = new Goal();
            images = new Dictionary<string, Texture2D>();
            sounds = new Dictionary<string, SoundEffect>();
            currentLevel = 1;
            mapMaker = null;
            levelScore = "";
            totalScore = "";
            balloonPop = 0;
            endScore = 0;
            getScore = new Scoring(); //Score object
            tail1 = new FollowObj(player);
            tail2 = new FollowObj(tail1);
            tail3 = new FollowObj(tail2);

            base.Initialize();
        }