void OnTouchesEnded(List <CCTouch> touches, CCEvent touchEvent)
        {
            monkey.StopAllActions();

            var location = touches [0].LocationOnScreen;

            location = WorldToScreenspace(location);

            if (location.Y >= allowableMovementRect.Size.Height)
            {
                location.Y = allowableMovementRect.Size.Height;
            }

            float ds = CCPoint.Distance(monkey.Position, location);

            var dt = ds / monkeySpeed;

            var moveMonkey = new CCMoveTo(dt, location);

            //BUG: calling walkRepeat separately as it doesn't run when called in RunActions or CCSpawn
            monkey.RunAction(walkRepeat);
            monkey.RunActions(moveMonkey, walkAnimStop);

            // move the clouds relative to the monkey's movement
            MoveClouds(location.Y - monkey.Position.Y);
        }
        internal void PrepareForPlanningPhase(PlayLayer pl)
        {
            // first check the aggro
            // i.e. if an enemy (i.e. a player aircraft) is close enough break formation
            // also if one of the aircrafts is damaged break formation too
            if (InFormation)
            {
                foreach (var aircraft in pl.PlayerAircrafts)
                {
                    if (CCPoint.Distance(aircraft.Position, Position) < AggroRange)
                    {
                        //Console.WriteLine("TRIGGERED - DISTANCE");
                        InFormation = false;
                        break;
                    }
                }
                foreach (var aircraft in AircraftsWithRelPositions.Keys)
                {
                    if (aircraft.Health < aircraft.MaxHealth)
                    {
                        //Console.WriteLine("TRIGGERED - HP");
                        InFormation = false;
                        break;
                    }
                }
            }

            foreach (var aircraft in AircraftsWithRelPositions.Keys)
            {
                aircraft.PrepareForPlanningPhase();
            }

            if (!InFormation)
            {
                return;                 // squadrons only control their units while in formation
            }
            //Console.WriteLine("FLYING IN FORMATION");

            const float dt = Constants.TURN_DURATION;
            // if you're too close to the current Waypoint roll a new one
            var   diff            = WayPoint - Leader.Position;
            float advanceDistance = Velocity * dt;

            if (diff.Length < advanceDistance)
            {
                GenerateWayPoint();
                diff = WayPoint - Leader.Position;
            }
            LeaderWayPoint = Leader.Position + CCPoint.Normalize(diff) * advanceDistance;
            // rotate all formation positions correctly around the leader and tell everyone to go to their positions
            float angle = Constants.DxDyToRadians(diff.X, diff.Y);

            foreach (var entry in AircraftsWithRelPositions)
            {
                var formationPoint = CCPoint.RotateByAngle(entry.Value, CCPoint.Zero, angle);
                var yourWaypoint   = LeaderWayPoint + formationPoint;
                entry.Key.TryToSetFlightPathHeadTo(yourWaypoint);
            }
        }
Example #3
0
        void MoveShipTo(CCPoint location)
        {
            float ds = CCPoint.Distance(ship.Position, location);
            var   dt = ds / SHIP_SPEED;

            var moveShip = new CCMoveTo(dt, location);
            var easeShip = new CCEaseSineInOut(moveShip);

            ship.RunAction(easeShip);
        }
        /// <summary>
        /// Advance the current position some distance on the flight path.
        /// </summary>
        /// <param name="distance"></param>
        /// <param name="destination">position after the advance</param>
        /// <param name="cCfinalDirection">direction of the segment that the position is on after the advance</param>
        internal void Advance(CCPoint currentPosition, float distance, out CCPoint destination, out float CCfinalDirection)
        {
            int   currentIndex = (int)AdvancementAsQuasiIndex;
            float relativeAdvancementToNextPoint = AdvancementAsQuasiIndex % 1;

            if (currentIndex == Path.Length - 1)  // if you've already reached the end you're done
            {
                destination      = EndPoint;
                CCfinalDirection = DirectionAt(currentIndex);
                return;
            }
            float absoluteAdvancementToNextPoint = relativeAdvancementToNextPoint * CCPoint.Distance(Path[currentIndex], Path[currentIndex + 1]);
            float directionToNextPointInRadians  = Constants.CCDegreesToMathRadians(DirectionAt(currentIndex));
            float absoluteXAdvancement           = absoluteAdvancementToNextPoint * (float)Math.Cos(directionToNextPointInRadians);
            float absoluteYAdvancement           = absoluteAdvancementToNextPoint * (float)Math.Sin(directionToNextPointInRadians);
            //CCPoint currentPosition = new CCPoint(Path[currentIndex].X + absoluteXAdvancement, Path[currentIndex].Y + absoluteYAdvancement);
            // try to advance from the current position to the next point on the Path
            float distanceToNextPoint = CCPoint.Distance(currentPosition, Path[currentIndex + 1]);

            while (distanceToNextPoint < distance)
            {
                currentIndex            = currentIndex + 1;
                currentPosition         = Path[currentIndex];
                distance               -= distanceToNextPoint;
                AdvancementAsQuasiIndex = currentIndex;
                if (currentIndex == Path.Length - 1)
                {
                    break;
                }
                distanceToNextPoint = CCPoint.Distance(currentPosition, Path[currentIndex + 1]);
            }
            // if you can't go far enough just move towards the point
            if (distance > 0 && currentIndex != Path.Length - 1)
            {
                // update the direction
                directionToNextPointInRadians = Constants.CCDegreesToMathRadians(DirectionAt(currentIndex));
                // calculate how far you can go
                // relative between the points
                float relativeAdvanche = distance / distanceToNextPoint;
                // in x direction
                float newX = currentPosition.X + distance * (float)Math.Cos(directionToNextPointInRadians);
                // in y direction
                float newY = currentPosition.Y + distance * (float)Math.Sin(directionToNextPointInRadians);
                AdvancementAsQuasiIndex = (float)currentIndex + relativeAdvanche;
                destination             = new CCPoint(newX, newY);
                CCfinalDirection        = Constants.RadiansToCCDegrees(directionToNextPointInRadians);
            }
            else
            {
                destination      = Path[currentIndex];
                CCfinalDirection = DirectionAt(currentIndex);
            }
            //
        }
 public static float GetZoomOneTouchMoving(CCTouch movingTouch, CCPoint stableTouchLoc)
 {
     Console.WriteLine("CALLED");
     // get the middlepoint and check if they both move towards it
     //CCPoint midPoint = (movingTouch.Location + stableTouch.Location) / 2;
     {
         Console.WriteLine("output2: " + CCPoint.Distance(movingTouch.PreviousLocation, stableTouchLoc) / CCPoint.Distance(movingTouch.Location, stableTouchLoc));
         return(CCPoint.Distance(movingTouch.PreviousLocation, stableTouchLoc) / CCPoint.Distance(movingTouch.Location, stableTouchLoc));
     }
     //else
     //    return float.NaN;
 }
Example #6
0
        private void moveRemoteMonkey(float x)
        {
            Console.WriteLine("moveRemoteMonkey");
            var location = new CCPoint();

            location.X = x;
            location.Y = remoteMonkey.PositionY;
            float ds = CCPoint.Distance(remoteMonkey.Position, location);

            float dt = ds / MONKEY_SPEED;

            var moveMonkey = new CCMoveTo(dt, location);

            remoteMonkey.RunAction(moveMonkey);
        }
Example #7
0
        private EnemyBullet AddEnemyBullet(CCSprite sender)
        {
            EnemyBullet bullet = new EnemyBullet();

            bullet.Position = new CCPoint(sender.Position.X, sender.Position.Y - sender.ContentSize.Height / 2);
            AddChild(bullet, ENEMY_BULLET_INDEX);

            CCPoint target   = CCPoint.IntersectPoint(bullet.Position, player.Position, CCPoint.Zero, new CCPoint(VisibleBoundsWorldspace.MaxX, 0));
            float   distance = CCPoint.Distance(bullet.Position, target);

            var moveBullet = new CCMoveTo(distance / ENEMY_BULLET_SPEED, target);

            bullet.RunActions(moveBullet, moveOutOfView);
            return(bullet);
        }
