public void SetDrawOffset(Vector2 offset)
        {
            _offset = new Vector2(MathHelper.Lerp(0, offset.X, _ratio), offset.Y);

            while (_offset.X < -_texture.Width)
            {
                _offset.X += _texture.Width;
            }
            while (_offset.X > _texture.Width)
            {
                _offset.X -= _texture.Width;
            }

            if (_offset.X > 0)
            {
                _offset2 = new Vector2(-_texture.Width + _offset.X, _offset.Y);
            }
            else if (_offset.X < -_texture.Width + _sb.GraphicsDevice.Viewport.Width)
            {
                _offset2 = new Vector2(_offset.X + _texture.Width, _offset.Y);
            }
            else
            {
                _offset2 = null;
            }
        }
Esempio n. 2
0
    private void drawWhiteboard(RaycastHit hit, string side)
    {
        //Debug.DrawLine(ray.origin, hit.point);
        Renderer rend = hit.transform.GetComponent<Renderer>();
        Texture2D tex = rend.material.mainTexture as Texture2D;
        Vector2 pixelUV = hit.textureCoord;
        pixelUV.x *= tex.width;
        pixelUV.y *= tex.height;
        Vector2 thisMark = new Vector2 (pixelUV.x, pixelUV.y);
        if (thisMark.x == 0 && thisMark.y == 0)
            return;
        if (side == "left") {
            if(lastMarkLeft == null)
                lastMarkLeft = thisMark;
        } else if (side == "right") {
            if(lastMarkRight == null)
                lastMarkRight = thisMark;
        }

        Vector2 lastMark = (Vector2)(side == "left" ? lastMarkLeft : lastMarkRight);
        //drawCircle(tex, (Vector2) (side == "left" ? lastMarkLeft : lastMarkRight), thisMark, markerRadius, markerColor);
        this.photonView.RPC("ChatMessage", PhotonTargets.All, hit.transform.name, ((int)lastMark.x).ToString (), ((int)lastMark.y).ToString (), ((int)pixelUV.x).ToString(), ((int)pixelUV.y).ToString(), markerRadius.ToString(), markerColor.ToString());

        if (side == "left") {
            lastMarkLeft = new Vector2 (pixelUV.x, pixelUV.y);
        } else if (side == "right") {
            lastMarkRight = new Vector2 (pixelUV.x, pixelUV.y);
        }
    }
        public override void Render(IGameContext gameContext, IRenderContext renderContext)
        {
            base.Render(gameContext, renderContext);

            if (renderContext.IsCurrentRenderPass<I2DDirectRenderPass>())
            {
                if (_analyzerEntity.TopLeftNormalized != null && _analyzerEntity.TopRightNormalized != null &&
                    _analyzerEntity.BottomLeftNormalized != null && _analyzerEntity.BottomRightNormalized != null)
                {
                    _cachedTopLeft = _analyzerEntity.TopLeftNormalized;
                    _cachedTopRight = _analyzerEntity.TopRightNormalized;
                    _cachedBottomLeft = _analyzerEntity.BottomLeftNormalized;
                    _cachedBottomRight = _analyzerEntity.BottomRightNormalized;
                }

                if (_cachedTopLeft != null && _cachedTopRight != null &&
                    _cachedBottomLeft != null && _cachedBottomRight != null)
                { 
                    _warpFromPolygonEffect.Effect.Parameters["TopLeft"].SetValue(_cachedTopLeft.Value);
                    _warpFromPolygonEffect.Effect.Parameters["TopRight"].SetValue(_cachedTopRight.Value);
                    _warpFromPolygonEffect.Effect.Parameters["BottomLeft"].SetValue(_cachedBottomLeft.Value);
                    _warpFromPolygonEffect.Effect.Parameters["BottomRight"].SetValue(_cachedBottomRight.Value);
                    _warpFromPolygonEffect.Effect.Parameters["Alpha"].SetValue(_alpha);

                    _graphicsBlit.Blit(
                        renderContext,
                        _webcamEntity.VideoCaptureFrame,
                        null,
                        _warpFromPolygonEffect.Effect,
                        BlendState.AlphaBlend);
                }
            }
        }
Esempio n. 4
0
        public void Input(MouseState ms, MouseState oms)
        {
            if (!Game.HasFocus) return;
            float _zoom = (Game.ScreenSize.X / (float)Rectangle.Width);

            if (
                ms.MiddleButton == ButtonState.Pressed &&
                oms.MiddleButton == ButtonState.Released)
                cameraStartGrab = new Vector2(ms.X, ms.Y);

            if (
                ms.MiddleButton == ButtonState.Released &&
                oms.MiddleButton == ButtonState.Pressed)
                cameraStartGrab = null;

            if (cameraStartGrab != null)
            {
                X += (int)((cameraStartGrab.Value.X - ms.X) / GetZoom());
                Y += (int)((cameraStartGrab.Value.Y - ms.Y) / GetZoom());
                cameraStartGrab = new Vector2(ms.X, ms.Y);
            }
            else //don't zoom/pan and stuff while mm dragging
            {
                int _scrollSpeed = (int)(9f / _zoom);
                if (ms.X > Game.ScreenSize.X)
                    Rectangle.X += _scrollSpeed;
                if (ms.Y > Game.ScreenSize.Y)
                    Rectangle.Y += _scrollSpeed;
                if (ms.X < 0)
                    Rectangle.X -= _scrollSpeed;
                if (ms.Y < 0)
                    Rectangle.Y -= _scrollSpeed;

                int _preW = Rectangle.Width;
                int _preH = Rectangle.Height;

                float _zoomSpeed = 1.1f;

                Rectangle.Width =
                    (int)(Rectangle.Width * 1 +
                    (Game.MouseWheelDelta * 120 * _zoomSpeed));
                Rectangle.Height =
                    (int)(Rectangle.Width * (9f / 16f));
                _zoom = (Game.ScreenSize.X / (float)Rectangle.Width);

                //work more on this to avoid glitching "through" the world
                if (_zoom > 6)
                {
                    Rectangle.Width = (int)Game.ScreenSize.X / 6;
                    Rectangle.Height = (int)Game.ScreenSize.Y / 6;
                }

                Rectangle.X -= (int)(
                    (Rectangle.Width - _preW) *
                    (ms.X / (Game.ScreenSize.X / 2f)) / 2f);
                Rectangle.Y -= (int)(
                    (Rectangle.Height - _preH) *
                    (ms.Y / (Game.ScreenSize.Y / 2f)) / 2f);
            }
        }
Esempio n. 5
0
        public void Update(Area area, GameTime gameTime)
        {
            OnUpdate(area, gameTime);

            // Bewegung
            if (destination.HasValue)
            {
                Vector2 expectedDistance = destination.Value - startPoint.Value;
                Vector2 currentDistance = Host.Position - startPoint.Value;

                // Prüfen ob das Ziel erreicht (oder überschritten) wurde.
                if (currentDistance.LengthSquared() > expectedDistance.LengthSquared())
                {
                    startPoint = null;
                    destination = null;
                    Host.Velocity = Vector2.Zero;
                }
                else
                {
                    // Kurs festlegen
                    Vector2 direction = destination.Value - Host.Position;
                    direction.Normalize();
                    Host.Velocity = direction * speed * Host.MaxSpeed;
                }
            }
        }
    void Update() {
        // Begin dragging if they user clicks
        if (dragStart == null && Input.GetMouseButton(0)) dragStart = (Input.mousePosition);
        // Update the drag if they are still clicking
        if (dragStart != null) {
            if (Input.GetMouseButton(0)) dragEnd = (Input.mousePosition);
            UpdateSelection(Input.mousePosition);
            if (Input.GetMouseButtonUp(0)) {
                EndSelection(Input.mousePosition);
            }
        }
        // Give units orders
        if (Input.GetMouseButtonDown(1)) {
            CommandAtRay(Input.mousePosition);
        }

        // Delete the selection if the user presses delete
        if (Input.GetKeyDown(KeyCode.Delete)) {
            for (int s = Selected.Count - 1; s >= 0; --s) {
                var selected = Selected[s];
                if (selected != null) {
                    var entity = selected;
                    if (entity != null) entity.Die();
                }
            }
            ClearSelected();
        }
    }
Esempio n. 7
0
        public override void Update(GameTime gameTime)
        {
            if (currentForce != null)
            {
                velocity += currentForce.Value * (float)gameTime.ElapsedGameTime.TotalSeconds * Speed;
                ttl -= gameTime.ElapsedGameTime.TotalSeconds;
                if (ttl <= 0)
                {
                    currentForce = null;
                }
            }

            foreach (var obj in container)
            {
                if (obj != this)
                {
                    var sphere = obj as HeavenlySphere;
                    if (sphere != null)
                    {
                        var delta = Vector2.Normalize(sphere.Position - Position);
                        velocity += delta * (sphere.Mass / delta.LengthSquared() * (float)gameTime.ElapsedGameTime.TotalSeconds);
                    }
                }
            }

            Position += velocity * (float)gameTime.ElapsedGameTime.TotalSeconds;
        }
        public FingerRunnerPlayer(GamePlayer player, Rectangle bounds, bool flip)
        {
            Player = player;
            Flip = flip;

            _bounds = bounds;
            _leftFootLoc = _rightFootLoc = null;
            _position = new Vector2(0, 0);
            _hurdleLoc = null;
            _speed = new Vector2(0, 0);
            _footDownMarks.Clear();
            _isOnLeft = true;
            _shouldSpeedUp = false;

            int topA = (flip) ? 0 : 315;
            int botA = (flip) ? 0 : 320;

            LeftBorder = new Rectangle(bounds.Left, topA, 165, 165);
            RightBorder = new Rectangle(bounds.Left + bounds.Width - 165, topA, 165, 165);
            LeftBox = new Rectangle(bounds.Left, botA, 160, 160);
            RightBox = new Rectangle(bounds.Left + bounds.Width - 160, botA, 160, 160);

            _leftFootSound = FingerRunnerGame._leftFootDrum.CreateInstance();
            _rightFootSound = FingerRunnerGame._rightFootDrum.CreateInstance();
        }
        /*--------------------------------------------------------------------------------------------*/
        public void SetRectLayout(float pSizeX, float pSizeY, ISettingsController pController)
        {
            Controllers.Set(OuterRadiusName, pController);

            OuterRadius = Mathf.Min(pSizeX, pSizeY)/2;
            vRectSize = new Vector2(pSizeX, pSizeY);
        }
Esempio n. 10
0
	void Update () {
	
		if ( !Input.GetMouseButton(0) )
		{
			mDragStart = null;
			return;
		}

		//	first touch
		if (mDragStart == null)
			mDragStart = Input.mousePosition;

		var Mouse2 = new Vector2 (Input.mousePosition.x, Input.mousePosition.y);
		Vector2 Delta2 = (Mouse2 - mDragStart.Value);

#if UNITY_ANDROID
		Delta2.x *= -1.0f;
		Delta2 *= 1.3f;
#endif

		Delta2.Scale( new Vector2( 1.0f/Screen.width, 1.0f/Screen.height ) );

		Delta2.Scale (new Vector2 (mFlySpeed, mPanSpeed));
		Debug.Log("Mouse delta = " + Mouse2 );

		mCameraPositioner.transform.position += mCamera.transform.forward * Delta2.x;
		mCameraPositioner.transform.position += mCamera.transform.up * Delta2.y;

	}
        public override bool ProcessSceneEvents()
        {
            switch (Event.current.type) {
                case EventType.MouseDown:
                    _dragStart = Event.current.mousePosition;
                    _isDragging = false;
                    break;
                case EventType.MouseDrag:
                    if (_dragStart.HasValue) {
                        _selectionRectangle = new Rect(_dragStart.Value, Event.current.mousePosition - _dragStart.Value);
                        _isDragging = true;
                        SceneView.RepaintAll();
                    }
                    break;
                case EventType.Ignore:
                case EventType.MouseUp:
                    if (_isDragging) {
                        CompleteSelection();
                    }
                    break;
                case EventType.Repaint:
                    if (_isDragging) {
                        Utils.DrawSelectionRectangle(_selectionRectangle);
                    }
                    break;
                case EventType.KeyDown:
                    if (Event.current.keyCode == KeyCode.LeftAlt) {
                        Event.current.Use();
                    }
                    break;
            }

            return true;
        }
Esempio n. 12
0
 public MouseMove(ReactiveMouse mouse, Point screenPosition, Point screenDelta, Vector2? worldPosition, Vector2? worldDelta)
 {
     this.Mouse = mouse;
     this.ScreenPosition = screenPosition;
     this.ScreenDelta = screenDelta;
     this.WorldPosition = worldPosition;
     this.WorldDelta = worldDelta;
 }
        public SlidingSprite(Texture2D texture, Vector2 position, Color tintColor)
            : base(texture, position, tintColor)
        {
            _slideTo = null;
            SlideUpdateCount = 100;

            _currentStep = null;
        }
Esempio n. 14
0
 public Vector2 Position()
 {
     if (position == null)
     {
         position = CustomVector.GetFromString(gameObject.name);
     }
     return (Vector2)position;
 }
    // Update is called once per frame
    void Update()
    {
        if(_dungeon == null)
        {
            return;
        }

        if( route.Count == 0)
        {
            // obtain new globalTarget
            int x = Random.Range(1, _dungeon.GetLength(0)-1);
            int y = Random.Range(1, _dungeon.GetLength(1)-1);
            while(_dungeon[x,y] == (int) TileContent.wall)
            {
                x = Random.Range(1, _dungeon.GetLength(0)-1);
                y = Random.Range(1, _dungeon.GetLength(1)-1);
            }

            globalTarget = new Vector2(x,y);

            // obtain route
            route = Pathfinder.FindPath(_dungeon, (int) Mathf.Round(_self.position.x/CONSTANTS.TileSize),
                (int) Mathf.Round(_self.position.y/CONSTANTS.TileSize), x,y);

            if(route == null)
            {
                //print ("ERROR??!?");
                return;
            }

            //print(route.Count);
            if(_targetEffect != null)
            {
                OT.DestroyObject(_targetEffect);
            }
            SpawnEffect(globalTarget.Value*CONSTANTS.TileSize);

            currentTarget = route.Pop();
        }
        else
        {
            // check if close enough to target
            Vector2 diff = new Vector2((currentTarget.Value.x*CONSTANTS.TileSize-_self.position.x),
                (currentTarget.Value.y*CONSTANTS.TileSize-_self.position.y));
            if(diff.magnitude < 5)
            {
                currentTarget = route.Pop();
            }
            else
            {
                // if too far, advance...
                diff.Normalize();
                _self.position += 500f* diff*Time.deltaTime;
            }

        }
    }