Example #8
0
        void OnTouchesEnded(List <CCTouch> touches, CCEvent touchEvent)
        {
            base.TouchesEnded(touches, touchEvent);

            var location = touches [0].Location;

            float ds = CCPoint.Distance(monkey.Position, location);

            float dt = ds / MONKEY_SPEED;

            var moveMonkey = new CCMoveTo(dt, location);

            monkey.RunAction(moveMonkey);

            CCSimpleAudioEngine.SharedEngine.PlayEffect("Sounds/tap.mp3");
        }
        public void OnTouchesEnded(List <CCTouch> touches, CCEvent touchEvent)
        {
            monkey.StopAllActions();
            var location = touches[0].LocationOnScreen;

            location = WorldToScreenspace(location);
            float ds = CCPoint.Distance(monkey.Position, location);

            var dt = ds / Money_Speed;

            var MoveMonkey = new CCMoveTo(dt, location);

            monkey.RunAction(walkRepeat);
            monkey.RunActions(MoveMonkey, walkAnimStop);
            CCSimpleAudioEngine.SharedEngine.PlayEffect("Sounds/tap");
        }
        internal override void ActInPlanningPhase()
        {
            // first check whether you're hurt and go scared if you are
            if (!Scared && Aircraft.Health < Aircraft.MaxHealth)
            {
                Scared = true;
            }
            // go through all aircrafts and find the closest enemy
            // (for now an enemy is everyone who isn't on your team)
            var myTeam = Aircraft.Team;
            IEnumerable <Aircraft> aircrafts;

            if (myTeam == Team.PlayerTeam)
            {
                aircrafts = Aircraft.ActiveAircraftsInLevel();
            }
            else
            {
                aircrafts = Aircraft.PlayerAircraftsInLevel();
            }
            Aircraft closestAircraft = null;

            foreach (var aircraft in aircrafts)
            {
                if (aircraft.MyState != Aircraft.State.SHOT_DOWN && aircraft != Aircraft && aircraft.Team.IsEnemy(myTeam) && aircraft.IsActive())
                {
                    // check the distance (closer is better)
                    if (closestAircraft == null ||
                        CCPoint.Distance(Aircraft.Position, aircraft.Position) < CCPoint.Distance(Aircraft.Position, closestAircraft.Position))
                    {
                        closestAircraft = aircraft;
                    }
                }
            }
            // if it is too close run away
            if (closestAircraft != null && (Scared || CCPoint.Distance(Aircraft.Position, closestAircraft.Position) < SCARE_DISTANCE))
            {
                //Console.WriteLine("FLEEING");
                Aircraft.TryToSetFlightPathHeadTo(Aircraft.Position + (Aircraft.Position - closestAircraft.Position) * 16);
            }
            // else move randomly
            else
            {
                //Console.WriteLine("Moving randomly");
                Aircraft.TryToSetFlightPathHeadTo(Constants.RandomPointBoxnear(Aircraft.Position, 1000f));
            }
        }
        /// <summary>
        /// If the two touches have a common center that they move toward or away from, this function returns the relative change of distance between them.
        /// Else it returns <c>float.NaN</c>.
        /// </summary>
        /// <param name="touch1"></param>
        /// <param name="touch2"></param>
        /// <returns>how the distance between the two touches changed</returns>
        public static float GetZoom(CCTouch touch1, CCTouch touch2)
        {
            // get the middlepoint and check if they both move towards it

            /*
             * CCPoint midPoint = new CCPoint((touch1.Location.X + touch2.Location.X) / 2, (touch1.Location.Y + touch2.Location.Y) / 2);
             * if ((CCPoint.Distance(touch1.Location, midPoint) < CCPoint.Distance(touch1.PreviousLocation, midPoint) &&
             *   CCPoint.Distance(touch2.Location, midPoint) < CCPoint.Distance(touch2.PreviousLocation, midPoint)) ||
             *  (CCPoint.Distance(touch1.Location, midPoint) > CCPoint.Distance(touch1.PreviousLocation, midPoint) &&
             *   CCPoint.Distance(touch2.Location, midPoint) > CCPoint.Distance(touch2.PreviousLocation, midPoint)))
             */
            {
                Console.WriteLine("output: " + CCPoint.Distance(touch1.PreviousLocation, touch2.PreviousLocation) / CCPoint.Distance(touch1.Location, touch2.Location));
                return(CCPoint.Distance(touch1.PreviousLocation, touch2.PreviousLocation) / CCPoint.Distance(touch1.Location, touch2.Location));
            }
            //else
            //    return float.NaN;
        }
Example #12
0
        public void MovePhase(float frameTimeInSeconds)
        {
            if (this.State == ActionState.walking)
            {
                double diffX  = nextMove.X - Position.X;
                double diffY  = nextMove.Y - Position.Y;
                double length = Math.Sqrt(diffX * diffX + diffY * diffY);                 //Pythagorean law
                float  dx     = (float)(diffX / length * moveSpeed * frameTimeInSeconds); //higher speed is faster
                float  dy     = (float)(diffY / length * moveSpeed * frameTimeInSeconds);

                this.Position += new CCPoint(dx, dy);
                UpdateNextMove();
                if (CCPoint.Distance(this.Position, nextMove) < 5)
                {
                    this.gridPos = GodClass.gridManager.GetTileFromScreenTouch(nextMove);
                    UpdateNextMove();
                }
            }
        }
Example #13
0
        public override void TouchesEnded(List <CCTouch> touches)
        {
            base.TouchesEnded(touches);

            var location = new CCPoint();

            location.X = touches [0].Location.X;
            location.Y = localMonkey.PositionY;
            float ds = CCPoint.Distance(localMonkey.Position, location);

            float dt = ds / MONKEY_SPEED;

            var moveMonkey = new CCMoveTo(dt, location);

            localMonkey.RunAction(moveMonkey);

            byte[] message = buildMonkeyMessage(location.X);
            sendWarpUpdate(message);
        }
Example #14
0
        public void ReturningToHiveBehavior()
        {
            CCPoint parkingSpot = this.AlienHive.GetPositionOfSlot(this.PositionInHive);

            float dist = CCPoint.Distance(this.Position, parkingSpot);

            if (dist > GameParameters.ALIEN_INVADER_VELOCITY_VAL)
            {
                this.AimAtPoint2(parkingSpot, GameParameters.ALIEN_INVADER_VELOCITY_VAL);
                UpdatePosition();
            }
            else
            {
                GameParameters.RENDERING_SURFACE_MUTEX.WaitOne();
                this.Position = parkingSpot;
                GameParameters.RENDERING_SURFACE_MUTEX.ReleaseMutex();
                this.SetBehaviorDormantInHive();
                this.IsAttacking        = false;
                this.IsLaunchingRockets = false;
            }
        }
        /** override functions */
        public virtual bool TouchBegan(CCTouch pTouch, CCEvent touchEvent)
        {
            if (!Visible)
            {
                return(false);
            }

            var frame = ViewRect;

            //dispatcher does not know about clipping. reject _touches outside visible bounds.
            if (_touches.Count > 2 ||
                IsTouchMoved ||
                !frame.ContainsPoint(_container.Layer.ScreenToWorldspace(pTouch.LocationOnScreen)))
            {
                return(false);
            }

            if (!_touches.Contains(pTouch))
            {
                _touches.Add(pTouch);
            }

            if (_touches.Count == 1)
            {
                // scrolling
                _touchPoint       = Layer.ScreenToWorldspace(pTouch.LocationOnScreen);
                IsTouchMoved      = false;
                Dragging          = true; //Dragging started
                _dragginStartTime = DateTime.Now;
                _scrollDistance   = CCPoint.Zero;
                _touchLength      = 0.0f;
            }
            else if (_touches.Count == 2)
            {
                _touchPoint  = CCPoint.Midpoint(Layer.ScreenToWorldspace(_touches[0].LocationOnScreen), Layer.ScreenToWorldspace(_touches[1].LocationOnScreen));
                _touchLength = CCPoint.Distance(_container.Layer.ScreenToWorldspace(_touches[0].LocationOnScreen), _container.Layer.ScreenToWorldspace(_touches[1].LocationOnScreen));
                Dragging     = false;
            }
            return(true);
        }
Example #16
0
        void OnTouchesMoved(List <CCTouch> touches, CCEvent touchEvent)
        {
            CCAffineTransform worldTransform = AffineWorldTransform;
            CCTouch           touch          = touches[0];
            CCPoint           start          = touch.Location;
            CCPoint           end            = touch.PreviousLocation;

            // begin drawing to the render texture
            target.Begin();

            // for extra points, we'll draw this smoothly from the last position and vary the sprite's
            // scale/rotation/offset
            float distance = CCPoint.Distance(start, end);

            if (distance > 1)
            {
                var d = (int)distance;
                for (int i = 0; i < d; i++)
                {
                    float difx  = end.X - start.X;
                    float dify  = end.Y - start.Y;
                    float delta = i / distance;
                    brush.Position = new CCPoint(start.X + (difx * delta), start.Y + (dify * delta));
                    brush.Rotation = CCRandom.Next() % 360;
                    float r = (CCRandom.Next() % 50 / 50f) + 0.25f;
                    brush.Scale = r;

                    // Comment out the following line to show just the initial red color set
                    brush.Color = new CCColor3B((byte)(CCRandom.Next() % 127 + 128), 255, 255);

                    // Call visit to draw the brush, don't call draw..
                    brush.Visit(ref worldTransform);
                }
            }

            // finish drawing and return context back to the screen
            target.End();
        }
Example #17
0
        void CheckEnemyCollisions()
        {
            if (enemies.ChildrenCount > 0 && shots.ChildrenCount > 0)
            {
                foreach (var enemy in enemies.Children)
                {
                    foreach (var shot in shots.Children)
                    {
                        var d = CCPoint.Distance(shot.Position, enemy.Position);
                        if (d <= ENEMY_RADIUS + SHOT_RADIUS)
                        {
                            var pt = enemy.Position;
                            enemy.RemoveFromParent(true);
                            CCSimpleAudioEngine.SharedEngine.PlayEffect("sounds/explosion");

                            var explosion = new CCParticleSystemQuad("implode.plist");
                            explosion.Position = pt;
                            AddChild(explosion);
                        }
                    }
                }
            }
        }
        internal override void ActInPlanningPhase()
        {
            // first go through all aircrafts and find the closest enemy
            // (for now an enemy is everyone who isn't on your team)
            var myTeam = Aircraft.Team;
            IEnumerable <Aircraft> aircrafts;

            if (myTeam == Team.PlayerTeam)
            {
                aircrafts = Aircraft.ActiveAircraftsInLevel();
            }
            else
            {
                aircrafts = Aircraft.PlayerAircraftsInLevel();
            }
            Aircraft closestAircraft = null;

            foreach (var aircraft in aircrafts)
            {
                if (aircraft.MyState != Aircraft.State.SHOT_DOWN && aircraft != Aircraft && aircraft.Team.IsEnemy(myTeam) && aircraft.IsActive())
                {
                    // check the distance (closer is better)
                    if (closestAircraft == null ||
                        CCPoint.Distance(Aircraft.Position, aircraft.Position) < CCPoint.Distance(Aircraft.Position, closestAircraft.Position))
                    {
                        closestAircraft = aircraft;
                    }
                }
            }
            // set path towards where he might be at the end of the next turn
            if (closestAircraft != null)
            {
                //Console.WriteLine("Attacking!");
                Aircraft.TryToSetFlightPathHeadTo(closestAircraft.Position + (closestAircraft.VelocityVector * Constants.TURN_DURATION));
            }
        }