Esempio n. 16
0
 /// <summary>
 /// Converte un Vector2 a asse di gioco
 /// </summary>
 /// <param name="assi"></param>
 /// <returns></returns>
 public Vector2? convertiAssiAPosRelativo(Vector2 assi)
 {
     Vector2? risultato = new Vector2?(new Vector2(Mathf.RoundToInt(assi.x - 0.5f - transform.position.x + 10),Mathf.RoundToInt(assi.y - 0.5f - transform.position.z + 10)));
     if((risultato.Value.x < 0 || risultato.Value.x >= 20) || (risultato.Value.y < 0 || risultato.Value.y >= 20)){
         return new Vector2?();
     }else{
         return risultato;
     }
 }
Esempio n. 17
0
 internal PanelSpecification(IApi platform)
 {
     panelPhysicalSize = platform.sys_GetPrimaryPanelPhysicalSize ();
     panelPhysicalAspectRatio =
         panelPhysicalSize.HasValue
             ? (Single) panelPhysicalSize.Value.X / (Single) panelPhysicalSize.Value.Y
             : (Single?) null;
     panelType = platform.sys_GetPrimaryPanelType ();
 }
Esempio n. 18
0
 public FreeRoamCamera(Vector2 viewMiddle)
 {
     this.position = new Vector3(5200f, 5200f, 20f);
     this.lastMousePosition = null;
     this.view = Matrix.Invert(FreeRoamCamera.roseCoordinate * Matrix.CreateTranslation(this.position));
     this.yawpitchroll.X = 0f;
     this.yawpitchroll.Y = 0f;
     this.yawpitchroll.Z = 0f;
     this.viewMiddle = viewMiddle;
 }
        private void CompleteSelection()
        {
            IEnumerable<int> selectedVertices = Editor.GetVerticesInRect(_selectionRectangle);
            if (Event.current.shift) {
                selectedVertices = selectedVertices.Concat(Editor.SelectedVertices);
            }
            Editor.SelectedVertices = new HashSet<int>(selectedVertices);

            _isDragging = false;
            _dragStart = null;
        }
 public MyGuiScreenEditorObject3DBase(MyEntity physObject, Vector2 position, Vector4 backgroundColor, Vector2? size, MyTextsWrapperEnum caption, Vector2? screenPosition = null)
     : base(position, backgroundColor, size)
 {
     m_caption = caption;
     m_newObjectPosition = MySpectator.Target + 2000 * MySpectator.Orientation;
     m_entity = physObject;
     m_backgroundFadeColor = MyGuiConstants.SCREEN_BACKGROUND_FADE_BLANK_DARK;
     m_backgroundFadeColor.W = 0.75f;
     m_screenPosition = screenPosition;
     this.OnEnterCallback = OnEnterClick;
 }
Esempio n. 21
0
 void Update()
 {
     if (targetPosition == null) { return; }
     if (remainingmMoveTime <= 0) { return; }
     var direction = targetPosition.Value - (Vector2)transform.position;
     if (direction.sqrMagnitude < stopRadius * stopRadius) {
         targetPosition = null;
     } else {
         body.velocity = direction.normalized * maxSpeed;
         remainingmMoveTime -= Time.deltaTime;
     }
 }
Esempio n. 22
0
        public override void Init(PloobsEngine.Engine.GraphicInfo ginfo, PloobsEngine.Engine.GraphicFactory factory)
        {
            switch (BlurRadiusSize)
            {
                case BlurRadiusSize.Fifteen:
                    effect = factory.GetEffect("sblur", true,true); 
                    break;
                case BlurRadiusSize.Seven:
                    effect = factory.GetEffect("sblur2", true, true); 
                    break;
                case BlurRadiusSize.Three:
                    effect = factory.GetEffect("sblur3", true, true); 
                    break;
                default:
                    ActiveLogger.LogMessage("Wrong Blur Radius Size Specified", LogLevel.RecoverableError);
                    effect = factory.GetEffect("sblur", true, true); 
                    break;
            }

            if (!destinySize.HasValue)
            {
                destinySize = new Vector2(ginfo.BackBufferWidth, ginfo.BackBufferHeight);
            }

            if (SurfaceFormat.HasValue)
            {
                if (SurfaceFormat.Value == Microsoft.Xna.Framework.Graphics.SurfaceFormat.Single ||
                    SurfaceFormat.Value == Microsoft.Xna.Framework.Graphics.SurfaceFormat.HalfSingle)
                {
                    effect.CurrentTechnique = effect.Techniques["GAUSSSingle"];
                }
                else
                {
                    effect.CurrentTechnique = effect.Techniques["GAUSSTriple"];
                }
                RenderTarget2D = factory.CreateRenderTarget((int)destinySize.Value.X, (int)destinySize.Value.Y, SurfaceFormat.Value);
            }
            else
            {
                RenderTarget2D = factory.CreateRenderTarget(ginfo.BackBufferWidth, ginfo.BackBufferHeight);                
            }

            ComputeKernel(BLUR_RADIUS, BLUR_AMOUNT);
            if (OriginSize.HasValue)
            {
                ComputeOffsets(OriginSize.Value.X, OriginSize.Value.Y);
            }
            else
            {
                ComputeOffsets(ginfo.BackBufferWidth, ginfo.BackBufferHeight);
            }
        }
Esempio n. 23
0
    // Update is called once per frame
    void FixedUpdate()
    {
        float movev = Input.GetAxis("Vertical");
        float moveh = Input.GetAxis("Horizontal");
        var move = new Vector2(moveh, movev).normalized;
        player.velocity = new Vector2(move.x * speed, move.y * speed);

        if (move.sqrMagnitude > 0) {
            float x = 0, y = 0;
            if (move.x > 0) {
                x = Mathf.Floor((player.transform.position.x + snap) / snap) * snap;
            } else if (move.x < 0) {
                x = Mathf.Ceil((player.transform.position.x - snap) / snap) * snap;
            } else {
                x = Mathf.RoundToInt(player.transform.position.x / snap) * snap;
            }

            if (move.y > 0) {
                y = Mathf.Floor((player.transform.position.y + snap) / snap) * snap;
            } else if (move.y < 0) {
                y = Mathf.Ceil((player.transform.position.y - snap) / snap) * snap;
            } else {
                y = Mathf.RoundToInt(player.transform.position.y / snap) * snap;
            }

            target = new Vector2(x, y);
        } else if (target.HasValue) {
            player.MovePosition(Vector2.MoveTowards(player.position, target.Value, speed * Time.deltaTime));
            if (player.position == target.Value) {
                target = null;
            }
        }

        anim.SetFloat("Speed", player.velocity.magnitude);
        var normalizedir = player.velocity.normalized;
        if (player.velocity.magnitude > 0.5f) {
            if (Mathf.Abs(normalizedir.x) > Mathf.Abs(normalizedir.y)) {
                //moving right
                if (normalizedir.x > 0) {
                    anim.Play("Right");
                } else {
                    anim.Play("Left");
                }
            } else {
                if (normalizedir.y > 0) {
                    anim.Play("Up");
                } else {
                    anim.Play("Down");
                }
            }
        }
    }
Esempio n. 24
0
 private void DeadzoneMonitor()
 {
     if(!_isDrawingDeadzone) return;
     if (_firstPoint.HasValue && _secondPoint.HasValue)
     {
         _settings.Deadzones.Add(new Deadzone(_firstPoint.Value.X, _firstPoint.Value.Y, _secondPoint.Value.X - _firstPoint.Value.X, _secondPoint.Value.Y - _firstPoint.Value.Y));
         _settingsMenu.DeadzoneMenu.AddItem(new UIMenuItem("Deadzone #" + _settings.Deadzones.Count, "Select to remove."));
         _settingsMenu.DeadzoneMenu.RefreshIndex();
         _firstPoint = null;
         _secondPoint = null;
         _isDrawingDeadzone = false;
     }
 }
Esempio n. 25
0
        /// <summary>
        ///  Give priority to mouse.
        /// </summary>
        public void Update()
        {
            _clickedLocation = null;
            if (_touchWrapper.IsSupported())
                _clickedLocation = _touchWrapper.GetTouchPoint();

            MouseState mouseState = Mouse.GetState();
            if (mouseState.LeftButton == ButtonState.Pressed && !_mouseDownLastFrame)
            {
                _clickedLocation = new Vector2(mouseState.X, mouseState.Y);
            }

            _mouseDownLastFrame = mouseState.LeftButton == ButtonState.Pressed;
        }
 public FontProperties( Color? color                = null
                      , double rotation             = 0
                      , Vector2? scale              = null
                      , Vector2? origin             = null 
                      , SpriteEffects spriteEffects = SpriteEffects.None
                      , bool originIsRelative       = false )
 {
     Tint = color;
     Rotation = rotation;
     Scale = scale;
     Origin = origin.HasValue ? origin.Value : Vector2.Zero;
     SpriteEffects = spriteEffects;
     OriginIsRelative = originIsRelative;
 }
Esempio n. 27
0
        public void Apply()
        {
            if (mWarriors.Count == 0)
                return;
            if (mHasUnited)
            {
                // Just attack the sector's first unit:
                Vector2 target = GetFirstAttackableUnit().Position;
                foreach (IMovable warrior in mWarriors)
                {
                    mParent.AggressiveMove(warrior, target);
                }
            }
            else
            {
                // Move warriors to meeting point first
                if (mWarriorCenter == null)
                {
                    mWarriorCenter = CalcWarriorCenter();
                    foreach (IMovable warrior in mWarriors)
                        warrior.MoveTo((Vector2)mWarriorCenter);
                    // Now determine longest update counter and set timeout until we
                    // assume union has been successful:
                    long maxUpdatesTillUnion = 0;
                    foreach (IMovable warrior in mWarriors)
                    {
                        long updates = ((Spaceship)warrior).GetFreeMovement().GetPathUpdateCount();
                        Debug.Assert(updates >= 0);
                        if (updates > maxUpdatesTillUnion)
                            maxUpdatesTillUnion = updates;
                    }
                    mTimeoutForUnion = maxUpdatesTillUnion + 20;
                    //Debug.WriteLine("AI: mTimeoutForUnion = " + mTimeoutForUnion);
                }
                else
                {
                    // Move units to center meeting point, decrease timeout for union,
                    // and check if we may assume the union:
                    foreach (IMovable warrior in mWarriors)
                        mParent.AggressiveMove(warrior, (Vector2)mWarriorCenter);
                    //Debug.WriteLine("timeout: "+ mTimeoutForUnion);

                    if (mTimeoutForUnion <= 0)
                    {
                        //Debug.WriteLine("AI: Crusading group has united, now attack target");
                        mHasUnited = true;
                    }
                }
            }
        }
Esempio n. 28
0
        public RadialGradientBrush(GradientStop[] gradientStops, Vector2 center, float radiusX, float radiusY, float angle = 0f, Vector2? focusPoint = null)
        {
            if (gradientStops.Length > MaximumGradientColorCount)
                throw new ArgumentOutOfRangeException(nameof(gradientStops));
            if (radiusX < 0) throw new ArgumentOutOfRangeException(nameof(radiusX));
            if (radiusY < 0) throw new ArgumentOutOfRangeException(nameof(radiusY));

            this.gradientStops = gradientStops;
            Center = center;
            this.radiusX = radiusX;
            this.radiusY = radiusY;
            Angle = angle;
            FocusPoint = focusPoint;
        }
Esempio n. 29
0
    private void Awake()
    {
        matchmanager = FindObjectOfType<MatchManager>();
        if (matchmanager == null) Debug.LogError("MatchManager not found");
        matchmanager.RegisterBall(this);

        // start pos (set by first ball)
        if (start_pos == null) start_pos = transform.position;
        else transform.position = (Vector2)start_pos;

        // other
        camshake = Camera.main.GetComponent<CameraShake>();
        ball_audio = GetComponentInChildren<BallAudio>();
    }
Esempio n. 30
0
        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            if (DestinationRect.Contains(Input.X, Input.Y) && Texture != null)
            {
                int texWidth = SourceRect == null ? Texture.Width : SourceRect.Value.Width;
                int texHeight = SourceRect == null ? Texture.Height : SourceRect.Value.Height;

                if (Input.WheelDelta != 0)
                    Zoom += 10 * Zoom / Input.WheelDelta;
                Zoom = MathUtil.Clamp(Zoom, 0.05f, 1f);

                if (Input.MiddleButton.Down)
                    Position -= new Vector2(Input.XDelta, Input.YDelta) * Zoom;
                Vector2 max = new Vector2((float)(texWidth - DestinationRect.Width * ratioWPixelScreenPicture),
                            (float)(texHeight - DestinationRect.Height * ratioHPixelScreenPicture));
                max.X = max.X < 0 ? 0 : max.X;
                max.Y = max.Y < 0 ? 0 : max.Y;
                Position = DrawHelper.ClampVector(Position, Vector2.Zero, max);

                if (Input.LeftButton.Pressed)
                {
                    if (SelectionMode)
                    {
                        isSelecting = true;
                        SelectedRectangle = null;
                        selectionStartPoint = ConvertScreenToPicture(new Vector2(Input.X, Input.Y));
                    }
                }
                if (Input.RightButton.Pressed)
                {
                    if (SelectPointMode)
                        SelectedPoint = ConvertScreenToPicture(new Vector2(Input.X, Input.Y));
                }
            }

            if (Input.LeftButton.Released && isSelecting == true)
            {
                isSelecting = false;
                Vector2 selectionEndPoint = ConvertScreenToPicture(new Vector2(Input.X, Input.Y));
                Rectangle selectionRect = new Rectangle();
                selectionRect.Left = Math.Min((int)selectionStartPoint.X, (int)selectionEndPoint.X);
                selectionRect.Right = Math.Max((int)selectionStartPoint.X, (int)selectionEndPoint.X) + 1;
                selectionRect.Top = Math.Min((int)selectionStartPoint.Y, (int)selectionEndPoint.Y);
                selectionRect.Bottom = Math.Max((int)selectionStartPoint.Y, (int)selectionEndPoint.Y) + 1;
                SelectedRectangle = selectionRect;
            }
        }
Esempio n. 31
0
    private void MobileUpdate()
    {
        //CoolDown management
        if (coolDownAccumulated < playerSettings.GetCoolDownTime())
        {
            coolDownAccumulated += Time.deltaTime;
        }

        if (Input.touchCount == 1)
        {
            int fingerID = Input.GetTouch(0).fingerId;
            if (!buttonPressed.IsButtonPressed() && Input.GetTouch(0).phase == TouchPhase.Ended && !IsPointerOverUIObject())
            {
                Vector3 raycastHit = getRayCastPoint(Input.GetTouch(0).position);
                if (raycastHit != Vector3.zero)
                {
                    if (dashed && touchStartPosition != null && IsDashLongEnough(Input.GetTouch(0).position))
                    {
                        Debug.Log("DASH");
                        navMeshAgent.destination = Flash(raycastHit);
                        return;
                    }
                    else
                    {
                        navMeshAgent.destination = raycastHit;
                        navMeshAgent.isStopped   = false;
                    }
                }

                dashed             = false;
                touchStartPosition = null;
            }
            else if (Input.GetTouch(0).phase == TouchPhase.Moved)
            {
                Debug.Log("MOVED");
                dashed = true;
            }
            else if (Input.GetTouch(0).phase == TouchPhase.Began)
            {
                touchStartPosition = Input.GetTouch(0).position;
            }
            else
            {
                //Debug.Log("NO HACER NADA");
            }
        }
        else if (Input.touchCount == 2)
        {
            //Debug.Log("DOS TOQUES");
            if (buttonPressed.IsButtonPressed())
            {
                Debug.Log(coolDownAccumulated + " / " + playerSettings.GetCoolDownTime());
                if (coolDownAccumulated >= playerSettings.GetCoolDownTime())
                {
                    navMeshAgent.destination = transform.position;
                    navMeshAgent.isStopped   = true;
                    Quaternion newRotation = RotatePlayerForShoting(Input.touches[1].position);
                    transform.rotation = newRotation;

                    GameObject bala = Instantiate(balaGO, cañonGO.transform.position, newRotation) as GameObject;
                    bala.GetComponent <BalaMovement>().SetBulletTargetPositon(new Vector3(0, 0, 0));
                    bala.transform.Rotate(new Vector3(90f, 0f, 0f));
                    bala.GetComponent <Rigidbody>().AddForce(transform.forward * playerSettings.GetBulletVelocity());
                    bala.GetComponent <BalaSettings>().SetBalaTeam(playerSettings.GetPlayerTeam());

                    Destroy(bala, playerSettings.GetBulletDestroyingTime());

                    coolDownAccumulated = 0f;
                }
            }
        }
    }
Esempio n. 32
0
        /// <summary>
        /// Draws the sprite
        /// </summary>
        /// <param name="sb"></param>
        /// <param name="dest"></param>
        /// <param name="source"></param>
        /// <param name="color"></param>
        /// <param name="scale"></param>
        /// <param name="origin"></param>
        /// <param name="rotation"></param>
        public void Draw(SpriteBatch sb, Rectangle dest, Rectangle?source = null, Color?color = null, Vector2?scale = null, Vector2?origin = null, float rotation = 0f)
        {
            // setup values
            if (color == null)
            {
                color = Color.White;
            }

            switch (spriteType)
            {
            case SpriteType.Atlas:
                Atlas.Draw(sb, AtlasKey, dest, source, color, scale, origin, rotation);
                break;

            case SpriteType.Texture:
                if (source == null)
                {
                    source = Texture.Bounds;
                }
                sb.Draw(Texture, null, dest, source, origin, rotation, scale, color);
                break;
            }
        }
Esempio n. 33
0
        public void AddVehicle(
            uint elementId, byte elementType, uint?parentId, byte interior,
            ushort dimension, ElementAttachment?attachment, bool areCollisionsEnabled,
            bool isCallPropagationEnabled, CustomData customData, string name,
            byte timeContext, Vector3 position, Vector3 rotation, ushort model,
            float health, Color[] colors, byte paintJob, VehicleDamage damage,
            byte variant1, byte variant2, Vector2?turret, ushort?adjustableProperty,
            float[] doorRatios, byte[] upgrades, string plateText, byte overrideLights,
            bool isLandingGearDown, bool isSirenActive, bool isFuelTankExplodable,
            bool isEngineOn, bool isLocked, bool areDoorsUndamageable, bool isDamageProof,
            bool isFrozen, bool isDerailed, bool isDerailable, bool trainDirection,
            bool isTaxiLightOn, float alpha, Color headlightColor, VehicleHandling?handling,
            VehicleSirenSet?sirens
            )
        {
            AddEntity(
                elementId, elementType, parentId, interior,
                dimension, attachment, areCollisionsEnabled,
                isCallPropagationEnabled, customData, name, timeContext
                );

            builder.WriteVector3WithZAsFloat(position);
            builder.WriteVectorAsUshorts(rotation);
            builder.Write((byte)(model - 400));
            builder.WriteFloatFromBits(health, 12, 0, 2047.5f, true);

            builder.WriteCapped((byte)colors.Length - 1, 2);
            foreach (var color in colors)
            {
                builder.Write(color);
            }
            builder.WriteCapped(paintJob, 2);

            WriteVehicleDamage(damage.Doors, 3);
            WriteVehicleDamage(damage.Wheels, 2);
            WriteVehicleDamage(damage.Panels, 2);
            WriteVehicleDamage(damage.Lights, 2);


            builder.Write(variant1);
            builder.Write(variant2);

            if (turret != null)
            {
                builder.Write((short)(turret.Value.X * (32767.0f / MathF.PI)));
                builder.Write((short)(turret.Value.Y * (32767.0f / MathF.PI)));
            }

            if (adjustableProperty != null)
            {
                builder.WriteCompressed(adjustableProperty.Value);
            }

            foreach (var doorRatio in doorRatios)
            {
                if (doorRatio == 0 || doorRatio == 1)
                {
                    builder.Write(false);
                    builder.Write(doorRatio == 1);
                }
                else
                {
                    builder.Write(true);
                    builder.WriteFloatFromBits(doorRatio, 10, 0, 1, true);
                }
            }

            builder.Write((byte)upgrades.Length);
            foreach (var upgrade in upgrades)
            {
                builder.Write(upgrade);
            }

            builder.WriteStringWithoutLength(plateText.PadRight(8).Substring(0, 8));
            builder.WriteCapped(overrideLights, 2);

            builder.Write(isLandingGearDown);
            builder.Write(isSirenActive);
            builder.Write(isFuelTankExplodable);
            builder.Write(isEngineOn);
            builder.Write(isLocked);
            builder.Write(areDoorsUndamageable);
            builder.Write(isDamageProof);
            builder.Write(isFrozen);
            builder.Write(isDerailed);
            builder.Write(isDerailable);
            builder.Write(trainDirection);
            builder.Write(isTaxiLightOn);

            builder.WriteCompressed((byte)(255 - alpha));

            builder.Write(headlightColor != Color.White);
            if (headlightColor != Color.White)
            {
                builder.Write(headlightColor);
            }

            builder.Write(handling != null);
            if (handling != null)
            {
                WriteVehicleHandling(handling.Value);
            }

            WriteSirens(sirens);
        }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="location">The longitude and latitude values specifying the location for which you wish to obtain the closest, human-readable address. </param>
 public ReverseGeocodingParams(Vector2 location)
 {
     this.location = location;
 }
Esempio n. 35
0
        protected MyGuiControlCombobox AddCombo(List <MyGuiControlBase> controlGroup = null, MyGuiControlButtonTextAlignment textAlign = MyGuiControlButtonTextAlignment.CENTERED, Vector4?textColor = null, Vector2?size = null)
        {
            MyGuiControlCombobox combo = new MyGuiControlCombobox(this, new Vector2(m_buttonXOffset, m_currentPosition.Y), MyGuiControlPreDefinedSize.MEDIUM, Vector4.One, 0.7f);

            Controls.Add(combo);

            m_currentPosition.Y += 0.04f * m_scale;

            if (controlGroup != null)
            {
                controlGroup.Add(combo);
            }

            return(combo);
        }
Esempio n. 36
0
    private void UpdateState()
    {
        // Transition between water and land
        if ((((Vector2)transform.position) - lastWaterTransitionPos).magnitude > WATER_TRANSITION_DISTANCE)
        {
            // Emerge from water
            if ((currentState == State.Sunk) && lastOnLand)
            {
                currentState           = State.Bubbled;
                lastWaterTransitionPos = ((Vector2)transform.position);
                if (!soundPlaying)
                {
                    soundPlaying    = true;
                    soundWasPlaying = true;
                    if (!TrainingMode)
                    {
                        SoundSource.clip = SplashSound;
                        SoundSource.Play();
                    }
                }
            }

            // Go into water
            if ((currentState != State.Sunk) && !lastOnLand)
            {
                currentState           = State.Sunk;
                lastWaterTransitionPos = ((Vector2)transform.position);
                timeUnderwater         = 0.0f;
                if (!soundPlaying)
                {
                    soundPlaying    = true;
                    soundWasPlaying = true;
                    if (!TrainingMode)
                    {
                        SoundSource.clip = SplashSound;
                        SoundSource.Play();
                    }
                }
            }
        }

        if (currentState == State.Sunk)
        {
            timeUnderwater += Time.deltaTime;

            if (timeUnderwater > SunkDeadTime)
            {
                PlayerInfo.IncrementSnakesDrowned();
                Destroy(this.gameObject);
            }

            return;
        }

        if (bubbleTimeLeft > 0.0f)
        {
            currentState    = State.Bubbled;
            bubbleTimeLeft -= Time.deltaTime;
            return;
        }

        // Let the parent remain with the egg
        if (child)
        {
            //Debug.Log("with child");
            if ((((Vector2)(transform.position) - (Vector2)(Player.transform.position)).magnitude < GiveUpDistance) || chaseTimeLeft > 0.0f)
            {
                currentState = State.Chasing;
                return;
            }
            else
            {
                currentState = State.Parenting;
                return;
            }
        }

        // Don't attempt to lay eggs near obstacles - we don't want to lay eggs in the lake!
        if (!nearObstacle && (parentingTimer >= ParentAge) && !child)
        {
            parentingTimer = 0f;

            GameObject[] snakes = GameObject.FindGameObjectsWithTag("Predator");
            GameObject[] eggs   = GameObject.FindGameObjectsWithTag("Egg");

            // Extra randomization step to see if an egg is to be created.
            if ((snakes.Length + eggs.Length < MaxSnakes) && (Random.Range(0f, 1f) <= ParentDesire))
            {
                LayEgg();
                currentState = State.Parenting;
                return;
            }
        }

        float distanceFromHome       = ((Vector2)(transform.position) - (Vector2)(Home.transform.position)).magnitude;
        float distanceFromPlayer     = ((Vector2)(transform.position) - (Vector2)(Player.transform.position)).magnitude;
        float playerDistanceFromHome = ((Vector2)(Player.transform.position) - (Vector2)(Home.transform.position)).magnitude;

        if ((distanceFromHome > LeashLength) && (distanceFromPlayer > GiveUpDistance) && (chaseTimeLeft <= 0.0f))
        {
            currentState = State.HeadingHome;
        }
        else if (timeSinceWentHome > GoHomeTimeout)
        {
            currentState = State.Wandering;

            // Try targeting the player directly to see if they're reachable
            homeTargeter.Target = Player;
            aStarTargeter.underlyingTargeter = homeTargeter;
            Vector2?target = aStarTargeter.GetTarget();

            if (target != null)
            {
                // Check if we're gonna chase.
                if (((playerDistanceFromHome < LeashLength) || (distanceFromPlayer < GiveUpDistance) || (chaseTimeLeft > 0.0f)) &&
                    !Player.GetComponent <PlayerInfo>().IsUnderwater())
                {
                    currentState = State.Chasing;
                }
            }
        }
    }
Esempio n. 37
0
        public static void ConstructOffsetsFromAnchor(this tk2dSpriteDefinition def, tk2dBaseSprite.Anchor anchor, Vector2?scale = null, bool fixesScale = false, bool changesCollider = true)
        {
            if (!scale.HasValue)
            {
                scale = new Vector2?(def.position3);
            }

            if (fixesScale)
            {
                Vector2 fixedScale = scale.Value - def.position0.XY();
                scale = new Vector2?(fixedScale);
            }

            float xOffset = 0;

            if (anchor == tk2dBaseSprite.Anchor.LowerCenter || anchor == tk2dBaseSprite.Anchor.MiddleCenter || anchor == tk2dBaseSprite.Anchor.UpperCenter)
            {
                xOffset = -(scale.Value.x / 2f);
            }
            else if (anchor == tk2dBaseSprite.Anchor.LowerRight || anchor == tk2dBaseSprite.Anchor.MiddleRight || anchor == tk2dBaseSprite.Anchor.UpperRight)
            {
                xOffset = -scale.Value.x;
            }

            float yOffset = 0;

            if (anchor == tk2dBaseSprite.Anchor.MiddleLeft || anchor == tk2dBaseSprite.Anchor.MiddleCenter || anchor == tk2dBaseSprite.Anchor.MiddleLeft)
            {
                yOffset = -(scale.Value.y / 2f);
            }
            else if (anchor == tk2dBaseSprite.Anchor.UpperLeft || anchor == tk2dBaseSprite.Anchor.UpperCenter || anchor == tk2dBaseSprite.Anchor.UpperRight)
            {
                yOffset = -scale.Value.y;
            }

            def.MakeOffset(new Vector2(xOffset, yOffset), false);

            if (changesCollider && def.colliderVertices != null && def.colliderVertices.Length > 0)
            {
                float colliderXOffset = 0;

                if (anchor == tk2dBaseSprite.Anchor.LowerLeft || anchor == tk2dBaseSprite.Anchor.MiddleLeft || anchor == tk2dBaseSprite.Anchor.UpperLeft)
                {
                    colliderXOffset = (scale.Value.x / 2f);
                }
                else if (anchor == tk2dBaseSprite.Anchor.LowerRight || anchor == tk2dBaseSprite.Anchor.MiddleRight || anchor == tk2dBaseSprite.Anchor.UpperRight)
                {
                    colliderXOffset = -(scale.Value.x / 2f);
                }

                float colliderYOffset = 0;

                if (anchor == tk2dBaseSprite.Anchor.LowerLeft || anchor == tk2dBaseSprite.Anchor.LowerCenter || anchor == tk2dBaseSprite.Anchor.LowerRight)
                {
                    colliderYOffset = (scale.Value.y / 2f);
                }
                else if (anchor == tk2dBaseSprite.Anchor.UpperLeft || anchor == tk2dBaseSprite.Anchor.UpperCenter || anchor == tk2dBaseSprite.Anchor.UpperRight)
                {
                    colliderYOffset = -(scale.Value.y / 2f);
                }

                def.colliderVertices[0] += new Vector3(colliderXOffset, colliderYOffset, 0);
            }
        }