Example #19
0
        void OnTouchesMoved(List <CCTouch> touches, CCEvent touchEvent)
        {
            if (touches.Count <= 0)
            {
                return;
            }

            float x = touches[0].LocationOnScreen.X;
            float y = touches[0].LocationOnScreen.Y;

            if (m_IsCardDragging)
            {
                CCSprite Spr = TexturePool.GetSprite(m_Game.m_CurrentCard.m_Hash);
                Spr.Position = touches[0].LocationOnScreen;

                foreach (CCTouch i in touches)
                {
                    CCPoint p = i.LocationOnScreen;
                    p = m_Overlay.ScreenToWorldspace(p);
                    m_Overlay.m_CardButton.Position = p;
                }
            }
            else
            {
                if (m_Touches == 1) // Pan
                {
                    foreach (CCTouch i in touches)
                    {
                        var s = m_BoardLayer.Camera.CenterInWorldspace;
                        s.X += i.PreviousLocationOnScreen.X - i.LocationOnScreen.X;
                        s.Y += i.LocationOnScreen.Y - i.PreviousLocationOnScreen.Y;
                        m_BoardLayer.Camera.CenterInWorldspace = s;

                        var target = m_BoardLayer.Camera.TargetInWorldspace;
                        target.X = s.X;
                        target.Y = s.Y;
                        m_BoardLayer.Camera.TargetInWorldspace = target;
                    }
                }
                else if (m_Touches == 2) // Zoom
                {
                    if (touches.Count < 2)
                    {
                        return;
                    }

                    for (int i = 0; i < touches.Count; i += 2)
                    {
                        CCPoint fir   = touches[i].LocationOnScreen;
                        CCPoint sec   = touches[i + 1].LocationOnScreen;
                        CCPoint third = touches[i].PreviousLocationOnScreen;
                        CCPoint four  = touches[i + 1].PreviousLocationOnScreen;

                        float one = CCPoint.Distance(fir, sec);
                        float two = CCPoint.Distance(third, four);

                        if (one < two)
                        {
                            m_BoardLayer.UpdateScale(-0.05f);
                        }
                        else
                        {
                            m_BoardLayer.UpdateScale(0.05f);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// takes care of dragging and zoom
        /// </summary>
        /// <param name="touch"></param>
        /// <param name="touchEvent"></param>
        public virtual void TouchMoved(CCTouch touch, CCEvent touchEvent)
        {
            if (!Visible)
            {
                return;
            }

            if (_touches.Contains(touch))
            {
                if (_touches.Count == 1 && Dragging)
                {                                   // scrolling
                    CCPoint moveDistance, newPoint; //, _maxInset, _minInset;

                    var frame = ViewRect;

                    newPoint     = Layer.ScreenToWorldspace(_touches[0].LocationOnScreen);
                    moveDistance = newPoint - _touchPoint;
                    Debug.WriteLine("move distance: " + moveDistance);

                    float dis;
                    if (Direction == CcScrollViewDirection.Vertical)
                    {
                        dis = moveDistance.Y;
                    }
                    else if (Direction == CcScrollViewDirection.Horizontal)
                    {
                        dis = moveDistance.X;
                    }
                    else
                    {
                        dis = (float)Math.Sqrt(moveDistance.X * moveDistance.X + moveDistance.Y * moveDistance.Y);
                    }

                    if (!IsTouchMoved && Math.Abs(ConvertDistanceFromPointToInch(dis)) < MoveInch)
                    {
                        //CCLOG("Invalid movement, distance = [%f, %f], disInch = %f", moveDistance.x, moveDistance.y);
                        return;
                    }

                    if (!IsTouchMoved)
                    {
                        moveDistance = CCPoint.Zero;
                    }

                    _touchPoint  = newPoint;
                    IsTouchMoved = true;

                    if (frame.ContainsPoint(_touchPoint))
                    {
                        switch (Direction)
                        {
                        case CcScrollViewDirection.Vertical:
                            moveDistance = new CCPoint(0.0f, moveDistance.Y);
                            break;

                        case CcScrollViewDirection.Horizontal:
                            moveDistance = new CCPoint(moveDistance.X, 0.0f);
                            break;
                        }

                        float newX = _container.Position.X + moveDistance.X;
                        float newY = _container.Position.Y + moveDistance.Y;

                        //Debug.WriteLine("Scroll Distance: " + _scrollDistance);
                        _scrollDistance = moveDistance;
                        Debug.WriteLine("new offset " + new CCPoint(newX, newY));
                        SetContentOffset(new CCPoint(newX, newY));
                    }
                }
                else if (_touches.Count == 2 && !Dragging)
                {
                    //2 fingers no dragging? zoom

                    float len = CCPoint.Distance(Layer.ScreenToWorldspace(_touches[0].LocationOnScreen),
                                                 Layer.ScreenToWorldspace(_touches[1].LocationOnScreen));



                    var differenceTouchLength = (len / _touchLength);
                    ZoomScale = (differenceTouchLength < 1)
                        ? ZoomScale * (1 - (1 - differenceTouchLength) * 0.5f)
                        : ZoomScale * (1 + (differenceTouchLength - 1) * 0.5f);

                    _touchLength = len;
                }
            }
        }
Example #21
0
        protected void TouchesEnded(List <CCTouch> touches, CCEvent touchEvent)
        {
            if (_state == gamestates.kGameIntro && !isLoading)
            {
                _intro.Visible    = false;
                _pauseBtn.Visible = true;
                _state            = gamestates.kGamePlay;
                resetGame();
                return;
            }
            else if (_state == gamestates.kGamePaused)
            {
                //_pauseBtn.DisplayFrame = CCSpriteFrameCache.SharedSpriteFrameCache["btn_pause_off.png"];
                _paused.Visible = false;
                _state          = gamestates.kGamePlay;
                _running        = true;
                return;
            }
            else if (_state == gamestates.kGameOver)
            {
                _gameOver.Visible = false;
                _pauseBtn.Visible = true;
                _state            = gamestates.kGamePlay;
                resetGame();
                return;
            }

            if (!_running)
            {
                return;
            }

            CCTouch touch = touches.FirstOrDefault();

            if (touch != null)
            {
                CCPoint tap = touch.LocationOnScreen;;;                   //??¿¿?¿?
                tap.Y = Window.WindowSizeInPixels.Height - tap.Y;

                if (_pauseBtn.BoundingBox.ContainsPoint(tap))
                {
                    _paused.Visible = true;
                    _state          = gamestates.kGamePaused;
                    //	_pauseBtn.DisplayFrame = CCApplication.SharedApplication.SpriteFrameCache["btn_pause_on.png"]; // CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName ("btn_pause_on.png"));
                    _running = false;
                    return;
                }

                //track if tapping on ship
                _drawing = false;
                _rocket.select(false);

                //if we are showing a temp line
                if (_lineContainer._lineType == lineTypes.LINE_TEMP)
                {
                    //set up dashed line
                    _lineContainer._pivot      = tap;
                    _lineContainer._lineLength = CCPoint.Distance(_rocket.Position, tap);

                    //set up rocket
                    _rocket._pivot = tap;
                    float circle_length = _lineContainer._lineLength * 2 * CCMathHelper.Pi;

                    int iterations = (int)Math.Floor(circle_length / _rocket._speed);
                    _rocket._angularSpeed = 2 * CCMathHelper.Pi / iterations;

                    CCPoint clockwise = CCPoint.PerpendicularCW(_rocket.Position - _rocket._pivot);

                    float dot = CCPoint.Dot(clockwise, _rocket._vector);

                    if (dot > 0)
                    {
                        _rocket._angularSpeed        = (_rocket._angularSpeed * -1);
                        _rocket._rotationOrientation = Rocket.ROTATE_CLOCKWISE;
                        _rocket.setTargetRotation(MathHelper.ToDegrees((float)Math.Atan2(clockwise.Y, clockwise.X)));
                    }
                    else
                    {
                        _rocket._rotationOrientation = Rocket.ROTATE_COUNTER;
                        _rocket._targetRotation      = MathHelper.ToDegrees((float)Math.Atan2(-1 * clockwise.Y, -1 * clockwise.X));
                    }

                    _lineContainer._lineType = lineTypes.LINE_DASHED;
                }
            }
        }
Example #22
0
        bool isPeaceCloseToHome(Peace peace)
        {
            const int MIN_DISTANCE = 20;

            return(CCPoint.Distance(peace.Sprite.Position, peace.AssembledPos) < MIN_DISTANCE);
        }
        new private protected void OnTouchesEnded(List <CCTouch> touches, CCEvent touchEvent)
        {
            base.OnTouchesEnded(touches, touchEvent);
            switch (touches.Count)
            {
            case 1:
            {
                var touch = touches[0];
                if (DragAndDropObject != null)
                {
                    touchEvent.StopPropogation();
                    switch (HangarLayer.State)
                    {
                    case HangarLayer.HangarState.HANGAR:
                        var selectedAircraft = DragAndDropObject as Aircraft;
                        DragAndDropObject = null;
                        if (selectedAircraft != null)
                        {
                            // if an aircraft is dragged upon the takeoff node add it to the collection
                            if (!(TakeoffNode.BoundingBoxTransformedToParent.ContainsPoint(touch.Location) && TakeoffCollectionNode.AddToCollection(selectedAircraft)))
                            {
                                // if not, then place it back into the hangar
                                HangarLayer.AddAircraftChild(selectedAircraft);
                                selectedAircraft.Scale = Constants.STANDARD_SCALE;
                                HangarLayer.PlaceAircraft(selectedAircraft, HangarLayer.GUICoordinatesToHangar(selectedAircraft.Position));
                            }
                            if (TakeoffCollectionNode.Collection.Any())
                            {
                                GOButton.AddAction(HangarLayer.AddGOButton);
                                TakeoffCollectionLabel.Visible = false;
                            }
                            else if (!PopUp.TriggeredPlayLayer)
                            {
                                TakeoffCollectionLabel.Visible = true;
                            }
                        }
                        break;

                    case HangarLayer.HangarState.MODIFY_AIRCRAFT:
                    {
                        bool mounted = false;
                        HangarLayer.UpdateClosestMount();
                        // the object is a part
                        var part = (Part)DragAndDropObject;
                        DragAndDropObject = null;
                        // if it is a body and the aircraft currently has none (which means no parts at all)
                        if (HangarLayer.ModifiedAircraft.Body == null && part.Types.Contains(Part.Type.BODY) && CCPoint.IsNear(HangarLayer.GUICoordinatesToHangar(part.PositionWorldspace), HangarLayer.ModifiedAircraft.PositionWorldspace, MOUNT_DISTANCE))
                        {
                            // set it as the aircraft body
                            HangarLayer.ModifiedAircraft.InWorkshopConfiguration = false;
                            part.Scale = 1;
                            HangarLayer.ModifiedAircraft.Body = part;
                            HangarLayer.ModifiedAircraft.InWorkshopConfiguration = true;
                            HangarLayer.CalcBoundaries();                 // the aircraft has changed size, so update the boundaries
                            HangarLayer.DrawInModifyAircraftState();
                            mounted = true;
                        }
                        // check if the part is currently at a mount point where it can be mounted
                        else if (!mounted)
                        {
                            var possibleMounts = new List <PartMount>();
                            foreach (var modPart in HangarLayer.ModifiedAircraft.TotalParts)
                            {
                                foreach (var mountPoint in modPart.PartMounts)
                                {
                                    if (mountPoint.Available && mountPoint.CanMount(part))
                                    {
                                        if (CCPoint.IsNear(HangarLayer.GUICoordinatesToHangar(part.PositionWorldspace), mountPoint.PositionModifyAircraft, MOUNT_DISTANCE))
                                        {
                                            possibleMounts.Add(mountPoint);
                                        }
                                    }
                                }
                            }
                            // mount at the closest possible mount point
                            float     minDistance  = float.PositiveInfinity;
                            PartMount closestMount = null;
                            foreach (var mountPoint in possibleMounts)
                            {
                                float distance = CCPoint.Distance(HangarLayer.GUICoordinatesToHangar(part.PositionWorldspace), mountPoint.PositionModifyAircraft);
                                if (distance < minDistance)
                                {
                                    minDistance  = distance;
                                    closestMount = mountPoint;
                                }
                            }
                            if (closestMount != null)
                            {
                                // better mount in non-workshop configuration
                                HangarLayer.ModifiedAircraft.InWorkshopConfiguration = false;
                                part.Scale = 1;
                                closestMount.MyPart.MountPart(closestMount, part);
                                HangarLayer.ModifiedAircraft.InWorkshopConfiguration = true;
                                HangarLayer.CalcBoundaries();                 // the aircraft has probably changed size, so update the boundaries
                                HangarLayer.DrawInModifyAircraftState();
                                mounted = true;
                            }
                        }
                        // if the part has not been mounted the part is just dropped and added to the collection
                        if (!mounted)
                        {
                            // first disassemble it though
                            // and flip it if it is flipped
                            var totalParts = part.TotalParts;
                            part.Disassemble();
                            foreach (var singlePart in totalParts)
                            {
                                if (singlePart.Flipped)
                                {
                                    singlePart.Flip();
                                }
                                HangarLayer.AddPart(singlePart);
                            }
                        }
                    }
                    break;
                    }
                    DragAndDropObject = null;
                }
            }
            break;

            default:
                break;
            }
        }
Example #24
0
        public override void Update(float dt)
        {
            base.Update(dt);
            switch (State)
            {
            case GameState.PLANNING:
                break;

            case GameState.EXECUTING_ORDERS:
            {
                TimeLeftExecutingOrders -= dt;
                if (Aircraft.CloudFrameCountdown != 0)
                {
                    Aircraft.CloudFrameCountdown--;
                }
                else
                {
                    Aircraft.CloudFrameCountdown = Aircraft.CLOUD_FRAME_COUNTDOWN;
                }
                if (powerUpCheckCountDown != 0)
                {
                    powerUpCheckCountDown--;
                }
                else
                {
                    powerUpCheckCountDown = PU_CHECK_COUNTDOWN;
                    // check if any powerup is close enough to be picked up
                    foreach (var aircraft in PlayerAircrafts)
                    {
                        if (aircraft.MyState == Aircraft.State.SHOT_DOWN)
                        {
                            continue;
                        }
                        CCPoint aPos = aircraft.Position;
                        foreach (var powerUp in PowerUps)
                        {
                            // only pick up power-ups that are close in x-y but also in z direction
                            if (powerUp.VertexZ > -10f && CCPoint.Distance(powerUp.Position, aPos) < PowerUp.PICKUP_DISTANCE)
                            {
                                // pick up the powerup
                                if (!PopUp.TriggeredPowerUp)
                                {
                                    PopUp.ShowPopUp(GUILayer, PopUp.Enum.TRIGGERED_POWERUP);
                                }
                                powerUp.StartPickupAnimation();
                                aircraft.ChangePowerUpCount(powerUp.Power, 1);
                                PowerUps.Remove(powerUp);
                                break;
                            }
                        }
                    }
                }
                // DEBUG: Console.WriteLine("EXECUTING ORDERS; dt: " + dt);
                // go through all aircrafts and let them execute their orders
                List <Aircraft> aircraftToBeRemoved = new List <Aircraft>();
                // first the enemies (organized into squadrons)
                foreach (var aircraft in ActiveAircrafts)
                {
                    aircraft.ExecuteOrders(dt);
                    if (aircraft.ToBeRemoved)
                    {
                        aircraftToBeRemoved.Add(aircraft);
                    }
                }
                // then the player aircrafts
                foreach (var aircraft in PlayerAircrafts)
                {
                    aircraft.ExecuteOrders(dt);
                    if (aircraft.ToBeRemoved)
                    {
                        aircraftToBeRemoved.Add(aircraft);
                    }
                }
                // remove aircrafts that have to be removed
                foreach (var aircraft in aircraftToBeRemoved)
                {
                    if (!aircraft.ControlledByPlayer)
                    {
                        // add a powerup
                        if ((new Random()).Next(3) < 2)
                        {
                            var powerUp = aircraft.GeneratePowerUp();
                            if (powerUp != null)
                            {
                                powerUp.Position = aircraft.Position;
                                AddPowerUp(powerUp);
                            }
                        }
                    }
                    // add an explosion
                    var cloudNode = new CloudTailNode();
                    cloudNode.AddCloud(new CircleCloud(aircraft.Position, 0, CCColor4B.White, true, aircraft.ContentSize.Width * 16, 6f));
                    ExplosionNodes.Add(cloudNode);

                    // if the aircraft is not completely made up of scrap parts add it to the salvageable wrecks
                    foreach (var part in aircraft.TotalParts)
                    {
                        if (!(part is BodyScrap) && !(part is DoubleWingScrap) && !(part is RotorScrap) && !(part is RudderScrap) && !(part is WeaponScrap))
                        {
                            DownedAircrafts.Add(aircraft);
                            break;
                        }
                    }
                    RemoveAircraft(aircraft);
                }
                // go through all projectiles and let them advance
                // check whether a projectile needs to be removed
                List <Projectile> projectilesToBeRemoved = new List <Projectile>();
                foreach (var projectile in Projectiles)
                {
                    projectile.Advance(dt);
                    if (projectile.CanBeRemoved())
                    {
                        projectilesToBeRemoved.Add(projectile);
                    }
                }
                // go through all clouds that are directly bounds to you
                List <CloudTailNode> cloudsToBeRemoved = new List <CloudTailNode>();
                foreach (var cloudNode in ExplosionNodes)
                {
                    cloudNode.Advance(dt);
                    if (!cloudNode.HasClouds())
                    {
                        cloudsToBeRemoved.Add(cloudNode);
                    }
                }
                foreach (var cloudNode in cloudsToBeRemoved)
                {
                    ExplosionNodes.Remove(cloudNode);
                }
                UpdateDrawNodes();
                if (TimeLeftExecutingOrders <= 0)
                {
                    StartPlanningPhase();
                }
            }
            break;
            }
        }
        internal void CalculatePath(CCPoint startPosition, float startSlopeDx, float startSlopeDy, CCPoint endPosition, float endSlopeDx = float.NaN, float endSlopeDy = float.NaN)
        {
            //List<CCPoint> pathPoints = new List<CCPoint>();
            // fixes for numerical problems
            if (startSlopeDx < 0.0001 && 0 < startSlopeDx)
            {
                startSlopeDx = 0.001f;
            }
            if (startSlopeDx > -0.0001 && 0 > startSlopeDx)
            {
                startSlopeDx = -0.001f;
            }
            if (startSlopeDy < 0.0001 && 0 < startSlopeDy)
            {
                startSlopeDy = 0.001f;
            }
            if (startSlopeDy > -0.0001 && 0 > startSlopeDy)
            {
                startSlopeDy = -0.001f;
            }
            if (startSlopeDx == 0)
            {
                startSlopeDx = 0.001f;
            }
            if (startSlopeDy == 0)
            {
                startSlopeDy = 0.001f;
            }

            /*
             * // ALTERNATIVE METHOD:
             * // create a path that is a circular arc
             * // for this 1. find the rotational center
             * // 2. rotate the start point towards the end point around the rotational center, step by step, and add these points to the path
             *
             * // SPECIAL CASE: the path is a straight line
             * CCPoint normalizedVectorStartEnd = CCPoint.Normalize(endPosition - startPosition);
             * const float DELTA = 0.01f;
             * if (CCPoint.Distance(normalizedVectorStartEnd, new CCPoint(startSlopeDx, startSlopeDy)) < DELTA)
             * {
             *  pathPoints.Add(startPosition);
             *  pathPoints.Add(endPosition);
             * }
             *  // 1.1 solve yStart = -1/(dy/dx) * xStart + n  for n (line through start perpendicular to the start direction)
             *  // 1.2 get the midpoint between start and end
             *  // 1.3 solve yMid = -1/((endY-startY)/(endX-startX)) * xMid + n2  for n2 (line through midpoint perpendicular to the line from start to end)
             *  // 1.4 solve -1/(dy/dx) * x + n = -1/((endY-startY)/(endX-startX)) * x + n2  for x (intersection of the previous two lines, aka "the rotational center")
             *
             *  // 1.1
             *  // yStart = - dx/dy * xStart + n
             *  // yStart + dx/dy * xStart = n
             *  float n = startPosition.Y + (startSlopeDx / startSlopeDy) * startPosition.X;
             *  // 1.2
             *  CCPoint midPoint = (endPosition + startPosition) / 2;
             *  // 1.3
             *  // yMid + ((endX-startX)/(endY-startY)) * xMid = n2
             *  float n2 = midPoint.Y + ((endPosition.X - startPosition.X) / (endPosition.Y - startPosition.Y)) * midPoint.X;
             *  // 1.4
             *  // - dx/dy * x + n = - ((endX-startX)/(endY-startY)) * x + n2
             *  // - dx/dy * x + ((endX-startX)/(endY-startY)) * x = n2 - n
             *  // x = (n2 - n) / ((dx/dy) - ((endX-startX)/(endY-startY)))
             *  float xRotCenter = (n2 - n) / (((endPosition.X - startPosition.X) / (endPosition.Y - startPosition.Y)) - (startSlopeDx / startSlopeDy));
             *  float yRotCenter = -(startSlopeDx / startSlopeDy) * xRotCenter + n;
             *  CCPoint rotationPoint = new CCPoint(xRotCenter, yRotCenter);
             *
             *  // 2.1 find out whether to rotate left or right
             *  // for that rotate the start-direction-vector by 90° and by -90° and check which rotated vector is closer to the rotation point
             *  CCPoint rotatedLeft = CCPoint.RotateByAngle(new CCPoint(startSlopeDx, startSlopeDy), CCPoint.Zero, (float)Math.PI / 2) + startPosition;
             *  CCPoint rotatedRight = CCPoint.RotateByAngle(new CCPoint(startSlopeDx, startSlopeDy), CCPoint.Zero, -(float)Math.PI / 2) + startPosition;
             *  float angleSign;
             *  if (CCPoint.Distance(rotatedLeft, rotationPoint) < CCPoint.Distance(rotatedRight, rotationPoint))
             *  {
             *      // the rotation point is on your left, so rotate to the left
             *      angleSign = 1;
             *  }
             *  else
             *  {
             *      // the rotation point is on your right, so rotate to the right
             *      angleSign = -1;
             *  }
             *
             *  // ALTERNATE PATH COMPUTATION:
             *  // compute the angle between the vectors starting at the rotational center and ending in a) the startpoint b) the endpoint.
             *  // The path points are then generated by rotating the startpoint (using that point for each rotation) and increasing the angle
             *  // of rotation until it reaches the computed angle between the vectors.
             *  // The number of steps is dependent on the length of the line, calculated from the radius * the angle.
             *  float radius = CCPoint.Distance(rotationPoint, startPosition);
             *  CCPoint normalizedVectorRotStart = CCPoint.Normalize(startPosition - rotationPoint);
             *  CCPoint normalizedVectorRotEnd   = CCPoint.Normalize(endPosition - rotationPoint);
             *  float angleStart = Constants.DxDyToRadians(normalizedVectorRotStart.X, normalizedVectorRotStart.Y);
             *  float angleEnd   = Constants.DxDyToRadians(normalizedVectorRotEnd.X, normalizedVectorRotEnd.Y);
             *  // make sure angles are positive
             *  if (angleStart < 0) angleStart = (float)(2.0 * Math.PI) + angleStart;
             *  if (angleEnd < 0) angleEnd = (float)(2.0 * Math.PI) + angleEnd;
             *  // normalize the angles
             *  float angleShift = (float)(2.0 * Math.PI) - angleStart;
             *  angleEnd = (angleEnd + angleShift) % (float)(2.0 * Math.PI);
             *  float angleDestination = angleSign == 1 ? angleEnd : (float)(2.0*Math.PI) - angleEnd;
             *  //int steps = (int)(radius * angleDestination);
             *  //if (steps < 200) steps = 200;
             *  int steps = 250;
             *  for (int i=0; i < steps; i++)
             *  {
             *      CCPoint pathPoint = CCPoint.RotateByAngle(startPosition, rotationPoint, angleSign * angleDestination * ((float)i / (float)steps));
             *      pathPoints.Add(pathPoint);
             *  }
             *  pathPoints.Add(endPosition);
             * }
             */
            // SPECIAL CASE: the path is a straight line
            CCPoint     normalizedVectorStartEnd = CCPoint.Normalize(endPosition - startPosition);
            const float DELTA = 0.01f;

            if (CCPoint.Distance(normalizedVectorStartEnd, new CCPoint(startSlopeDx, startSlopeDy)) < DELTA)
            {
                Path = new CCPoint[] { startPosition, endPosition };
            }
            else
            {
                // calculate a spline
                // as the first point of the input-path add a new point
                // this point realises the start slope
                float firstX = startPosition.X - startSlopeDx;
                float firstY = startPosition.Y - startSlopeDy;
                // also create another point as the third point
                // it makes sure that the plane HAS TO MOVE a little bit in a somewhat straight way first
                float secondX = startPosition.X + 1 * startSlopeDx;
                float secondY = startPosition.Y + 1 * startSlopeDy;
                float thirdX  = startPosition.X + 10 * startSlopeDx;
                float thirdY  = startPosition.Y + 10 * startSlopeDy;

                // now calculate a special midpoint; it strongly defines the curvature of the path
                // start with the midpoint between start and end
                CCPoint midpoint = new CCPoint((endPosition.X + startPosition.X) / 2, (endPosition.Y + startPosition.Y) / 2);
                // now we need the perpendicular line going through that point (midpoint.Y = (-1/m)*midpoint.X + np) (mp = -1/m)
                float m  = (endPosition.Y - startPosition.Y) / (endPosition.X - startPosition.X);
                float mp = -1 / m;
                float np = midpoint.Y - midpoint.X * mp;
                // now get the line extending from the starting point with the startSlope (startPosition.Y = startSlope*startPosition.X + ns)
                float ns = startPosition.Y - (startSlopeDy / startSlopeDx) * startPosition.X;
                // next find the intersection point that these lines form (startSlope*x + ns = mp*x + np)
                // x*(startSlope - mp) = np - ns;
                float x = (np - ns) / ((startSlopeDy / startSlopeDx) - mp);
                float y = mp * x + np;
                // finally, as the special curvature point calculate the midpoint between the start-end-midpoint and intersection point
                float curvaturePointX = midpoint.X + ((x - midpoint.X) / 3f);
                float curvaturePointY = midpoint.Y + ((y - midpoint.Y) / 3f);
                // ADDITIONAL PROCESS FOR REFINING THIS FURTHER:
                // first get the curvature point as a vector relative to the midpoint
                CCPoint curveVector = new CCPoint(curvaturePointX - midpoint.X, curvaturePointY - midpoint.Y);
                // if it's not (0,0) (i.e. if there is any curvature at all)
                float curveFactor         = 0;
                float halfDistance        = CCPoint.Distance(startPosition, midpoint);
                float magicDistanceFactor = halfDistance / 900f < 1 ? halfDistance / 900f : 1;
                if (!curveVector.Equals(CCPoint.Zero))
                {
                    // normalize it
                    curveVector = CCPoint.Normalize(curveVector);
                    // now we need to calculate the factor by which it is to be scaled
                    // for that we calculate the scalar product of the normalized direction vector of the starting slope and the normalized direction vector from start to end point
                    float scalarProduct = CCPoint.Dot(new CCPoint(startSlopeDx, startSlopeDy), CCPoint.Normalize(new CCPoint(endPosition.X - startPosition.X, endPosition.Y - startPosition.Y)));
                    // the larger this product, the less curvature
                    curveFactor = 1 - scalarProduct;
                    //Console.WriteLine("CurveVector: " + curveVector);
                    //Console.WriteLine("CurveFactor: " + curveFactor);
                    //Console.WriteLine("Distance: " + CCPoint.Distance(startPosition, midpoint));
                    // now calculate the curvature point
                    curvaturePointX = midpoint.X + curveVector.X * curveFactor * (1.3f - 0.8f * magicDistanceFactor) * halfDistance * (curveFactor > 1 ? -1 : 1);
                    curvaturePointY = midpoint.Y + curveVector.Y * curveFactor * (1.3f - 0.8f * magicDistanceFactor) * halfDistance * (curveFactor > 1 ? -1 : 1);
                    //Console.WriteLine("Midpoint: " + midpoint);
                    //Console.WriteLine("CurvaturePoint: " + curvaturePointX + "," + curvaturePointY);
                }
                float[] xValues, yValues;
                magicDistanceFactor = halfDistance / 900f;
                if (curveFactor / magicDistanceFactor > 0.55f)
                {
                    xValues = new float[] { startPosition.X, secondX, thirdX, curvaturePointX, endPosition.X };
                    yValues = new float[] { startPosition.Y, secondY, thirdY, curvaturePointY, endPosition.Y };
                }
                else
                {
                    xValues = new float[] { startPosition.X, secondX, thirdX, endPosition.X };
                    yValues = new float[] { startPosition.Y, secondY, thirdY, endPosition.Y };
                }
                //var xValues = new float[] { startPosition.X, curvaturePointX, endPosition.X };
                //var yValues = new float[] { startPosition.Y, curvaturePointY, endPosition.Y };
                CubicSpline.FitParametric(xValues, yValues, POINTS_PER_PATH / 4, out float[] pathX1, out float[] pathY1); // startSlopeDx, startSlopeDy, endSlopeDx, endSlopeDy);
                                                                                                                          // get the point before the endpoint to adjust the curvature
                float xBeforeEnd = pathX1[pathX1.Length - 2];
                float yBeforeEnd = pathY1[pathY1.Length - 2];
                if (curveFactor / magicDistanceFactor > 0.55f)
                {
                    xValues = new float[] { startPosition.X, secondX, thirdX, curvaturePointX, xBeforeEnd, endPosition.X };
                    yValues = new float[] { startPosition.Y, secondY, thirdY, curvaturePointY, yBeforeEnd, endPosition.Y };
                }
                else
                {
                    xValues = new float[] { startPosition.X, secondX, thirdX, xBeforeEnd, endPosition.X };
                    yValues = new float[] { startPosition.Y, secondY, thirdY, yBeforeEnd, endPosition.Y };
                }
                CubicSpline.FitParametric(xValues, yValues, POINTS_PER_PATH, out float[] pathX, out float[] pathY);
                var newPath = new CCPoint[pathX.Length];

                // for the output skip the first point (start slope point)
                // and replace it with the start point
                newPath[0] = startPosition;
                for (int i = 1; i < pathX.Length; i++)
                {
                    newPath[i] = new CCPoint(pathX[i], pathY[i]);
                }
                Path = newPath;
            }

            // calculate and update the PathLength
            var pathLength = 0f;

            for (int i = 0; i < Path.Length - 1; i++)
            {
                pathLength += Constants.DistanceBetween(Path[i], Path[i + 1]);
            }
            PathLength = pathLength;
            // reset the advancement to 0
            AdvancementAsQuasiIndex = 0f;
        }
Example #26
0
        private void HandleMoveCircle(CCTouch touch)
        {
            const float        timeToTake = 1.5f;      // in seconds
            CCFiniteTimeAction coreAction = null;

            CCNode nodeToAddTo = drawNodeRoot;

            switch (VariableOptions [currentVariableIndex])
            {
            case "Position":
                coreAction = new CCMoveTo(timeToTake, touch.Location);

                break;

            case "Scale":
                var distance     = CCPoint.Distance(touch.Location, drawNodeRoot.Position);
                var desiredScale = distance / DefaultCircleRadius;
                coreAction = new CCScaleTo(timeToTake, desiredScale);

                break;

            case "Rotation":
                float differenceY = touch.Location.Y - drawNodeRoot.PositionY;
                float differenceX = touch.Location.X - drawNodeRoot.PositionX;

                float angleInDegrees = -1 * CCMathHelper.ToDegrees(
                    (float)System.Math.Atan2(differenceY, differenceX));

                coreAction = new CCRotateTo(timeToTake, angleInDegrees);

                break;

            case "LineWidth":
                coreAction  = new LineWidthAction(timeToTake, touch.Location.X / 40.0f);
                nodeToAddTo = lineNode;
                break;
            }

            CCAction easing = null;

            switch (EasingOptions [currentEasingIndex])
            {
            case "<None>":
                // no easing, do nothing, it will be handled below
                break;

            case "CCEaseBack":
                if (currentInOutIndex == 0)
                {
                    easing = new CCEaseBackOut(coreAction);
                }
                else if (currentInOutIndex == 1)
                {
                    easing = new CCEaseBackIn(coreAction);
                }
                else
                {
                    easing = new CCEaseBackInOut(coreAction);
                }

                break;

            case "CCEaseBounce":
                if (currentInOutIndex == 0)
                {
                    easing = new CCEaseBounceOut(coreAction);
                }
                else if (currentInOutIndex == 1)
                {
                    easing = new CCEaseBounceIn(coreAction);
                }
                else
                {
                    easing = new CCEaseBounceInOut(coreAction);
                }

                break;

            case "CCEaseElastic":
                if (currentInOutIndex == 0)
                {
                    easing = new CCEaseElasticOut(coreAction);
                }
                else if (currentInOutIndex == 1)
                {
                    easing = new CCEaseElasticIn(coreAction);
                }
                else
                {
                    easing = new CCEaseElasticInOut(coreAction);
                }

                break;

            case "CCEaseExponential":
                if (currentInOutIndex == 0)
                {
                    easing = new CCEaseExponentialOut(coreAction);
                }
                else if (currentInOutIndex == 1)
                {
                    easing = new CCEaseExponentialIn(coreAction);
                }
                else
                {
                    easing = new CCEaseExponentialInOut(coreAction);
                }

                break;

            case "CCEaseSine":

                if (currentInOutIndex == 0)
                {
                    easing = new CCEaseSineOut(coreAction);
                }
                else if (currentInOutIndex == 1)
                {
                    easing = new CCEaseSineIn(coreAction);
                }
                else
                {
                    easing = new CCEaseSineInOut(coreAction);
                }

                break;
            }

            if (easing != null)
            {
                nodeToAddTo.AddAction(easing);
            }
            else
            {
                nodeToAddTo.AddAction(coreAction);
            }
        }
 /// <summary>
 /// called by the Aircraft owning the part owning this WeaponAbility each frame
 /// </summary>
 /// <param name="dt">time since the previous frame</param>
 internal void ExecuteOrders(float dt)
 {
     // cool down
     CooldownUntilNextShot -= dt;
     CooldownUntilNextTargetUpdate -= dt;
     if (CooldownUntilNextShot < 0) CooldownUntilNextShot = 0;
     // if you have a target check if it is still in range
     if (TargetPart != null)
     {
             CCPoint vectorMyPartTarget = TargetPart.PositionWorldspace - MyPart.PositionWorldspace;
             if (TargetPart.MyState == Part.State.DESTROYED || (TargetAircraft != null && TargetAircraft.MyState == Aircraft.State.SHOT_DOWN)
                 || CooldownUntilNextTargetUpdate <= 0
                 || CCPoint.Distance(MyPart.PositionWorldspace, TargetPart.PositionWorldspace) > AttentionRange
                 || Constants.AbsAngleDifferenceDeg(MyPart.TotalRotation - MyPart.RotationFromNull, Constants.DxDyToCCDegrees(vectorMyPartTarget.X, vectorMyPartTarget.Y)) > AttentionAngle)
                 TargetPart = null;
     }
     if (TargetPart == null && CooldownUntilNextTargetUpdate <= 0)     // if you currently do not aim at anything search for a target
     {
         CooldownUntilNextTargetUpdate = UpdateTargetDelay;
         // collect aircrafts that are near enough to have parts which could be targets
         // go through the parts of all of these planes and collect those that are in the attention angle
         PartsInRange(out List<Part> partsInRange, out List<float> anglesFromTo, out List<float> distances);
         // try to choose a part that is in reach
         // choose the part that is closest anglewise
         // but prioritize aircraft bodies:
         //  this means that you should only change target from a body to another part if the part you would choose instead (because it's closer)
         //  belongs to another plane
         float minAngle = float.PositiveInfinity;
         for (int i=0; i<partsInRange.Count(); i++)
         {
             if (distances[i] <= ShootingRange)  // first only try parts that are already in reach
             {
                 float absAngle = (float)Math.Abs(anglesFromTo[i]);
                 var part = partsInRange[i];
                 if (absAngle < minAngle) //&&
                     //(TargetPart == null || !(part.Parent == TargetPart.Parent && TargetPart == TargetAircraft.Body)))  // don't switch from a body to a different part of the same aircraft
                 {
                     TargetPart = part;
                     minAngle = absAngle;
                 }
             }
         }
         if (TargetPart == null) // if you found no target this way check the rest
         {
             minAngle = float.PositiveInfinity;
             for (int i = 0; i < partsInRange.Count(); i++)
             {
                 float absAngle = (float)Math.Abs(anglesFromTo[i]);
                 var part = partsInRange[i];
                 // now also try parts that are not already in reach
                 if (absAngle < minAngle) //&&
                     //(TargetPart == null || !(part.Parent == TargetPart.Parent && TargetPart == TargetAircraft.Body)))  // don't switch from a body to a different part of the same aircraft
                 {
                     TargetPart = part;
                     minAngle = absAngle;
                 }
             }
         }
     }
     // calculate the perfect point to aim for in order to hit the target
     if (TargetPart != null)
     {
         float angleToAimFor = AngleToAimFor();
         if (!(MyPart is WingJet))   // a dirty fix to make sure jet wings don't rotate since rotation screws up the flip state; for other weapons this effect can be neglected since it is only visual
         {
             float angleToTurnTo = angleToAimFor;
             float angleTurn = Constants.AngleFromToDeg(MyPart.NullRotation, angleToTurnTo);
             // make sure you don't rotate further than your MountPoint allows
             if (angleTurn > MyPart.MountPoint.MaxTurningAngle)
                 angleToTurnTo = MyPart.NullRotation + MyPart.MountPoint.MaxTurningAngle;
             else if (angleTurn < -MyPart.MountPoint.MaxTurningAngle)
                 angleToTurnTo = MyPart.NullRotation - MyPart.MountPoint.MaxTurningAngle;
             // make sure you don't rotate further than this weapons MaxTurningAngle allows
             if (MaxTurningAngle < MyPart.MountPoint.MaxTurningAngle)
             {
                 if (angleTurn > MaxTurningAngle)
                     angleToTurnTo = MyPart.NullRotation + MaxTurningAngle;
                 else if (angleTurn < -MaxTurningAngle)
                     angleToTurnTo = MyPart.NullRotation - MaxTurningAngle;
             }
             MyPart.RotateTowards(angleToTurnTo, TurningAnglePerSecond * dt);
         }
         // if you're now close enough to the perfect angle (and in range) start shooting
         if (CanShoot()
             && CCPoint.Distance(MyPart.PositionWorldspace, TargetPart.PositionWorldspace) <= ShootingRange
             && (Constants.AbsAngleDifferenceDeg(angleToAimFor, MyPart.MyRotation) <= ToleratedError || WouldHit()))
         {
             TryShoot();
         }
             
     }
     // and if you have no target try to get back to NullRotation
     else if (!(MyPart is WingJet))
     {
         MyPart.RotateTowards(MyPart.NullRotation, TurningAnglePerSecond * dt);
     }
 }
Example #28
0
        void HandleMoveCircle(CCTouch touch)
        {
            const float        timeToTake = 1.5f;      // in seconds
            CCFiniteTimeAction coreAction = null;

            // By default all actions will be added directly to the
            // root node - it has values for Position, Scale, and Rotation.
            CCNode nodeToAddTo = drawNodeRoot;

            switch (VariableOptions [currentVariableIndex])
            {
            case "Position":
                coreAction = new CCMoveTo(timeToTake, touch.Location);
                break;

            case "Scale":
                var distance     = CCPoint.Distance(touch.Location, drawNodeRoot.Position);
                var desiredScale = distance / DefaultCircleRadius;
                coreAction = new CCScaleTo(timeToTake, desiredScale);
                break;

            case "Rotation":
                float differenceY = touch.Location.Y - drawNodeRoot.PositionY;
                float differenceX = touch.Location.X - drawNodeRoot.PositionX;

                float angleInDegrees = -1 * CCMathHelper.ToDegrees(
                    (float)Math.Atan2(differenceY, differenceX));

                coreAction = new CCRotateTo(timeToTake, angleInDegrees);

                break;

            case "LineWidth":
                coreAction = new LineWidthAction(timeToTake, touch.Location.X / 40f);
                // The LineWidthAction is a special action designed to work only on
                // LineNode instances, so we have to set the nodeToAddTo to the lineNode:
                nodeToAddTo = lineNode;
                break;
            }

            CCAction easing = null;

            switch (EasingOptions [currentEasingIndex])
            {
            case "CCEaseBack":
                if (currentInOutIndex == 0)
                {
                    easing = new CCEaseBackOut(coreAction);
                }
                else if (currentInOutIndex == 1)
                {
                    easing = new CCEaseBackIn(coreAction);
                }
                else
                {
                    easing = new CCEaseBackInOut(coreAction);
                }

                break;

            case "CCEaseBounce":
                if (currentInOutIndex == 0)
                {
                    easing = new CCEaseBounceOut(coreAction);
                }
                else if (currentInOutIndex == 1)
                {
                    easing = new CCEaseBounceIn(coreAction);
                }
                else
                {
                    easing = new CCEaseBounceInOut(coreAction);
                }

                break;

            case "CCEaseElastic":
                if (currentInOutIndex == 0)
                {
                    easing = new CCEaseElasticOut(coreAction);
                }
                else if (currentInOutIndex == 1)
                {
                    easing = new CCEaseElasticIn(coreAction);
                }
                else
                {
                    easing = new CCEaseElasticInOut(coreAction);
                }

                break;

            case "CCEaseExponential":
                if (currentInOutIndex == 0)
                {
                    easing = new CCEaseExponentialOut(coreAction);
                }
                else if (currentInOutIndex == 1)
                {
                    easing = new CCEaseExponentialIn(coreAction);
                }
                else
                {
                    easing = new CCEaseExponentialInOut(coreAction);
                }

                break;

            case "CCEaseSine":
                if (currentInOutIndex == 0)
                {
                    easing = new CCEaseSineOut(coreAction);
                }
                else if (currentInOutIndex == 1)
                {
                    easing = new CCEaseSineIn(coreAction);
                }
                else
                {
                    easing = new CCEaseSineInOut(coreAction);
                }

                break;
            }

            nodeToAddTo.AddAction(easing ?? coreAction);
        }