Esempio n. 38
0
        public static void AnimateProjectile(this Projectile proj, List <string> names, int fps, bool loops, List <IntVector2> pixelSizes, List <bool> lighteneds, List <tk2dBaseSprite.Anchor> anchors, List <bool> anchorsChangeColliders,
                                             List <bool> fixesScales, List <Vector3?> manualOffsets, List <IntVector2?> overrideColliderPixelSizes, List <IntVector2?> overrideColliderOffsets, List <Projectile> overrideProjectilesToCopyFrom)
        {
            tk2dSpriteAnimationClip clip = new tk2dSpriteAnimationClip();

            clip.name = "idle";
            clip.fps  = fps;
            List <tk2dSpriteAnimationFrame> frames = new List <tk2dSpriteAnimationFrame>();

            for (int i = 0; i < names.Count; i++)
            {
                string     name      = names[i];
                IntVector2 pixelSize = pixelSizes[i];
                IntVector2?overrideColliderPixelSize = overrideColliderPixelSizes[i];
                IntVector2?overrideColliderOffset    = overrideColliderOffsets[i];
                Vector3?   manualOffset          = manualOffsets[i];
                bool       anchorChangesCollider = anchorsChangeColliders[i];
                bool       fixesScale            = fixesScales[i];

                if (!manualOffset.HasValue)
                {
                    manualOffset = new Vector2?(Vector2.zero);
                }

                tk2dBaseSprite.Anchor anchor            = anchors[i];
                bool       lightened                    = lighteneds[i];
                Projectile overrideProjectileToCopyFrom = overrideProjectilesToCopyFrom[i];
                tk2dSpriteAnimationFrame frame          = new tk2dSpriteAnimationFrame();
                frame.spriteId         = ETGMod.Databases.Items.ProjectileCollection.inst.GetSpriteIdByName(name);
                frame.spriteCollection = ETGMod.Databases.Items.ProjectileCollection;
                frames.Add(frame);
                int?overrideColliderPixelWidth  = null;
                int?overrideColliderPixelHeight = null;

                if (overrideColliderPixelSize.HasValue)
                {
                    overrideColliderPixelWidth  = overrideColliderPixelSize.Value.x;
                    overrideColliderPixelHeight = overrideColliderPixelSize.Value.y;
                }

                int?overrideColliderOffsetX = null;
                int?overrideColliderOffsetY = null;

                if (overrideColliderOffset.HasValue)
                {
                    overrideColliderOffsetX = overrideColliderOffset.Value.x;
                    overrideColliderOffsetY = overrideColliderOffset.Value.y;
                }

                tk2dSpriteDefinition def = AnimateProjectileTools.SetupDefinitionForProjectileSprite(name, frame.spriteId, pixelSize.x, pixelSize.y, lightened,
                                                                                                     overrideColliderPixelWidth, overrideColliderPixelHeight, overrideColliderOffsetX, overrideColliderOffsetY, overrideProjectileToCopyFrom);

                def.ConstructOffsetsFromAnchor(anchor, def.position3, fixesScale, anchorChangesCollider);
                def.position0 += manualOffset.Value;
                def.position1 += manualOffset.Value;
                def.position2 += manualOffset.Value;
                def.position3 += manualOffset.Value;

                if (i == 0)
                {
                    proj.GetAnySprite().SetSprite(frame.spriteCollection, frame.spriteId);
                }
            }

            clip.wrapMode = loops ? tk2dSpriteAnimationClip.WrapMode.Loop : tk2dSpriteAnimationClip.WrapMode.Once;
            clip.frames   = frames.ToArray();

            if (proj.sprite.spriteAnimator == null)
            {
                proj.sprite.spriteAnimator = proj.sprite.gameObject.AddComponent <tk2dSpriteAnimator>();
            }

            proj.sprite.spriteAnimator.playAutomatically = true;

            if (proj.sprite.spriteAnimator.Library == null)
            {
                proj.sprite.spriteAnimator.Library         = proj.sprite.spriteAnimator.gameObject.AddComponent <tk2dSpriteAnimation>();
                proj.sprite.spriteAnimator.Library.clips   = new tk2dSpriteAnimationClip[0];
                proj.sprite.spriteAnimator.Library.enabled = true;
            }

            proj.sprite.spriteAnimator.Library.clips      = proj.sprite.spriteAnimator.Library.clips.Concat(new tk2dSpriteAnimationClip[] { clip }).ToArray();
            proj.sprite.spriteAnimator.DefaultClipId      = proj.sprite.spriteAnimator.Library.GetClipIdByName("idle");
            proj.sprite.spriteAnimator.deferNextStartClip = false;
        }
Esempio n. 39
0
        // TODO - Cleanup and make more generic
        private IEnumerator pipeMovement(Entity entity, bool fromStart, bool canBounceBack = true, Vector2?forcedStartPosition = null)
        {
            MarioClearPipeInteraction interaction = GetClearPipeInteraction(entity);

            int startIndex = fromStart ? 0 : nodes.Length - 1;
            int lastIndex  = fromStart ? nodes.Length - 1 : 0;
            int direction  = fromStart ? 1 : -1;

            Direction transportStartDirection = fromStart ? startDirection : endDirection;
            Direction transportEndDirection   = fromStart ? endDirection : startDirection;

            if (forcedStartPosition != null || CanTransportEntity(entity, transportStartDirection))
            {
                CurrentlyTransportedEntities.Add(entity);
                interaction.CurrentClearPipe = this;
                interaction.ExitEarly        = false;
                interaction?.OnPipeEnter?.Invoke(entity, interaction);

                // Check if we are entering the pipe or bouncing back from a blocked exit
                if (forcedStartPosition != null)
                {
                    entity.Position = forcedStartPosition.Value;
                }
                else
                {
                    // Gracefully attempt to move to the first node
                    yield return(moveBetweenNodes(entity, interaction, entity.Position, nodes[startIndex], TransportSpeed * transportSpeedEnterMultiplier, true));
                }

                // Follow the nodes
                for (int i = startIndex; i != lastIndex && !interaction.ExitEarly; i += direction)
                {
                    yield return(moveBetweenNodes(entity, interaction, nodes[i], nodes[i + direction], TransportSpeed, false));
                }

                if (interaction.ExitEarly)
                {
                    ejectFromPipe(entity, interaction);

                    yield break;
                }

                // Check if we can exit the pipe
                if (CanExitPipe(entity, interaction.DirectionVector, TransportSpeed))
                {
                    yield return(exitPipeMovement(entity, interaction));
                }

                // Send back if it gets stuck in a solid
                if (entity != null && entity.Scene != null && entity.CollideCheck <Solid>())
                {
                    if (canBounceBack)
                    {
                        entity.Position = nodes[lastIndex] + interaction.PipeRenderOffset;

                        yield return(pipeMovement(entity, !fromStart, false, entity.Position));
                    }
                    else
                    {
                        ejectFromPipe(entity, interaction);
                    }
                }
                else
                {
                    ejectFromPipe(entity, interaction);
                }
            }
        }
        public override void AI()
        {
            Vector2?vector78 = null;

            if (projectile.velocity.HasNaNs() || projectile.velocity == Vector2.Zero)
            {
                projectile.velocity = -Vector2.UnitY;
            }
            if (Main.npc[(int)projectile.ai[1]].active && Main.npc[(int)projectile.ai[1]].type == ModContent.NPCType <LifeChampion>())
            {
                projectile.Center = Main.npc[(int)projectile.ai[1]].Center;
            }
            else
            {
                projectile.Kill();
                return;
            }
            if (projectile.velocity.HasNaNs() || projectile.velocity == Vector2.Zero)
            {
                projectile.velocity = -Vector2.UnitY;
            }
            if (projectile.localAI[0] == 0f)
            {
                Main.PlaySound(SoundID.Item12, projectile.Center);
            }
            float num801 = 1f;

            projectile.localAI[0] += 1f;
            if (projectile.localAI[0] >= maxTime)
            {
                projectile.Kill();
                return;
            }
            projectile.scale = (float)Math.Sin(projectile.localAI[0] * 3.14159274f / maxTime) * 2f * num801;
            if (projectile.scale > num801)
            {
                projectile.scale = num801;
            }
            float num804 = projectile.velocity.ToRotation();

            num804 += projectile.ai[0];
            projectile.rotation = num804 - 1.57079637f;
            //float num804 = Main.npc[(int)projectile.ai[1]].ai[3] - 1.57079637f + projectile.ai[0];
            //if (projectile.ai[0] != 0f) num804 -= (float)Math.PI;
            //projectile.rotation = num804;
            //num804 += 1.57079637f;
            projectile.velocity = num804.ToRotationVector2();
            float   num805        = 3f;
            float   num806        = (float)projectile.width;
            Vector2 samplingPoint = projectile.Center;

            if (vector78.HasValue)
            {
                samplingPoint = vector78.Value;
            }
            float[] array3 = new float[(int)num805];
            //Collision.LaserScan(samplingPoint, projectile.velocity, num806 * projectile.scale, 3000f, array3);
            for (int i = 0; i < array3.Length; i++)
            {
                array3[i] = 3000f;
            }
            float num807 = 0f;
            int   num3;

            for (int num808 = 0; num808 < array3.Length; num808 = num3 + 1)
            {
                num807 += array3[num808];
                num3    = num808;
            }
            num807 /= num805;
            float amount = 0.5f;

            projectile.localAI[1] = MathHelper.Lerp(projectile.localAI[1], num807, amount);
            Vector2 vector79 = projectile.Center + projectile.velocity * (projectile.localAI[1] - 14f);

            for (int num809 = 0; num809 < 2; num809 = num3 + 1)
            {
                float   num810   = projectile.velocity.ToRotation() + ((Main.rand.Next(2) == 1) ? -1f : 1f) * 1.57079637f;
                float   num811   = (float)Main.rand.NextDouble() * 2f + 2f;
                Vector2 vector80 = new Vector2((float)Math.Cos((double)num810) * num811, (float)Math.Sin((double)num810) * num811);
                int     num812   = Dust.NewDust(vector79, 0, 0, 244, vector80.X, vector80.Y, 0, default(Color), 1f);
                Main.dust[num812].noGravity = true;
                Main.dust[num812].scale     = 1.7f;
                num3 = num809;
            }
            if (Main.rand.Next(5) == 0)
            {
                Vector2 value29 = projectile.velocity.RotatedBy(1.5707963705062866, default(Vector2)) * ((float)Main.rand.NextDouble() - 0.5f) * (float)projectile.width;
                int     num813  = Dust.NewDust(vector79 + value29 - Vector2.One * 4f, 8, 8, 244, 0f, 0f, 100, default(Color), 1.5f);
                Dust    dust    = Main.dust[num813];
                dust.velocity *= 0.5f;
                Main.dust[num813].velocity.Y = -Math.Abs(Main.dust[num813].velocity.Y);
            }
            //DelegateMethods.v3_1 = new Vector3(0.3f, 0.65f, 0.7f);
            //Utils.PlotTileLine(projectile.Center, projectile.Center + projectile.velocity * projectile.localAI[1], (float)projectile.width * projectile.scale, new Utils.PerLinePoint(DelegateMethods.CastLight));
        }
Esempio n. 41
0
 public RectElement(Dictionary <string, object> json, Element parent) : base(json, parent)
 {
     canvasPosition = json.GetVector2("x", "y");
     sizeDelta      = json.GetVector2("w", "h");
 }
Esempio n. 42
0
    private void DesktopUpdate()
    {
        if (PhotonNetwork.IsConnected && !photonView.IsMine)
        {
            return;
        }

        //CoolDown management
        if (coolDownAccumulated < playerSettings.GetCoolDownTime())
        {
            coolDownAccumulated += Time.deltaTime;
        }

        if (Input.GetMouseButtonDown(0))
        {
            Vector3 raycastHit = getRayCastPoint(Input.mousePosition);
            if (raycastHit != Vector3.zero)
            {
                navMeshAgent.destination = raycastHit;
                navMeshAgent.isStopped   = false;
            }

            dashed             = false;
            touchStartPosition = null;
        }
        else if (Input.GetMouseButtonDown(1))
        {
            Debug.Log(coolDownAccumulated + " / " + playerSettings.GetCoolDownTime());
            if (coolDownAccumulated >= playerSettings.GetCoolDownTime())
            {
                navMeshAgent.destination = transform.position;
                navMeshAgent.isStopped   = true;
                Quaternion newRotation = RotatePlayerForShoting(Input.mousePosition);
                transform.rotation = newRotation;

                GameObject bala = null;
                if (!PhotonNetwork.IsConnected)
                {
                    bala = Instantiate(balaGO, cañonGO.transform.position, newRotation) as GameObject;
                    bala.GetComponent <BalaMovement>().SetBulletTargetPositon(new Vector3(0, 0, 0));
                    bala.transform.Rotate(new Vector3(90f, 0f, 0f));
                    bala.GetComponent <Rigidbody>().AddForce(transform.forward * playerSettings.GetBulletVelocity());
                    bala.GetComponent <BalaSettings>().SetBalaTeam(playerSettings.GetPlayerTeam());
                }
                else
                {
                    //Hay que pasarle parámetros a la bala de networking
                    //[0] -> BalaTeam
                    //bala = PhotonNetwork.Instantiate(balaGO.name, cañonGO.transform.position, newRotation, 0, new object[] { playerSettings.GetPlayerTeam() }) as GameObject;

                    //Vamos a intentar Instanciar con RPC
                    Debug.Log("Antes del disparo");
                    photonView.RPC("InstantiateBullet", RpcTarget.All, new object[] { newRotation, getRayCastPoint(Input.mousePosition) });
                }

                //Esto se hace para los dos porque el transform de la bala ya se está observando.

                //Destroy(bala, playerSettings.GetBulletDestroyingTime());

                coolDownAccumulated = 0f;
            }
        }
    }
Esempio n. 43
0
        /// <summary>
        /// Creates a new instance of a MyGuiControlRanged slider with given parameters
        /// </summary>
        /// <param name="position">The position of the slider in screenspace</param>
        /// <param name="width">The width of the slider in screenspace</param>
        /// <param name="minValue">The minimum value of the slider</param>
        /// <param name="maxValue">The maximum value of the slider</param>
        /// <param name="showLabel">Whether to show a label with the sliders values</param>
        /// <param name="labelSpaceWidth">The space between label and slider</param>
        /// <param name="labelScale">The size of the labels text</param>
        /// <param name="labelFont">The font of the label</param>
        /// <param name="toolTip">The tooltip for the slider</param>
        /// <param name="originAlign">The alignment of the slider</param>
        /// <param name="useLogScale">Whether to use logarithmic scaling of values on the slider to allow for wider ranges</param>
        /// <param name="defaultMax">Default max value</param>
        /// <param name="defaultMin">Default min value</param>
        /// <param name="intMode">If the slider should work in int mode</param>
        public MyGuiControlRangedSlider(double minValue, double maxValue, double defaultMin, double defaultMax, bool intMode = false, Vector2?position = null, float width = 0.29f, bool showLabel = true, float labelSpaceWidth = 0f, float labelScale = 0.8f, string labelFont = "White", string toolTip = null, MyGuiDrawAlignEnum originAlign = MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_CENTER, bool useLogScale = false) :
            base(position, null, null, toolTip, null, true, true, MyGuiControlHighlightType.WHEN_CURSOR_OVER_OR_FOCUS, originAlign)
        {
            m_showLabel       = showLabel;
            m_minValue        = Math.Min(minValue, maxValue);
            m_maxValue        = Math.Max(maxValue, minValue);
            m_labelSpaceWidth = labelSpaceWidth;

            m_railTexture = MyGuiConstants.TEXTURE_SLIDER_RAIL;
            m_minThumb    = new MyGuiSliderThumb(defaultMin);
            m_maxThumb    = new MyGuiSliderThumb(defaultMax);

            m_intMode = intMode;

            m_logScale = useLogScale;

            m_minLabel = new MyGuiControlLabel(null, null, "", null, labelScale, labelFont, MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_BOTTOM);
            m_maxLabel = new MyGuiControlLabel(null, null, "", null, labelScale, labelFont, MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_TOP);
            if (m_showLabel)
            {
                Elements.Add(m_minLabel);
                Elements.Add(m_maxLabel);
            }
            Size = new Vector2(width, Size.Y);
            UpdateLabels();
            RefreshInternals();
        }
Esempio n. 44
0
        /// <summary>
        /// Gets fast-predicted unit position
        /// </summary>
        /// <param name="target">Target</param>
        /// <param name="path">Path</param>
        /// <param name="delay">Spell delay</param>
        /// <param name="missileSpeed">Spell missile speed</param>
        /// <param name="from">Spell casted position</param>
        /// <param name="moveSpeed">Move speed</param>
        /// <param name="distanceSet"></param>
        /// <returns></returns>
        public static Vector2 GetFastUnitPosition(Obj_AI_Base target, List <Vector2> path, float delay, float missileSpeed = 0, Vector2?from = null, float moveSpeed = 0, float distanceSet = 0)
        {
            if (from == null)
            {
                from = target.ServerPosition.To2D();
            }

            if (moveSpeed == 0)
            {
                moveSpeed = target.MoveSpeed;
            }

            if (path.Count <= 1 || (target is AIHeroClient && ((AIHeroClient)target).IsChannelingImportantSpell()) || Utility.IsImmobileTarget(target))
            {
                return(target.ServerPosition.To2D());
            }

            if (target.IsDashing())
            {
                return(target.GetDashInfo().Path.Last());
            }

            float distance = distanceSet;

            if (distance == 0)
            {
                float targetDistance = from.Value.Distance(target.ServerPosition);
                float flyTime        = 0f;

                if (missileSpeed != 0) //skillshot with a missile
                {
                    Vector2 Vt = (path[path.Count - 1] - path[0]).Normalized() * moveSpeed;
                    Vector2 Vs = (target.ServerPosition.To2D() - from.Value).Normalized() * missileSpeed;
                    Vector2 Vr = Vs - Vt;

                    flyTime = targetDistance / Vr.Length();

                    if (path.Count > 5) //complicated movement
                    {
                        flyTime = targetDistance / missileSpeed;
                    }
                }

                float t = flyTime + delay + Game.Ping / 2000f + SpellDelay / 1000f;
                distance = t * moveSpeed;
            }

            for (int i = 0; i < path.Count - 1; i++)
            {
                float d = path[i + 1].Distance(path[i]);
                if (distance == d)
                {
                    return(path[i + 1]);
                }
                else if (distance < d)
                {
                    return(path[i] + distance * (path[i + 1] - path[i]).Normalized());
                }
                else
                {
                    distance -= d;
                }
            }

            return(path.Last());
        }
Esempio n. 45
0
    /// Convert segments to lists.
    public static List <List <Vector2> > LinkUp(this List <Segment> sts)
    {
        var pts = new HashSet <Vector2>();

        foreach (var i in sts)
        {
            pts.Add(i.from); pts.Add(i.to);
        }

        var adj = new Dictionary <Vector2, HashSet <Vector2> >();

        foreach (var s in sts)
        {
            if (!adj.ContainsKey(s.from))
            {
                adj[s.from] = new HashSet <Vector2>();
            }
            adj[s.from].Add(s.to);
            if (!adj.ContainsKey(s.to))
            {
                adj[s.to] = new HashSet <Vector2>();
            }
            adj[s.to].Add(s.from);
        }

        var res  = new List <List <Vector2> >();
        var used = new HashSet <Vector2>();

        void SetupList(Vector2 src)
        {
            used.Add(src);
            var lst = new List <Vector2>();

            res.Add(lst);
            var cur = src;

            // There shouldn't be any source point that equals to (NaN, NaN)...
            var prev = new Vector2(float.NaN, float.NaN);

            while (true)
            {
                lst.Add(cur);
                used.Add(cur);

                // Find the next point, which is not previous.
                Vector2?nxt = null;
                foreach (var i in adj[cur])
                {
                    if (prev != i)
                    {
                        nxt = i; break;
                    }
                }

                // Non-closed path's end.
                if (nxt == null)
                {
                    break;
                }

                // Repeat the source point if it is closed path.
                if (nxt == src)
                {
                    lst.Add(src); break;
                }

                prev = cur;
                cur  = nxt.Value;
            }
        }

        // Non-closed path should be in one collider
        //   so the start point of a non-closed path should be an end point.
        foreach (var src in pts)
        {
            if (!used.Contains(src) && adj[src].Count == 1)
            {
                SetupList(src);
            }
        }

        // Closed path's point is arbitary.
        foreach (var src in pts)
        {
            if (!used.Contains(src))
            {
                SetupList(src);
            }
        }

        // Connect end-points to form a closed area.
        // This polygon then can be used in rendering.
        // TODO!

        return(res);
    }
Esempio n. 46
0
        public static void ExecuteCommand(string command, GameMain game)
        {
            if (string.IsNullOrWhiteSpace(command))
            {
                return;
            }
            string[] commands = command.Split(' ');

            if (!commands[0].ToLowerInvariant().Equals("admin"))
            {
                NewMessage(textBox.Text, Color.White);
            }

#if !DEBUG
            if (GameMain.Client != null && !IsCommandPermitted(commands[0].ToLowerInvariant(), GameMain.Client))
            {
                ThrowError("You're not permitted to use the command \"" + commands[0].ToLowerInvariant() + "\"!");
                return;
            }
#endif

            switch (commands[0].ToLowerInvariant())
            {
            case "help":
                NewMessage("menu: go to main menu", Color.Cyan);
                NewMessage("game: enter the \"game screen\"", Color.Cyan);
                NewMessage("edit: switch to submarine editor", Color.Cyan);
                NewMessage("edit [submarine name]: load a submarine and switch to submarine editor", Color.Cyan);
                NewMessage("load [submarine name]: load a submarine", Color.Cyan);
                NewMessage("save [submarine name]: save the current submarine using the specified name", Color.Cyan);

                NewMessage(" ", Color.Cyan);

                NewMessage("spawn [creaturename] [near/inside/outside]: spawn a creature at a random spawnpoint (use the second parameter to only select spawnpoints near/inside/outside the submarine)", Color.Cyan);
                NewMessage("spawnitem [itemname] [cursor/inventory]: spawn an item at the position of the cursor, in the inventory of the controlled character or at a random spawnpoint if the last parameter is omitted", Color.Cyan);

                NewMessage(" ", Color.Cyan);

                NewMessage("lights: disable lighting", Color.Cyan);
                NewMessage("los: disable the line of sight effect", Color.Cyan);
                NewMessage("freecam: detach the camera from the controlled character", Color.Cyan);
                NewMessage("control [character name]: start controlling the specified character", Color.Cyan);

                NewMessage(" ", Color.Cyan);

                NewMessage("water: allows adding water into rooms or removing it by holding the left/right mouse buttons", Color.Cyan);
                NewMessage("fire: allows putting up fires by left clicking", Color.Cyan);

                NewMessage(" ", Color.Cyan);

                NewMessage("teleport: teleport the controlled character to the position of the cursor", Color.Cyan);
                NewMessage("teleport [character name]: teleport the specified character to the position of the cursor", Color.Cyan);
                NewMessage("heal: restore the controlled character to full health", Color.Cyan);
                NewMessage("heal [character name]: restore the specified character to full health", Color.Cyan);
                NewMessage("revive: bring the controlled character back from the dead", Color.Cyan);
                NewMessage("revive [character name]: bring the specified character back from the dead", Color.Cyan);
                NewMessage("killmonsters: immediately kills all AI-controlled enemies in the level", Color.Cyan);

                NewMessage(" ", Color.Cyan);

                NewMessage("fixwalls: fixes all the walls", Color.Cyan);
                NewMessage("fixitems: fixes every item/device in the sub", Color.Cyan);
                NewMessage("oxygen: replenishes the oxygen in every room to 100%", Color.Cyan);
                NewMessage("power [amount]: immediately sets the temperature of the reactor to the specified value", Color.Cyan);

                NewMessage(" ", Color.Cyan);

                NewMessage("kick [name]: kick a player out from the server", Color.Cyan);
                NewMessage("ban [name]: kick and ban the player from the server", Color.Cyan);
                NewMessage("banip [IP address]: ban the IP address from the server", Color.Cyan);
                NewMessage("debugdraw: toggles the \"debug draw mode\"", Color.Cyan);
                NewMessage("netstats: toggles the visibility of the network statistics panel", Color.Cyan);

                break;

            case "createfilelist":
                UpdaterUtil.SaveFileList("filelist.xml");
                break;

            case "spawn":
            case "spawncharacter":
                if (commands.Length == 1)
                {
                    return;
                }

                Character spawnedCharacter = null;

                Vector2  spawnPosition = Vector2.Zero;
                WayPoint spawnPoint    = null;

                if (commands.Length > 2)
                {
                    switch (commands[2].ToLowerInvariant())
                    {
                    case "inside":
                        spawnPoint = WayPoint.GetRandom(SpawnType.Human, null, Submarine.MainSub);
                        break;

                    case "outside":
                        spawnPoint = WayPoint.GetRandom(SpawnType.Enemy);
                        break;

                    case "near":
                    case "close":
                        float closestDist = -1.0f;
                        foreach (WayPoint wp in WayPoint.WayPointList)
                        {
                            if (wp.Submarine != null)
                            {
                                continue;
                            }

                            //don't spawn inside hulls
                            if (Hull.FindHull(wp.WorldPosition, null) != null)
                            {
                                continue;
                            }

                            float dist = Vector2.Distance(wp.WorldPosition, GameMain.GameScreen.Cam.WorldViewCenter);

                            if (closestDist < 0.0f || dist < closestDist)
                            {
                                spawnPoint  = wp;
                                closestDist = dist;
                            }
                        }
                        break;

                    case "cursor":
                        spawnPosition = GameMain.GameScreen.Cam.ScreenToWorld(PlayerInput.MousePosition);
                        break;

                    default:
                        spawnPoint = WayPoint.GetRandom(commands[1].ToLowerInvariant() == "human" ? SpawnType.Human : SpawnType.Enemy);
                        break;
                    }
                }
                else
                {
                    spawnPoint = WayPoint.GetRandom(commands[1].ToLowerInvariant() == "human" ? SpawnType.Human : SpawnType.Enemy);
                }

                if (string.IsNullOrWhiteSpace(commands[1]))
                {
                    return;
                }

                if (spawnPoint != null)
                {
                    spawnPosition = spawnPoint.WorldPosition;
                }

                if (commands[1].ToLowerInvariant() == "human")
                {
                    spawnedCharacter = Character.Create(Character.HumanConfigFile, spawnPosition);

                    if (GameMain.GameSession != null)
                    {
                        SinglePlayerMode mode = GameMain.GameSession.gameMode as SinglePlayerMode;
                        if (mode != null)
                        {
                            Character.Controlled = spawnedCharacter;
                            GameMain.GameSession.CrewManager.AddCharacter(Character.Controlled);
                            GameMain.GameSession.CrewManager.SelectCharacter(null, Character.Controlled);
                        }
                    }
                }
                else
                {
                    spawnedCharacter = Character.Create(
                        "Content/Characters/"
                        + commands[1].First().ToString().ToUpper() + commands[1].Substring(1)
                        + "/" + commands[1].ToLower() + ".xml", spawnPosition);
                }

                break;

            case "spawnitem":
                if (commands.Length < 2)
                {
                    return;
                }

                Vector2?  spawnPos       = null;
                Inventory spawnInventory = null;

                int extraParams = 0;
                switch (commands.Last())
                {
                case "cursor":
                    extraParams = 1;
                    spawnPos    = GameMain.GameScreen.Cam.ScreenToWorld(PlayerInput.MousePosition);
                    break;

                case "inventory":
                    extraParams    = 1;
                    spawnInventory = Character.Controlled == null ? null : Character.Controlled.Inventory;
                    break;

                default:
                    extraParams = 0;
                    break;
                }

                string itemName = string.Join(" ", commands.Skip(1).Take(commands.Length - extraParams - 1)).ToLowerInvariant();

                var itemPrefab = MapEntityPrefab.list.Find(ip => ip.Name.ToLowerInvariant() == itemName) as ItemPrefab;
                if (itemPrefab == null)
                {
                    ThrowError("Item \"" + itemName + "\" not found!");
                    return;
                }

                if (spawnPos == null && spawnInventory == null)
                {
                    var wp = WayPoint.GetRandom(SpawnType.Human, null, Submarine.MainSub);
                    spawnPos = wp == null ? Vector2.Zero : wp.WorldPosition;
                }

                if (spawnPos != null)
                {
                    Item.Spawner.AddToSpawnQueue(itemPrefab, (Vector2)spawnPos);
                }
                else if (spawnInventory != null)
                {
                    Item.Spawner.AddToSpawnQueue(itemPrefab, spawnInventory);
                }

                break;

            case "disablecrewai":
                HumanAIController.DisableCrewAI = !HumanAIController.DisableCrewAI;
                break;

            case "enablecrewai":
                HumanAIController.DisableCrewAI = false;
                break;

            /*case "admin":
             *  if (commands.Length < 2) break;
             *
             *  if (GameMain.Server != null)
             *  {
             *      GameMain.Server.AdminAuthPass = commands[1];
             *
             *  }
             *  else if (GameMain.Client != null)
             *  {
             *      GameMain.Client.RequestAdminAuth(commands[1]);
             *  }
             *  break;*/
            case "kick":
                if (GameMain.NetworkMember == null || commands.Length < 2)
                {
                    break;
                }
                GameMain.NetworkMember.KickPlayer(string.Join(" ", commands.Skip(1)), false);

                break;

            case "ban":
                if (GameMain.NetworkMember == null || commands.Length < 2)
                {
                    break;
                }
                GameMain.NetworkMember.KickPlayer(string.Join(" ", commands.Skip(1)), true);

                break;

            case "banip":
            {
                if (GameMain.Server == null || commands.Length < 2)
                {
                    break;
                }

                var client = GameMain.Server.ConnectedClients.Find(c => c.Connection.RemoteEndPoint.Address.ToString() == commands[1]);
                if (client == null)
                {
                    GameMain.Server.BanList.BanPlayer("Unnamed", commands[1]);
                }
                else
                {
                    GameMain.Server.KickClient(client, true);
                }
            }
            break;

            case "startclient":
                if (commands.Length == 1)
                {
                    return;
                }
                if (GameMain.Client == null)
                {
                    GameMain.NetworkMember = new GameClient("Name");
                    GameMain.Client.ConnectToServer(commands[1]);
                }
                break;

            case "mainmenuscreen":
            case "mainmenu":
            case "menu":
                GameMain.GameSession = null;

                List <Character> characters = new List <Character>(Character.CharacterList);
                foreach (Character c in characters)
                {
                    c.Remove();
                }

                GameMain.MainMenuScreen.Select();
                break;

            case "gamescreen":
            case "game":
                GameMain.GameScreen.Select();
                break;

            case "editmapscreen":
            case "editmap":
            case "edit":
                if (commands.Length > 1)
                {
                    Submarine.Load(string.Join(" ", commands.Skip(1)), true);
                }
                GameMain.EditMapScreen.Select();
                break;

            case "test":
                Submarine.Load("aegir mark ii", true);
                GameMain.DebugDraw = true;
                GameMain.LightManager.LosEnabled = false;
                GameMain.EditMapScreen.Select();
                break;

            case "editcharacter":
            case "editchar":
                GameMain.EditCharacterScreen.Select();
                break;

            case "controlcharacter":
            case "control":
            {
                if (commands.Length < 2)
                {
                    break;
                }

                var character = FindMatchingCharacter(commands, true);

                if (character != null)
                {
                    Character.Controlled = character;
                }
            }
            break;

            case "setclientcharacter":
            {
                if (GameMain.Server == null)
                {
                    break;
                }

                int separatorIndex = Array.IndexOf(commands, ";");

                if (separatorIndex == -1 || commands.Length < 4)
                {
                    ThrowError("Invalid parameters. The command should be formatted as \"setclientcharacter [client] ; [character]\"");
                    break;
                }

                string[] commandsLeft  = commands.Take(separatorIndex).ToArray();
                string[] commandsRight = commands.Skip(separatorIndex).ToArray();

                string clientName = String.Join(" ", commandsLeft.Skip(1));

                var client = GameMain.Server.ConnectedClients.Find(c => c.name == clientName);
                if (client == null)
                {
                    ThrowError("Client \"" + clientName + "\" not found.");
                }

                var character = FindMatchingCharacter(commandsRight, false);
                GameMain.Server.SetClientCharacter(client, character);
            }
            break;

            case "teleportcharacter":
            case "teleport":
                var tpCharacter = FindMatchingCharacter(commands, false);

                if (commands.Length < 2)
                {
                    tpCharacter = Character.Controlled;
                }

                if (tpCharacter != null)
                {
                    var cam = GameMain.GameScreen.Cam;
                    tpCharacter.AnimController.CurrentHull = null;
                    tpCharacter.Submarine = null;
                    tpCharacter.AnimController.SetPosition(ConvertUnits.ToSimUnits(cam.ScreenToWorld(PlayerInput.MousePosition)));
                    tpCharacter.AnimController.FindHull(cam.ScreenToWorld(PlayerInput.MousePosition), true);
                }
                break;

            case "godmode":
                if (Submarine.MainSub == null)
                {
                    return;
                }

                Submarine.MainSub.GodMode = !Submarine.MainSub.GodMode;
                break;

            case "lockx":
                Submarine.LockX = !Submarine.LockX;
                break;

            case "locky":
                Submarine.LockY = !Submarine.LockY;
                break;

            case "dumpids":
                try
                {
                    int count = commands.Length < 2 ? 10 : int.Parse(commands[1]);
                    Entity.DumpIds(count);
                }
                catch
                {
                    return;
                }
                break;

            case "heal":
                Character healedCharacter = null;
                if (commands.Length == 1)
                {
                    healedCharacter = Character.Controlled;
                }
                else
                {
                    healedCharacter = FindMatchingCharacter(commands);
                }

                if (healedCharacter != null)
                {
                    healedCharacter.AddDamage(CauseOfDeath.Damage, -healedCharacter.MaxHealth, null);
                    healedCharacter.Oxygen   = 100.0f;
                    healedCharacter.Bleeding = 0.0f;
                    healedCharacter.Stun     = 0.0f;
                }

                break;

            case "revive":
                Character revivedCharacter = null;
                if (commands.Length == 1)
                {
                    revivedCharacter = Character.Controlled;
                }
                else
                {
                    revivedCharacter = FindMatchingCharacter(commands);
                }

                if (revivedCharacter != null)
                {
                    revivedCharacter.Revive(false);
                    if (GameMain.Server != null)
                    {
                        foreach (Client c in GameMain.Server.ConnectedClients)
                        {
                            if (c.Character != revivedCharacter)
                            {
                                continue;
                            }
                            //clients stop controlling the character when it dies, force control back
                            GameMain.Server.SetClientCharacter(c, revivedCharacter);
                            break;
                        }
                    }
                }
                break;

            case "freeze":
                if (Character.Controlled != null)
                {
                    Character.Controlled.AnimController.Frozen = !Character.Controlled.AnimController.Frozen;
                }
                break;

            case "freecamera":
            case "freecam":
                Character.Controlled = null;
                GameMain.GameScreen.Cam.TargetPos = Vector2.Zero;
                break;

            case "editwater":
            case "water":
                if (GameMain.Client == null)
                {
                    Hull.EditWater = !Hull.EditWater;
                }

                break;

            case "fire":
                if (GameMain.Client == null)
                {
                    Hull.EditFire = !Hull.EditFire;
                }

                break;

            case "fixitems":
                foreach (Item it in Item.ItemList)
                {
                    it.Condition = 100.0f;
                }
                break;

            case "fixhull":
            case "fixwalls":
                foreach (Structure w in Structure.WallList)
                {
                    for (int i = 0; i < w.SectionCount; i++)
                    {
                        w.AddDamage(i, -100000.0f);
                    }
                }
                break;

            case "power":
                Item reactorItem = Item.ItemList.Find(i => i.GetComponent <Reactor>() != null);
                if (reactorItem == null)
                {
                    return;
                }

                float power = 5000.0f;
                if (commands.Length > 1)
                {
                    float.TryParse(commands[1], out power);
                }

                var reactor = reactorItem.GetComponent <Reactor>();
                reactor.ShutDownTemp = power == 0 ? 0 : 7000.0f;
                reactor.AutoTemp     = true;
                reactor.Temperature  = power;

                if (GameMain.Server != null)
                {
                    reactorItem.CreateServerEvent(reactor);
                }
                break;

            case "shake":
                GameMain.GameScreen.Cam.Shake = 10.0f;
                break;

            case "losenabled":
            case "los":
            case "drawlos":
                GameMain.LightManager.LosEnabled = !GameMain.LightManager.LosEnabled;
                break;

            case "lighting":
            case "lightingenabled":
            case "light":
            case "lights":
                GameMain.LightManager.LightingEnabled = !GameMain.LightManager.LightingEnabled;
                break;

            case "oxygen":
            case "air":
                foreach (Hull hull in Hull.hullList)
                {
                    hull.OxygenPercentage = 100.0f;
                }
                break;

            case "tutorial":
                TutorialMode.StartTutorial(Tutorials.TutorialType.TutorialTypes[0]);


                break;

            case "editortutorial":
                GameMain.EditMapScreen.Select();
                GameMain.EditMapScreen.StartTutorial();
                break;

            case "lobbyscreen":
            case "lobby":
                GameMain.LobbyScreen.Select();
                break;

            case "savemap":
            case "savesub":
            case "save":
                if (commands.Length < 2)
                {
                    break;
                }

                if (GameMain.EditMapScreen.CharacterMode)
                {
                    GameMain.EditMapScreen.ToggleCharacterMode();
                }

                string fileName = string.Join(" ", commands.Skip(1));
                if (fileName.Contains("../"))
                {
                    DebugConsole.ThrowError("Illegal symbols in filename (../)");
                    return;
                }

                if (Submarine.SaveCurrent(System.IO.Path.Combine(Submarine.SavePath, fileName + ".sub")))
                {
                    NewMessage("Sub saved", Color.Green);
                    //Submarine.Loaded.First().CheckForErrors();
                }

                break;

            case "loadmap":
            case "loadsub":
            case "load":
                if (commands.Length < 2)
                {
                    break;
                }

                Submarine.Load(string.Join(" ", commands.Skip(1)), true);
                break;

            case "cleansub":
                for (int i = MapEntity.mapEntityList.Count - 1; i >= 0; i--)
                {
                    MapEntity me = MapEntity.mapEntityList[i];

                    if (me.SimPosition.Length() > 2000.0f)
                    {
                        DebugConsole.NewMessage("Removed " + me.Name + " (simposition " + me.SimPosition + ")", Color.Orange);
                        MapEntity.mapEntityList.RemoveAt(i);
                    }
                    else if (me.MoveWithLevel)
                    {
                        DebugConsole.NewMessage("Removed " + me.Name + " (MoveWithLevel==true)", Color.Orange);
                        MapEntity.mapEntityList.RemoveAt(i);
                    }
                    else if (me is Item)
                    {
                        Item item = me as Item;
                        var  wire = item.GetComponent <Wire>();
                        if (wire == null)
                        {
                            continue;
                        }

                        if (wire.GetNodes().Count > 0 && !wire.Connections.Any(c => c != null))
                        {
                            wire.Item.Drop(null);
                            DebugConsole.NewMessage("Dropped wire (ID: " + wire.Item.ID + ") - attached on wall but no connections found", Color.Orange);
                        }
                    }
                }
                break;

            case "messagebox":
                if (commands.Length < 3)
                {
                    break;
                }
                new GUIMessageBox(commands[1], commands[2]);
                break;

            case "debugdraw":
                GameMain.DebugDraw = !GameMain.DebugDraw;
                break;

            case "disablehud":
            case "hud":
                GUI.DisableHUD = !GUI.DisableHUD;
                GameMain.Instance.IsMouseVisible = !GameMain.Instance.IsMouseVisible;
                break;

            case "followsub":
                Camera.FollowSub = !Camera.FollowSub;
                break;

            case "drawaitargets":
            case "showaitargets":
                AITarget.ShowAITargets = !AITarget.ShowAITargets;
                break;

            case "killmonsters":
                foreach (Character c in Character.CharacterList)
                {
                    if (!(c.AIController is EnemyAIController))
                    {
                        continue;
                    }
                    c.AddDamage(CauseOfDeath.Damage, 10000.0f, null);
                }
                break;

            case "netstats":
                if (GameMain.Server == null)
                {
                    return;
                }

                GameMain.Server.ShowNetStats = !GameMain.Server.ShowNetStats;
                break;

#if DEBUG
            case "spamevents":
                foreach (Item item in Item.ItemList)
                {
                    for (int i = 0; i < item.components.Count; i++)
                    {
                        if (item.components[i] is IServerSerializable)
                        {
                            GameMain.Server.CreateEntityEvent(item, new object[] { NetEntityEvent.Type.ComponentState, i });
                        }
                        var itemContainer = item.GetComponent <ItemContainer>();
                        if (itemContainer != null)
                        {
                            GameMain.Server.CreateEntityEvent(item, new object[] { NetEntityEvent.Type.InventoryState });
                        }

                        GameMain.Server.CreateEntityEvent(item, new object[] { NetEntityEvent.Type.Status });

                        item.NeedsPositionUpdate = true;
                    }
                }

                foreach (Character c in Character.CharacterList)
                {
                    GameMain.Server.CreateEntityEvent(c, new object[] { NetEntityEvent.Type.Status });
                }

                foreach (Structure wall in Structure.WallList)
                {
                    GameMain.Server.CreateEntityEvent(wall);
                }
                break;

            case "spamchatmessages":
                int msgCount = 1000;
                if (commands.Length > 1)
                {
                    int.TryParse(commands[1], out msgCount);
                }
                int msgLength = 50;
                if (commands.Length > 2)
                {
                    int.TryParse(commands[2], out msgLength);
                }

                for (int i = 0; i < msgCount; i++)
                {
                    if (GameMain.Server != null)
                    {
                        GameMain.Server.SendChatMessage(ToolBox.RandomSeed(msgLength), ChatMessageType.Default);
                    }
                    else
                    {
                        GameMain.Client.SendChatMessage(ToolBox.RandomSeed(msgLength));
                    }
                }
                break;
#endif
            case "cleanbuild":
                GameMain.Config.MusicVolume = 0.5f;
                GameMain.Config.SoundVolume = 0.5f;
                DebugConsole.NewMessage("Music and sound volume set to 0.5", Color.Green);

                GameMain.Config.GraphicsWidth  = 0;
                GameMain.Config.GraphicsHeight = 0;
                GameMain.Config.WindowMode     = WindowMode.Fullscreen;
                DebugConsole.NewMessage("Resolution set to 0 x 0 (screen resolution will be used)", Color.Green);
                DebugConsole.NewMessage("Fullscreen enabled", Color.Green);

                GameSettings.VerboseLogging = false;

                if (GameMain.Config.MasterServerUrl != "http://www.undertowgames.com/baromaster")
                {
                    DebugConsole.ThrowError("MasterServerUrl \"" + GameMain.Config.MasterServerUrl + "\"!");
                }

                GameMain.Config.Save("config.xml");

                var saveFiles = System.IO.Directory.GetFiles(SaveUtil.SaveFolder);

                foreach (string saveFile in saveFiles)
                {
                    System.IO.File.Delete(saveFile);
                    DebugConsole.NewMessage("Deleted " + saveFile, Color.Green);
                }

                if (System.IO.Directory.Exists(System.IO.Path.Combine(SaveUtil.SaveFolder, "temp")))
                {
                    System.IO.Directory.Delete(System.IO.Path.Combine(SaveUtil.SaveFolder, "temp"), true);
                    DebugConsole.NewMessage("Deleted temp save folder", Color.Green);
                }

                if (System.IO.Directory.Exists(ServerLog.SavePath))
                {
                    var logFiles = System.IO.Directory.GetFiles(ServerLog.SavePath);

                    foreach (string logFile in logFiles)
                    {
                        System.IO.File.Delete(logFile);
                        DebugConsole.NewMessage("Deleted " + logFile, Color.Green);
                    }
                }

                if (System.IO.File.Exists("filelist.xml"))
                {
                    System.IO.File.Delete("filelist.xml");
                    DebugConsole.NewMessage("Deleted filelist", Color.Green);
                }


                if (System.IO.File.Exists("Submarines/TutorialSub.sub"))
                {
                    System.IO.File.Delete("Submarines/TutorialSub.sub");

                    DebugConsole.NewMessage("Deleted TutorialSub from the submarine folder", Color.Green);
                }

                if (System.IO.File.Exists(GameServer.SettingsFile))
                {
                    System.IO.File.Delete(GameServer.SettingsFile);
                    DebugConsole.NewMessage("Deleted server settings", Color.Green);
                }

                if (System.IO.File.Exists(GameServer.ClientPermissionsFile))
                {
                    System.IO.File.Delete(GameServer.ClientPermissionsFile);
                    DebugConsole.NewMessage("Deleted client permission file", Color.Green);
                }

                if (System.IO.File.Exists("crashreport.txt"))
                {
                    System.IO.File.Delete("crashreport.txt");
                    DebugConsole.NewMessage("Deleted crashreport.txt", Color.Green);
                }

                if (!System.IO.File.Exists("Content/Map/TutorialSub.sub"))
                {
                    DebugConsole.ThrowError("TutorialSub.sub not found!");
                }

                break;

            default:
                NewMessage("Command not found", Color.Red);
                break;
            }
        }
Esempio n. 47
0
        /// <summary>
        /// Creates a Collider struct from a polygon defined by an array of vectors.
        /// </summary>
        /// <param name="poly">The array of vectors defining the polygon.</param>
        public Collider(Vector2[] poly, Vector2 position, Vector2?offset = null)
        {
            // Polygon type collider setup
            Type = ColliderType.Poly;

            // Copy the polygon into the Points array
            Points = new Vector2[poly.Length];
            poly.CopyTo(Points, 0);

            // Setup the temprary axis list
            var ta        = new List <SATAxis>();
            var gradients = new List <float>();

            // Initialise the bounding box values
            BBCenter = new Vector2();
            BBRadius = new Vector2();
            //Position = Points[0];

            Vector2 off = offset ?? new Vector2();

            for (int i = 0; i < Points.Length; i++)
            {
                Points[i] -= off;
            }
            position += off;
            Position  = position;

            float mx = Points[0].X - position.X;
            float Mx = Points[0].X - position.X;
            float my = Points[0].Y - position.Y;
            float My = Points[0].Y - position.Y;

            for (int i = 0, j = 1; i < Points.Length; i++, j = (j + 1) % Points.Length)
            {
                // Set the position to the minimal X/Y coords, and the bounding box radius to the width/height
                //Position.X = Math.Min(Position.X, Points[i].X);
                //Position.Y = Math.Min(Position.Y, Points[i].Y);
                //BBRadius.X = Math.Max(BBRadius.X, Math.Abs(Position.X - Points[i].X));
                //BBRadius.Y = Math.Max(BBRadius.Y, Math.Abs(Position.Y - Points[i].Y));
                // Update the polygon bounding box.
                mx = Math.Min(mx, Points[i].X - position.X);
                Mx = Math.Max(Mx, Points[i].X - position.X);
                my = Math.Min(my, Points[i].Y - position.Y);
                My = Math.Max(My, Points[i].Y - position.Y);

                // Calculate the gradient of the line
                float gradient = (Points[i].X - Points[j].X) / (Points[i].Y - Points[j].Y);

                // Ignore this axis if we've already stored it by checking against our known gradients.
                if (gradients.Contains(gradient))
                {
                    continue;
                }
                gradients.Add(gradient);

                // Add unique axes to the list
                ta.Add(SATAxis.FromLine(Points[i], Points[j]));
            }

            // Calculate the bounding radius.
            BBRadius = new Vector2(Mx - mx, My - my) / 2f;

            // Set the bounding box center to the middle of the bounding box.
            BBCenter = new Vector2(mx, my) + BBRadius + position;

            // Store all the computed axes into the array.
            Axes = ta.ToArray();
        }
Esempio n. 48
0
        public void Update(GameTime gameTime)
        {
            int c = 0;

            foreach (var f in Fighters)
            {
                if (!f.Update(gameTime) && ((!f.IsAlive && f.isDying) || f.IsAlive))
                {
                    Vector2?pos = f.Move(GameMap, Fighters, Enemies);
                    if (pos != null && f.PlayerControlled)
                    {
                        camera.Pos = (Vector2)pos;
                    }
                }
                else
                {
                    f.isDying = false;
                }
                if (f.IsAlive)
                {
                    c++;
                }
            }

            if (c == 0)
            {
                LostGameScreen lgs = new LostGameScreen("Przegrałeś!");
                lgs.Accepted += delegate(object sender, EventArgs e)
                {
                    LoadingScreen.Load(screenManager, false, new BackgroundScreen(@"Menu\background"), new MainMenuScreen());
                };
                screenManager.AddScreen(lgs);
            }

            c = Enemies.Count;
            for (int i = 0; i < c; i++)
            {
                if (Enemies[i].Update(gameTime))
                {
                    Enemies.RemoveAt(i);
                    i--;
                    c--;
                }
                else
                {
                    Enemies[i].Move(GameMap, Fighters, Enemies);
                    Enemies[i].Notice(GameMap, Fighters, Enemies);
                    Enemies[i].Shoot(screenManager, Weapon.Gun, gameTime, Missiles);
                }
            }

            c = Missiles.Count;
            for (int i = 0; i < c; i++)
            {
                if (Missiles[i].Update(gameTime, GameMap, Fighters, Enemies))
                {
                    Missiles.RemoveAt(i);
                    i--;
                    c--;
                }
            }
        }
Esempio n. 49
0
        protected MyGuiControlListbox AddListbox(List <MyGuiControlBase> controlGroup = null, Vector2?size = null)
        {
            int itemCount = 15;
            var s         = size ?? new Vector2(0.20f, 0.025f);
            var pos       = new Vector2(m_buttonXOffset, m_currentPosition.Y);

            pos.Y += s.Y * itemCount / 2;
            MyGuiControlListbox listbox = new MyGuiControlListbox(this, pos, s, Vector4.One, new StringBuilder(), 0.7f, 1, itemCount, 1, false, true, false);

            Controls.Add(listbox);

            m_currentPosition.Y += 0.04f * m_scale;

            if (controlGroup != null)
            {
                controlGroup.Add(listbox);
            }

            return(listbox);
        }
 private void StopMoving()
 {
     isMoving  = false;
     initTouch = null;
     vignetteController.HideVignette();
 }
Esempio n. 51
0
        protected MyGuiControlButton AddButton(StringBuilder text, MyGuiControlButton.OnButtonClick onClick, List <MyGuiControlBase> controlGroup = null, MyGuiControlButtonTextAlignment textAlign = MyGuiControlButtonTextAlignment.CENTERED, Vector4?textColor = null, Vector2?size = null)
        {
            MyGuiControlButton button = new MyGuiControlButton(this, new Vector2(m_buttonXOffset, m_currentPosition.Y), size ?? new Vector2(0.20f, 0.03f), Vector4.One, text, null, textColor ?? m_defaultColor, MyGuiConstants.LABEL_TEXT_SCALE * MyGuiConstants.DEBUG_BUTTON_TEXT_SCALE * m_scale, onClick, textAlign, true, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, true);

            Controls.Add(button);

            m_currentPosition.Y += 0.04f * m_scale;

            if (controlGroup != null)
            {
                controlGroup.Add(button);
            }

            return(button);
        }
        public override void Draw(BaseScreen.Resources screenResources, SmartSpriteBatch spriteBatch, ScreenAbstractor screen, float opacity, FloatRectangle?clip = null, Texture2D bgTexture = null, Vector2?scrollOffset = null)
        {
            float width    = ActualPosition.Width;
            float height   = ActualPosition.Height;
            float barWidth = BarWidth.Value();

            if (barWidth == 0)
            {
                barWidth = 0.001f;
            }


            float availableWidth = width - barWidth;

            float percentage = Value.Value() / MaxValue.Value();

            float sliderHeight = SliderHeight.Value();

            if (sliderHeight == 0)
            {
                sliderHeight = 0.001f;
            }

            float sliderTop = (height / 2f) - (sliderHeight / 2f);

            FloatRectangle sliderRect = new FloatRectangle(0 + ActualPosition.X, sliderTop + ActualPosition.Y, width, sliderHeight);
            FloatRectangle barRect    = new FloatRectangle(availableWidth * percentage + ActualPosition.X, ActualPosition.Y, barWidth, height);

            if (SliderTexture.HasValue())
            {
                using (new SmartSpriteBatchManager(Solids.Instance.SpriteBatch))
                {
                    spriteBatch.Draw(Solids.Instance.AssetLibrary.GetTexture(SliderTexture.Value(), true), screen.Translate(sliderRect).Value.ToRectangle, Color.White);
                }
            }
            else
            {
                spriteBatch.DrawSolidRectangle(screen.Translate(sliderRect).Value, SliderColor.Value().Value *opacity, clip);
            }

            if (BarTexture.HasValue())
            {
                using (new SmartSpriteBatchManager(Solids.Instance.SpriteBatch))
                {
                    spriteBatch.Draw(Solids.Instance.AssetLibrary.GetTexture(BarTexture.Value(), true), screen.Translate(barRect).Value.ToRectangle, Color.White);
                }
            }
            else
            {
                spriteBatch.DrawSolidRectangle(screen.Translate(barRect).Value, BarColor.Value().Value *opacity, clip);
            }
        }
        /// <summary>Draw text with an icon.</summary>
        /// <param name="batch">The sprite batch.</param>
        /// <param name="font">The sprite font.</param>
        /// <param name="position">The position at which to draw the text.</param>
        /// <param name="absoluteWrapWidth">The width at which to wrap the text.</param>
        /// <param name="text">The block of text to write.</param>
        /// <param name="textColor">The text color.</param>
        /// <param name="icon">The sprite to draw.</param>
        /// <param name="iconSize">The size to draw.</param>
        /// <param name="iconColor">The color to tint the sprite.</param>
        /// <param name="probe">Whether to calculate the positions without actually drawing anything to the screen.</param>
        /// <returns>Returns the drawn size.</returns>
        private Vector2 DrawIconText(SpriteBatch batch, SpriteFont font, Vector2 position, float absoluteWrapWidth, string text, Color textColor, SpriteInfo?icon = null, Vector2?iconSize = null, Color?iconColor = null, bool probe = false)
        {
            // draw icon
            int textOffset = 0;

            if (icon != null && iconSize.HasValue)
            {
                if (!probe)
                {
                    batch.DrawSpriteWithin(icon, position.X, position.Y, iconSize.Value, iconColor);
                }
                textOffset = this.IconMargin;
            }
            else
            {
                iconSize = Vector2.Zero;
            }

            // draw text
            Vector2 textSize = probe
                ? font.MeasureString(text)
                : batch.DrawTextBlock(font, text, position + new Vector2(iconSize.Value.X + textOffset, 0), absoluteWrapWidth - position.X, textColor);

            // get drawn size
            return(new Vector2(
                       x: iconSize.Value.X + textSize.X,
                       y: Math.Max(iconSize.Value.Y, textSize.Y)
                       ));
        }
Esempio n. 54
0
        /// <summary>
        /// Create a new icon.
        /// Note: if you want to use your own texture for the icon, simply set 'icon' to be IconType.None and replace 'Texture' with
        /// your own texture after it is created.
        /// </summary>
        /// <param name="icon">A pre-defined icon to draw.</param>
        /// <param name="anchor">Position anchor.</param>
        /// <param name="scale">Icon default scale.</param>
        /// <param name="background">Whether or not to show icon inventory-like background.</param>
        /// <param name="offset">Offset from anchor position.</param>
        public Icon(UserInterface ui, IconType icon, Anchor anchor = Anchor.Auto, float scale = 1.0f, bool background = false, Vector2?offset = null) :
            base(ui, null, USE_DEFAULT_SIZE, ImageDrawMode.Stretch, anchor, offset)
        {
            // set scale and basic properties
            Scale          = scale;
            DrawBackground = background;
            IconType       = icon;

            // set default background color
            SetStyleProperty("BackgroundColor", new StyleProperty(Color.White));

            // if have background, add default space-after
            if (background)
            {
                SpaceAfter = Vector2.One * BackgroundSize;
            }

            // update default style
            UpdateStyle(DefaultStyle);
        }
Esempio n. 55
0
        public override void AI()
        {
            Vector2?vector78 = null;

            if (projectile.velocity.HasNaNs() || projectile.velocity == Vector2.Zero)
            {
                projectile.velocity = -Vector2.UnitY;
            }
            if (Main.npc[(int)projectile.ai[1]].active && Main.npc[(int)projectile.ai[1]].type == mod.NPCType("AbomBoss"))
            {
                projectile.Center = Main.npc[(int)projectile.ai[1]].Center;
            }
            else
            {
                projectile.Kill();
                return;
            }
            if (projectile.velocity.HasNaNs() || projectile.velocity == Vector2.Zero)
            {
                projectile.velocity = -Vector2.UnitY;
            }
            if (projectile.localAI[0] == 0f)
            {
                Main.PlaySound(SoundID.Zombie, (int)projectile.position.X, (int)projectile.position.Y, 104, 1f, 0f);
            }
            float num801 = 1f;

            projectile.localAI[0] += 1f;
            if (projectile.localAI[0] >= maxTime)
            {
                projectile.Kill();
                return;
            }
            projectile.scale = (float)Math.Sin(projectile.localAI[0] * 3.14159274f / maxTime) * num801 * 6f;
            if (projectile.scale > num801)
            {
                projectile.scale = num801;
            }
            float num804 = projectile.velocity.ToRotation();

            if (Main.npc[(int)projectile.ai[1]].velocity != Vector2.Zero)
            {
                num804 += projectile.ai[0];
            }
            projectile.rotation = num804 - 1.57079637f;
            projectile.velocity = num804.ToRotationVector2();
            float   num805        = 3f;
            float   num806        = (float)projectile.width;
            Vector2 samplingPoint = projectile.Center;

            if (vector78.HasValue)
            {
                samplingPoint = vector78.Value;
            }
            float[] array3 = new float[(int)num805];
            //Collision.LaserScan(samplingPoint, projectile.velocity, num806 * projectile.scale, 3000f, array3);
            for (int i = 0; i < array3.Length; i++)
            {
                array3[i] = 3000f;
            }
            float num807 = 0f;
            int   num3;

            for (int num808 = 0; num808 < array3.Length; num808 = num3 + 1)
            {
                num807 += array3[num808];
                num3    = num808;
            }
            num807 /= num805;
            float amount = 0.5f;

            projectile.localAI[1] = MathHelper.Lerp(projectile.localAI[1], num807, amount);
            Vector2 vector79 = projectile.Center + projectile.velocity * (projectile.localAI[1] - 14f);

            for (int num809 = 0; num809 < 2; num809 = num3 + 1)
            {
                float   num810   = projectile.velocity.ToRotation() + ((Main.rand.Next(2) == 1) ? -1f : 1f) * 1.57079637f;
                float   num811   = (float)Main.rand.NextDouble() * 2f + 2f;
                Vector2 vector80 = new Vector2((float)Math.Cos((double)num810) * num811, (float)Math.Sin((double)num810) * num811);
                int     num812   = Dust.NewDust(vector79, 0, 0, 244, vector80.X, vector80.Y, 0, default(Color), 1f);
                Main.dust[num812].noGravity = true;
                Main.dust[num812].scale     = 1.7f;
                num3 = num809;
            }
            if (Main.rand.Next(5) == 0)
            {
                Vector2 value29 = projectile.velocity.RotatedBy(1.5707963705062866, default(Vector2)) * ((float)Main.rand.NextDouble() - 0.5f) * (float)projectile.width;
                int     num813  = Dust.NewDust(vector79 + value29 - Vector2.One * 4f, 8, 8, 244, 0f, 0f, 100, default(Color), 1.5f);
                Dust    dust    = Main.dust[num813];
                dust.velocity *= 0.5f;
                Main.dust[num813].velocity.Y = -Math.Abs(Main.dust[num813].velocity.Y);
            }
            //DelegateMethods.v3_1 = new Vector3(0.3f, 0.65f, 0.7f);
            //Utils.PlotTileLine(projectile.Center, projectile.Center + projectile.velocity * projectile.localAI[1], (float)projectile.width * projectile.scale, new Utils.PerLinePoint(DelegateMethods.CastLight));

            if (Main.npc[(int)projectile.ai[1]].velocity != Vector2.Zero && --counter < 0)
            {
                counter = 5;
                if (Main.netMode != NetmodeID.MultiplayerClient) //spawn bonus projs
                {
                    Vector2   spawnPos = projectile.Center;
                    Vector2   vel      = projectile.velocity.RotatedBy(Math.PI / 2 * Math.Sign(projectile.ai[0]));
                    const int max      = 15;
                    for (int i = 1; i <= max; i++)
                    {
                        spawnPos += projectile.velocity * 3000f / max;
                        Projectile.NewProjectile(spawnPos, vel, mod.ProjectileType("AbomSickle2"), projectile.damage, 0f, projectile.owner);
                    }
                }
            }

            if (!spawnedHandle)
            {
                spawnedHandle = true;
                if (Main.netMode != NetmodeID.MultiplayerClient)
                {
                    Projectile.NewProjectile(projectile.Center, projectile.velocity, ModContent.ProjectileType <AbomSwordHandle>(), projectile.damage, projectile.knockBack, projectile.owner, (float)Math.PI / 2, projectile.whoAmI);
                    Projectile.NewProjectile(projectile.Center, projectile.velocity, ModContent.ProjectileType <AbomSwordHandle>(), projectile.damage, projectile.knockBack, projectile.owner, -(float)Math.PI / 2, projectile.whoAmI);
                }
            }

            for (int i = 0; i < 40; i++)
            {
                int d = Dust.NewDust(projectile.position + projectile.velocity * Main.rand.NextFloat(3000), projectile.width, projectile.height, 87, 0f, 0f, 0, default(Color), 1.5f);
                Main.dust[d].noGravity = true;
                Main.dust[d].velocity *= 4f;
            }
        }
Esempio n. 56
0
        /// <summary>
        /// Draws the sprite using the nine cut method
        /// This is mostly useful for gui elements like forms and buttons
        /// </summary>
        /// <param name="sb"></param>
        /// <param name="dest"></param>
        /// <param name="source"></param>
        /// <param name="color"></param>
        /// <param name="destEdge"></param>
        /// <param name="sourceEdge"></param>
        /// <param name="scale"></param>
        /// <param name="origin"></param>
        /// <param name="rotation"></param>
        public void DrawNineCut(SpriteBatch sb, Rectangle dest, Rectangle?source = null, Color?color = null, int?destEdge = null, int?sourceEdge = null, Vector2?scale = null, Vector2?origin = null, float rotation = 0f)
        {
            // setup values
            if (color == null)
            {
                color = Color.White;
            }
            if (scale == null)
            {
                scale = Vector2.One;
            }
            if (origin == null)
            {
                origin = new Vector2(dest.Width / 2, dest.Height / 2);
            }

            switch (spriteType)
            {
            case SpriteType.Atlas:
                if (destEdge == null)
                {
                    destEdge = dest.Width / 3;
                }
                if (sourceEdge == null)
                {
                    sourceEdge = Width / 3;
                }
                Atlas.DrawNineCut(sb, AtlasKey, dest, source, color, destEdge, sourceEdge);
                break;

            case SpriteType.Texture:
                if (destEdge == null)
                {
                    destEdge = 15;
                }
                if (sourceEdge == null)
                {
                    sourceEdge = Texture.Width / 3;
                }
                if (source == null)
                {
                    source = Texture.Bounds;
                }
                DrawTextureNineCut(sb, Texture, color.Value, destEdge.Value, sourceEdge.Value, dest, source.Value);
                break;
            }
        }
Esempio n. 57
0
        public void ServerWrite(IWriteMessage msg, Client c, object[] extraData = null)
        {
            string errorMsg = "";

            if (extraData == null || extraData.Length == 0 || !(extraData[0] is NetEntityEvent.Type))
            {
                if (extraData == null)
                {
                    errorMsg = "Failed to write a network event for the item \"" + Name + "\" - event data was null.";
                }
                else if (extraData.Length == 0)
                {
                    errorMsg = "Failed to write a network event for the item \"" + Name + "\" - event data was empty.";
                }
                else
                {
                    errorMsg = "Failed to write a network event for the item \"" + Name + "\" - event type not set.";
                }
                msg.WriteRangedInteger((int)NetEntityEvent.Type.Invalid, 0, Enum.GetValues(typeof(NetEntityEvent.Type)).Length - 1);
                DebugConsole.Log(errorMsg);
                GameAnalyticsManager.AddErrorEventOnce("Item.ServerWrite:InvalidData" + Name, GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
                return;
            }

            int initialWritePos = msg.LengthBits;

            NetEntityEvent.Type eventType = (NetEntityEvent.Type)extraData[0];
            msg.WriteRangedInteger((int)eventType, 0, Enum.GetValues(typeof(NetEntityEvent.Type)).Length - 1);
            switch (eventType)
            {
            case NetEntityEvent.Type.ComponentState:
                if (extraData.Length < 2 || !(extraData[1] is int))
                {
                    errorMsg = "Failed to write a component state event for the item \"" + Name + "\" - component index not given.";
                    break;
                }
                int componentIndex = (int)extraData[1];
                if (componentIndex < 0 || componentIndex >= components.Count)
                {
                    errorMsg = "Failed to write a component state event for the item \"" + Name + "\" - component index out of range (" + componentIndex + ").";
                    break;
                }
                else if (!(components[componentIndex] is IServerSerializable))
                {
                    errorMsg = "Failed to write a component state event for the item \"" + Name + "\" - component \"" + components[componentIndex] + "\" is not server serializable.";
                    break;
                }
                msg.WriteRangedInteger(componentIndex, 0, components.Count - 1);
                (components[componentIndex] as IServerSerializable).ServerWrite(msg, c, extraData);
                break;

            case NetEntityEvent.Type.InventoryState:
                if (extraData.Length < 2 || !(extraData[1] is int))
                {
                    errorMsg = "Failed to write an inventory state event for the item \"" + Name + "\" - component index not given.";
                    break;
                }
                int containerIndex = (int)extraData[1];
                if (containerIndex < 0 || containerIndex >= components.Count)
                {
                    errorMsg = "Failed to write an inventory state event for the item \"" + Name + "\" - container index out of range (" + containerIndex + ").";
                    break;
                }
                else if (!(components[containerIndex] is ItemContainer))
                {
                    errorMsg = "Failed to write an inventory state event for the item \"" + Name + "\" - component \"" + components[containerIndex] + "\" is not server serializable.";
                    break;
                }
                msg.WriteRangedInteger(containerIndex, 0, components.Count - 1);
                msg.Write(GameMain.Server.EntityEventManager.Events.Last()?.ID ?? (ushort)0);
                (components[containerIndex] as ItemContainer).Inventory.ServerWrite(msg, c);
                break;

            case NetEntityEvent.Type.Status:
                msg.Write(condition);
                break;

            case NetEntityEvent.Type.AssignCampaignInteraction:
                msg.Write((byte)CampaignInteractionType);
                break;

            case NetEntityEvent.Type.Treatment:
            {
                ItemComponent targetComponent = (ItemComponent)extraData[1];
                ActionType    actionType      = (ActionType)extraData[2];
                ushort        targetID        = (ushort)extraData[3];
                Limb          targetLimb      = (Limb)extraData[4];

                Character targetCharacter = FindEntityByID(targetID) as Character;
                byte      targetLimbIndex = targetLimb != null && targetCharacter != null ? (byte)Array.IndexOf(targetCharacter.AnimController.Limbs, targetLimb) : (byte)255;

                msg.Write((byte)components.IndexOf(targetComponent));
                msg.WriteRangedInteger((int)actionType, 0, Enum.GetValues(typeof(ActionType)).Length - 1);
                msg.Write(targetID);
                msg.Write(targetLimbIndex);
            }
            break;

            case NetEntityEvent.Type.ApplyStatusEffect:
            {
                ActionType    actionType      = (ActionType)extraData[1];
                ItemComponent targetComponent = extraData.Length > 2 ? (ItemComponent)extraData[2] : null;
                ushort        characterID     = extraData.Length > 3 ? (ushort)extraData[3] : (ushort)0;
                Limb          targetLimb      = extraData.Length > 4 ? (Limb)extraData[4] : null;
                ushort        useTargetID     = extraData.Length > 5 ? (ushort)extraData[5] : (ushort)0;
                Vector2?      worldPosition   = null;
                if (extraData.Length > 6)
                {
                    worldPosition = (Vector2)extraData[6];
                }

                Character targetCharacter = FindEntityByID(characterID) as Character;
                byte      targetLimbIndex = targetLimb != null && targetCharacter != null ? (byte)Array.IndexOf(targetCharacter.AnimController.Limbs, targetLimb) : (byte)255;

                msg.WriteRangedInteger((int)actionType, 0, Enum.GetValues(typeof(ActionType)).Length - 1);
                msg.Write((byte)(targetComponent == null ? 255 : components.IndexOf(targetComponent)));
                msg.Write(characterID);
                msg.Write(targetLimbIndex);
                msg.Write(useTargetID);
                msg.Write(worldPosition.HasValue);
                if (worldPosition.HasValue)
                {
                    msg.Write(worldPosition.Value.X);
                    msg.Write(worldPosition.Value.Y);
                }
            }
            break;

            case NetEntityEvent.Type.ChangeProperty:
                try
                {
                    WritePropertyChange(msg, extraData, inGameEditableOnly: !GameMain.NetworkMember.IsServer);
                }
                catch (Exception e)
                {
                    errorMsg = "Failed to write a ChangeProperty network event for the item \"" + Name + "\" (" + e.Message + ")";
                }
                break;

            case NetEntityEvent.Type.Upgrade:
                if (extraData.Length > 0 && extraData[1] is Upgrade upgrade)
                {
                    var upgradeTargets = upgrade.TargetComponents;
                    msg.Write(upgrade.Identifier);
                    msg.Write((byte)upgrade.Level);
                    msg.Write((byte)upgradeTargets.Count);
                    foreach (var(_, value) in upgrade.TargetComponents)
                    {
                        msg.Write((byte)value.Length);
                        foreach (var propertyReference in value)
                        {
                            object originalValue = propertyReference.OriginalValue;
                            msg.Write((float)(originalValue ?? -1));
                        }
                    }
                }
                else
                {
                    errorMsg = extraData.Length > 0
                            ? $"Failed to write a network event for the item \"{Name}\" - \"{extraData[1].GetType()}\" is not a valid upgrade."
                            : $"Failed to write a network event for the item \"{Name}\". No upgrade specified.";
                }
                break;

            default:
                errorMsg = "Failed to write a network event for the item \"" + Name + "\" - \"" + eventType + "\" is not a valid entity event type for items.";
                break;
            }

            if (!string.IsNullOrEmpty(errorMsg))
            {
                //something went wrong - rewind the write position and write invalid event type to prevent creating an unreadable event
                msg.BitPosition = initialWritePos;
                msg.LengthBits  = initialWritePos;
                msg.WriteRangedInteger((int)NetEntityEvent.Type.Invalid, 0, Enum.GetValues(typeof(NetEntityEvent.Type)).Length - 1);
                DebugConsole.Log(errorMsg);
                GameAnalyticsManager.AddErrorEventOnce("Item.ServerWrite:" + errorMsg, GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
            }
        }
        public void HandleEvent(IBST <IntersectionSweepEvent> events, IBST <IntersectionStatusItem> status,
                                IntersectionSweepEvent ev)
        {
            if (ev.IsStart)
            {
                ev.StatusItem = new IntersectionStatusItem(ev);
                status.Insert(ev.StatusItem);

                IntersectionStatusItem prev, next;
                bool prevFound = status.FindNextSmallest(ev.StatusItem, out prev);
                bool nextFound = status.FindNextBiggest(ev.StatusItem, out next);

                if (prevFound)
                {
                    LineSegment otherSegment = prev.SweepEvent.Segment;
                    Vector2?    intersection = ev.Segment.IntersectProper(otherSegment);
                    if (intersection != null)
                    {
                        events.Insert(new IntersectionSweepEvent(intersection.Value, false, false,
                                                                 ev.Segment, otherSegment));
                    }
                }

                if (nextFound)
                {
                    LineSegment otherSegment = next.SweepEvent.Segment;
                    Vector2?    intersection = ev.Segment.IntersectProper(otherSegment);
                    if (intersection != null)
                    {
                        events.Insert(new IntersectionSweepEvent(intersection.Value, false, false,
                                                                 ev.Segment, otherSegment));
                    }
                }
            }
            else if (ev.IsEnd)
            {
                ev = ev.OtherEvent;
                if (ev.StatusItem == null)
                {
                    return;
                }

                IntersectionStatusItem prev, next;
                bool prevFound = status.FindNextSmallest(ev.StatusItem, out prev);
                bool nextFound = status.FindNextBiggest(ev.StatusItem, out next);

                status.Delete(ev.StatusItem);

                if (nextFound && prevFound)
                {
                    LineSegment segment      = prev.SweepEvent.Segment;
                    LineSegment otherSegment = next.SweepEvent.Segment;
                    Vector2?    intersection = segment.IntersectProper(otherSegment);
                    if (intersection != null)
                    {
                        events.Insert(new IntersectionSweepEvent(intersection.Value, false, false,
                                                                 segment, otherSegment));
                    }
                }
            }
            else if (ev.IsIntersection)
            {
                // stop on first intersection
                intersected = new List <Edge>
                {
                    new Edge(new Vertex(ev.Segment.Point1), new Vertex(ev.Segment.Point2)),
                    new Edge(new Vertex(ev.OtherSegment.Point1), new Vertex(ev.OtherSegment.Point2))
                };
                events.Clear();
                status.Clear();
            }
            else
            {
                throw new Exception("Invalid event type");
            }
        }
 /*********
 ** Public methods
 *********/
 /// <summary>Construct an instance.</summary>
 /// <param name="obj">The underlying in-game object.</param>
 /// <param name="tilePosition">The object's tile position in the current location (if applicable).</param>
 /// <param name="reflection">Simplifies access to private game code.</param>
 public ObjectTarget(Object obj, Vector2?tilePosition, IReflectionHelper reflection)
     : base(TargetType.Object, obj, tilePosition)
 {
     this.Reflection = reflection;
 }
Esempio n. 60
0
 /// <summary>
 /// Blit a quad to OpenGL display with specified parameters.
 /// </summary>
 public abstract void DrawQuad(Quad vertexQuad, RectangleF?textureRect, ColourInfo drawColour, Action <TexturedVertex2D> vertexAction = null, Vector2?inflationPercentage = null, Vector2?blendRangeOverride = null);