예제 #1
0
        public override void OnTick(Entity[] entities)
        {
            TimeToLive--;
            PickupDelay--;

            if (TimeToLive <= 0)
            {
                DespawnEntity();
                return;
            }

            if (PickupDelay > 0)
            {
                return;
            }

            var players = Level.GetSpawnedPlayers();

            foreach (SkyPlayer player in players)
            {
                if (!player.IsGameSpectator && KnownPosition.DistanceTo(player.KnownPosition) <= 2)
                {
                    GameState.AddPlayerGunParts((MurderLevel)Level, player);

                    GameState.GunParts.Remove(SpawnLocation);

                    DespawnEntity();
                    break;
                }
            }
        }
예제 #2
0
        /// <summary>
        /// For debugging of flight-path and rotation.
        /// </summary>
        private void BroadcastMoveAndMotion()
        {
            if (new Random().Next(5) == 0)
            {
                McpeSetEntityMotion motions = McpeSetEntityMotion.CreateObject();
                motions.runtimeEntityId = EntityId;
                motions.velocity        = Velocity;
                //new Task(() => Level.RelayBroadcast(motions)).Start();
                Level.RelayBroadcast(motions);
            }

            McpeMoveEntity moveEntity = McpeMoveEntity.CreateObject();

            moveEntity.runtimeEntityId = EntityId;
            moveEntity.position        = KnownPosition;
            Level.RelayBroadcast(moveEntity);

            if (Shooter != null && IsCritical)
            {
                var p = Shooter as Player;

                if (p != null)
                {
                    var particle = new CriticalParticle(Level);
                    particle.Position = KnownPosition.ToVector3();
                    particle.Spawn(new[] { p });
                }
            }
        }
예제 #3
0
        /// <summary>
        ///     For debugging of flight-path and rotation.
        /// </summary>
        private void BroadcastMoveAndMotion()
        {
            if (new Random().Next(5) == 0)
            {
                McpeSetEntityMotion motions = McpeSetEntityMotion.CreateObject();
                motions.runtimeEntityId = EntityId;
                motions.velocity        = Velocity;
                Level.RelayBroadcast(motions);
            }

            if (LastSentPosition != null)
            {
                McpeMoveEntityDelta move = McpeMoveEntityDelta.CreateObject();
                move.runtimeEntityId  = EntityId;
                move.prevSentPosition = LastSentPosition;
                move.currentPosition  = (PlayerLocation)KnownPosition.Clone();
                move.isOnGround       = IsWalker && IsOnGround;
                if (move.SetFlags())
                {
                    Level.RelayBroadcast(move);
                }
            }

            LastSentPosition = (PlayerLocation)KnownPosition.Clone();              // Used for delta

            if (Shooter != null && IsCritical)
            {
                var particle = new CriticalParticle(Level);
                particle.Position = KnownPosition.ToVector3();
                particle.Spawn(new[] { Shooter });
            }
        }
예제 #4
0
        public override void OnTick()
        {
            TimeToLive--;

            if (TimeToLive <= 0)
            {
                DespawnEntity(null);
                return;
            }

            var players = Level.GetOnlinePlayers;

            foreach (var player in players)
            {
                if (KnownPosition.DistanceTo(player.KnownPosition) <= 1.8)
                {
                    player.Inventory.AddItem(Item.ItemId, Item.MetaData);

                    DespawnEntity(player);
                    break;
                }
                new EntityTeleport(player.Wrapper)
                {
                    UniqueServerId = EntityId,
                    Coordinates    = KnownPosition.ToVector3(),
                    Yaw            = (byte)KnownPosition.Yaw,
                    Pitch          = (byte)KnownPosition.Pitch,
                    OnGround       = true
                }.Write();
            }
        }
예제 #5
0
        public PlayerCountHologram(string name, Level level, PlayerLocation playerLocation, string gameName) : base(name, level, playerLocation)
        {
            _gameName = gameName;

            KnownPosition    = (PlayerLocation)KnownPosition.Clone();
            KnownPosition.Y += 2.8f;
        }
예제 #6
0
        public override void Update(IUpdateArgs args)
        {
            if (CanRender)
            {
                var knownPos = KnownPosition.ToVector3();
                //    var bb       = base.BoundingBox;
                // var knownPos = bb.GetCenter();

                if (DoRotation)
                {
                    //var offset = new Vector3((float) Width, (float) Height, (float) Width) / 2f;
                    var offset = new Vector3(0.5f, 0f, 0.5f);
                    ItemRenderer.Update(args, MCMatrix.CreateScale(0.25f)
                                        * MCMatrix.CreateTranslation(-offset)
                                        * MCMatrix.CreateRotationY(MathHelper.ToRadians(_rotation))
                                        * MCMatrix.CreateTranslation(offset)
                                        * MCMatrix.CreateTranslation(knownPos));
                }
                else
                {
                    ItemRenderer.Update(args, MCMatrix.CreateScale(0.25f)
                                        * MCMatrix.CreateRotationY(MathHelper.ToRadians(KnownPosition.Yaw))
                                        * MCMatrix.CreateTranslation(knownPos));
                }
            }

            if (DoRotation)
            {
                _rotation += 45f * (float)args.GameTime.ElapsedGameTime.TotalSeconds;
            }
        }
예제 #7
0
        public override void OnTick()
        {
            base.OnTick();

            if (Velocity.Length() > 0)
            {
                PlayerLocation oldPosition    = (PlayerLocation)KnownPosition.Clone();
                bool           onGroundBefore = IsOnGround(KnownPosition);

                KnownPosition.X += (float)Velocity.X;
                KnownPosition.Y += (float)Velocity.Y;
                KnownPosition.Z += (float)Velocity.Z;

                bool onGround = IsOnGround(KnownPosition);
                if (!onGroundBefore && onGround)
                {
                    KnownPosition.Y = (float)Math.Floor(oldPosition.Y);
                    Velocity        = Vector3.Zero;
                }
                else
                {
                    Velocity *= (float)(1.0f - Drag);
                    if (!onGround)
                    {
                        Velocity -= new Vector3(0, (float)Gravity, 0);
                    }
                }
                LastUpdatedTime = DateTime.UtcNow;
            }
            else if (Velocity != Vector3.Zero)
            {
                Velocity        = Vector3.Zero;
                LastUpdatedTime = DateTime.UtcNow;
            }
        }
예제 #8
0
        /// <inheritdoc />
        public override void HandleMcpeBlockEntityData(McpeBlockEntityData message)
        {
            var playerPosition = KnownPosition.ToBlockCoordinates();

            if (playerPosition.DistanceTo(message.coordinates) > 1000)
            {
                return;
            }

            var nbt = message.namedtag.NbtFile.RootTag;

            if (nbt is NbtCompound compound)
            {
                var blockEntity = Level.GetBlockEntity(message.coordinates);
                EventDispatcher.DispatchEventAsync(new PlayerSetBlockEntityDataEvent(this, blockEntity, compound)).Then(
                    (result) =>
                {
                    if (result.IsCancelled)
                    {
                        return;
                    }

                    blockEntity.SetCompound(compound);
                    Level.SetBlockEntity(blockEntity);
                });
            }

            //base.HandleMcpeBlockEntityData(message);
        }
예제 #9
0
        private Vector3 GetAdjustedLengthFromCollision(Vector3 velocity)
        {
            var length    = Length / 2;
            var direction = Vector3.Normalize(Velocity * 1.00000101f);
            var position  = KnownPosition.ToVector3();
            int count     = (int)(Math.Ceiling(Velocity.Length() / length) + 2);

            for (int i = 0; i < count; i++)
            {
                var distVec = direction * (float)length * i;
                BlockCoordinates blockPos = position + distVec;
                Block            block    = Level.GetBlock(blockPos);
                if (block.IsSolid)
                {
                    Ray ray      = new Ray(position, direction);
                    var distance = ray.Intersects(block.GetBoundingBox());
                    if (distance.HasValue)
                    {
                        float dist = (float)((float)distance - (Length / 4));
                        return(ray.Direction * new Vector3(dist));
                    }
                }
            }

            return(velocity);
        }
예제 #10
0
        public override void Update(IUpdateArgs args)
        {
            if (CanRender)
            {
                var offset = new Vector3(0.5f, 0.5f, 0.5f);

                if (DoRotation)
                {
                    ItemRenderer.Update(args, Matrix.Identity * Matrix.CreateScale(Scale) * Matrix.CreateTranslation(-offset)
                                        * Matrix.CreateRotationY(MathHelper.ToRadians(_rotation)) * Matrix.CreateTranslation(offset)
                                        * Matrix.CreateTranslation((KnownPosition.ToVector3())), Color.White.ToVector3(), KnownPosition);
                }
                else
                {
                    ItemRenderer.Update(args, Matrix.Identity * Matrix.CreateScale(Scale)
                                        * Matrix.CreateRotationY(MathHelper.ToRadians(KnownPosition.Yaw))
                                        * Matrix.CreateTranslation(KnownPosition.ToVector3()), Color.White.ToVector3(), KnownPosition);
                }

                ItemRenderer?.Update(args.GraphicsDevice, args.Camera);
            }

            if (DoRotation)
            {
                _rotation += 45f * (float)args.GameTime.ElapsedGameTime.TotalSeconds;
            }
        }
예제 #11
0
파일: Entity.cs 프로젝트: kroer/MiNET
        public void BroadcastMove(bool forceMove = false)
        {
            //if (NoAi || forceMove)
            {
                //McpeMoveEntity moveEntity = McpeMoveEntity.CreateObject();
                //moveEntity.runtimeEntityId = EntityId;
                //moveEntity.position = LastSentPosition;
                //moveEntity.flags = (short) (IsOnGround? 1: 0);
                //moveEntity.Encode();
                //Level.RelayBroadcast(moveEntity);

                if (LastSentPosition != null)
                {
                    McpeMoveEntityDelta move = McpeMoveEntityDelta.CreateObject();
                    move.runtimeEntityId  = EntityId;
                    move.prevSentPosition = LastSentPosition;
                    move.currentPosition  = (PlayerLocation)KnownPosition.Clone();
                    move.isOnGround       = IsWalker && IsOnGround;
                    if (move.SetFlags())
                    {
                        Level.RelayBroadcast(move);
                    }
                }

                LastSentPosition = (PlayerLocation)KnownPosition.Clone();                  // Used for delta
            }
        }
예제 #12
0
 public static void MoveAllToKnownPosition(KnownPosition knownPosition)
 {
     foreach (var axe in new Axe[] { Axe.X, Axe.Y, Axe.Z })
     {
         foreach (var courronne in new Couronne[] { Couronne.MidMin, Couronne.MidMax, Couronne.Max })
         {
             MoveToKnownPosition(axe, courronne, knownPosition);
         }
     }
 }
예제 #13
0
 public void BroadcastMove(bool forceMove = false)
 {
     if (NoAi || forceMove)
     {
         McpeMoveEntity moveEntity = McpeMoveEntity.CreateObject();
         moveEntity.runtimeEntityId = EntityId;
         moveEntity.position        = (PlayerLocation)KnownPosition.Clone();
         moveEntity.Encode();
         Level.RelayBroadcast(moveEntity);
     }
 }
예제 #14
0
 private void DoTeleport()
 {
     if (Shooter is Player shooter)
     {
         if (KnownPosition.Y > 0)
         {
             shooter.Teleport((PlayerLocation)KnownPosition.Clone());
             shooter.HealthManager.TakeHit(this, CalculateDamage(shooter), DamageCause.Magic);
         }
     }
 }
예제 #15
0
        public override void Update(IUpdateArgs args)
        {
            if (CanRender)
            {
                ItemRenderer?.Update(
                    Matrix.Identity * Matrix.CreateScale(Scale)
                    * Matrix.CreateRotationY(MathHelper.ToRadians(KnownPosition.Yaw))
                    * Matrix.CreateTranslation(KnownPosition.ToVector3()), KnownPosition);

                ItemRenderer?.Update(args.GraphicsDevice, args.Camera);
            }
        }
예제 #16
0
파일: Entity.cs 프로젝트: wqd1019dqw/Alex
        public virtual void OnTick()
        {
            Age++;

            if (DoRotationCalculations)
            {
                UpdateRotations();
            }

            _previousPosition = KnownPosition;

            if (IsNoAi)
            {
                return;
            }
            //	IsMoving = Velocity.LengthSquared() > 0f;

            var feetBlock = Level?.GetBlock(new BlockCoordinates(KnownPosition));

            if (feetBlock != null)
            {
                if (!feetBlock.Solid)
                {
                    if (KnownPosition.OnGround)
                    {
                        KnownPosition.OnGround = false;
                    }
                    else
                    {
                    }
                }
                else
                {
                    //KnownPosition.OnGround = true;
                }
            }

            var headBlock = Level?.GetBlock(KnownPosition.GetCoordinates3D() + new BlockCoordinates(0, 1, 0));

            if (headBlock != null)
            {
                if (headBlock.IsWater)
                {
                    IsInWater = true;
                }
                else
                {
                    IsInWater = false;
                }
            }

            //HealthManager.OnTick();
        }
예제 #17
0
        private void PositionCheck()
        {
            BlockCoordinates check = KnownPosition.GetCoordinates3D() + Level.Down;

            if (!Level.GetBlock(check).IsSolid)
            {
                KnownPosition.Y -= 1;
            }
            else
            {
                CheckPosition = false;
            }
        }
예제 #18
0
 private void BroadcastMoveAndMotion()
 {
     foreach (var i in Level.OnlinePlayers)
     {
         new EntityTeleport(i.Wrapper)
         {
             UniqueServerID = EntityId,
             Coordinates    = KnownPosition.ToVector3(),
             Yaw            = (byte)KnownPosition.Yaw,
             Pitch          = (byte)KnownPosition.Pitch,
             OnGround       = true
         }.Write();
     }
 }
예제 #19
0
        public override void SpawnEntity()
        {
            Velocity            = Force = KnownPosition.GetDirection().Normalize() * 0.06055374f;
            KnownPosition.Yaw   = (float)Velocity.GetYaw();
            KnownPosition.Pitch = (float)Velocity.GetPitch();

            McpeLevelSoundEvent sound = McpeLevelSoundEvent.CreateObject();

            sound.soundId    = 55;
            sound.blockId    = -1;
            sound.entityType = 1;
            sound.position   = KnownPosition;
            Level.RelayBroadcast(sound);

            base.SpawnEntity();
        }
예제 #20
0
        public override void OnTick()
        {
            base.OnTick();

            TimeToLive--;
            PickupDelay--;

            if (TimeToLive <= 0)
            {
                DespawnEntity();
                return;
            }

            // Motion



            if (PickupDelay > 0)
            {
                return;
            }

            var players = Level.GetSpawnedPlayers();

            foreach (var player in players)
            {
                if (KnownPosition.DistanceTo(player.KnownPosition) <= 2)
                {
                    if (player.GameMode == GameMode.Survival)
                    {
                        //Add the items to the inventory if posible
                        if (player.Inventory.SetFirstEmptySlot((short)Item.Id, (byte)Count, Item.Metadata))
                        {
                            //BUG: If this is sent, the client crashes for some unknown reason.
                            var takeItemEntity = McpeTakeItemEntity.CreateObject();
                            takeItemEntity.entityId = EntityId;
                            takeItemEntity.target   = player.EntityId;

                            Level.RelayBroadcast(takeItemEntity);
                            DespawnEntity();
                            break;
                        }
                    }
                }
            }
        }
예제 #21
0
        public void SendPlayerPositionAndLook()
        {
            PlayerLocation loc = (PlayerLocation)KnownPosition.Clone();

            PlayerPositionAndLookPacket packet = new PlayerPositionAndLookPacket()
            {
                Flags      = 0,
                TeleportId = 0,
                X          = loc.X,
                Y          = loc.Y,
                Z          = loc.Z,
                Yaw        = loc.Yaw,
                Pitch      = loc.Pitch
            };

            Connection.SendPacket(packet);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="state"></param>
        /// <param name="remainQuarters"></param>
        /// <param name="sens">1 ou -1</param>
        /// <param name="axe"></param>
        //private static void AddWithAnticollision(GlobalState state,int[] remainQuarters, int sens, Axe axe)
        //{
        //    var couronnesToMove = new List<Couronne>();
        //    var couronnesToFix = new List<Couronne>();

        //    if (Math.Sign(remainQuarters[0]) == sens)
        //    {
        //        couronnesToMove.Add(Couronne.MidMin);
        //        remainQuarters[0] -= sens ;
        //    }
        //    else couronnesToFix.Add(Couronne.MidMin);

        //    if (Math.Sign(remainQuarters[1]) == sens)
        //    {
        //        couronnesToMove.Add(Couronne.MidMax);
        //    remainQuarters[1] -= sens;
        //    }
        //    else couronnesToFix.Add(Couronne.MidMax);

        //    if (Math.Sign(remainQuarters[2]) == sens)
        //    {
        //        couronnesToMove.Add(Couronne.Max);
        //        remainQuarters[2]-= sens;
        //    }
        //    else couronnesToFix.Add(Couronne.Max);


        //    if (couronnesToMove.Count == 0) return;

        //    Add(new SetAccelerationInstruction(state.HardwareConfigGlobal.DisengagedAcceleration));
        //    Add(new SetSpeedInstruction(state.HardwareConfigGlobal.DisengagedSpeed));

        //    // mise en position des couronnes parallèles
        //    foreach (var c in couronnesToFix)
        //    {
        //        AddMoveToKnowPosition(axe, c, sens > 0 ? KnownPosition.MinStop : KnownPosition.MaxStop);
        //    }

        //    // mise en position des couronnes motrices
        //    foreach (var c in couronnesToMove)
        //    {
        //        AddMoveToKnowPosition(axe, c, sens > 0 ? KnownPosition.MaxStop : KnownPosition.MinStop);
        //    }


        //    //Déplacement des autres couronnes perpendiculaires
        //    foreach (var motor in state.Motors.Motors)
        //    {
        //        if (motor.Axe == axe) continue;
        //        /*
        //        var negCollision = couronnesToMove.Any((c) => motor.NegativeCollision.HasCollision(axe, c));
        //        var posCollision = couronnesToMove.Any((c) => motor.PositiveCollision.HasCollision(axe, c));

        //        KnownPosition pos;

        //        if (negCollision && posCollision) pos = KnownPosition.Middle;
        //        else if (negCollision) pos = KnownPosition.MaxStop;
        //        else if (posCollision) pos = KnownPosition.MinStop;
        //        else
        //        {
        //            // si pas de collision, ne pas toucher au moteur sauf s'il est en position middle non engreiné
        //            if (_designContext.GetPosition(motor.Courronne, motor.Axe) == KnownPosition.Middle) pos = KnownPosition.MinStop;
        //            else continue;
        //        }

        //        AddMoveToKnowPosition(motor.Axe, motor.Courronne, pos);
        //        */
        //        AddMoveToKnowPosition(motor.Axe, motor.Courronne, KnownPosition.Middle);

        //    }

        //    Add(new WaitTargetReachedInstruction());

        //    Add(new SetAccelerationInstruction(state.HardwareConfigGlobal.EngagedAcceleration));
        //    Add(new SetSpeedInstruction(state.HardwareConfigGlobal.EngagedSpeed));

        //    // faire un quart de tour
        //    foreach(var c in couronnesToMove)
        //    {
        //        AddMoveToKnowPosition(axe, c, sens > 0 ? KnownPosition.PositiveQuarterFromMaxStop : KnownPosition.NegativeQuarterFromMinStop);
        //    }

        //    Add(new WaitTargetReachedInstruction());
        //}

        private static void AddMoveToKnowPosition(Axe axe, Couronne couronne, KnownPosition pos)
        {
            Add(new MoveToKnownPositionInstruction(axe, couronne, pos));

            /*
             * if (_designContext.GetPosition(couronne, axe) != pos)
             * {
             *  Add(new MoveToKnownPositionInstruction(axe, couronne, pos));
             *
             *  // un quart de tour ne modifie pas la position actuelle, ne mettre à jour que si changement
             *  if (pos != KnownPosition.NegativeQuarter && pos != KnownPosition.PositiveQuarter)
             *  {
             *      _designContext.SetPosition(couronne, axe, pos);
             *  }
             * }
             */
        }
예제 #23
0
        public override void SpawnToPlayers(Player[] players)
        {
            McpeAddItemEntity mcpeAddItemEntity = McpeAddItemEntity.CreateObject();

            mcpeAddItemEntity.entityIdSelf    = EntityId;
            mcpeAddItemEntity.runtimeEntityId = EntityId;
            mcpeAddItemEntity.item            = GetItemStack();
            mcpeAddItemEntity.x        = KnownPosition.X;
            mcpeAddItemEntity.y        = KnownPosition.Y;
            mcpeAddItemEntity.z        = KnownPosition.Z;
            mcpeAddItemEntity.speedX   = Velocity.X;
            mcpeAddItemEntity.speedY   = Velocity.Y;
            mcpeAddItemEntity.speedZ   = Velocity.Z;
            mcpeAddItemEntity.metadata = GetMetadata();
            LastSentPosition           = (PlayerLocation)KnownPosition.Clone();
            Level.RelayBroadcast(players, mcpeAddItemEntity);

            BroadcastSetEntityData();
        }
예제 #24
0
        public override void OnTick()
        {
            base.OnTick();

            if (Velocity.Distance > 0)
            {
                PlayerLocation oldPosition    = (PlayerLocation)KnownPosition.Clone();
                var            onGroundBefore = IsOnGround(KnownPosition);

                KnownPosition.X += (float)Velocity.X;
                KnownPosition.Y += (float)Velocity.Y;
                KnownPosition.Z += (float)Velocity.Z;

                var onGround = IsOnGround(KnownPosition);
                if (!onGroundBefore && onGround)
                {
                    KnownPosition.Y = (float)Math.Floor(oldPosition.Y);
                    Velocity        = Vector3.Zero;
                }
                else
                {
                    Velocity *= (1.0 - Drag);
                    Velocity -= new Vector3(0, Gravity, 0);
                }
            }

            McpeMoveEntity moveEntity = McpeMoveEntity.CreateObject();

            moveEntity.entities = new EntityLocations {
                { EntityId, KnownPosition }
            };
            Level.RelayBroadcast(moveEntity);

            McpeSetEntityMotion motions = McpeSetEntityMotion.CreateObject();

            motions.entities = new EntityMotions {
                { EntityId, Velocity }
            };
            Level.RelayBroadcast(motions);
        }
예제 #25
0
        private void BroadcastMoveAndMotion()
        {
            foreach (var i in Level.GetOnlinePlayers)
            {
                new EntityTeleport(i.Wrapper)
                {
                    UniqueServerId = EntityId,
                    Coordinates    = KnownPosition.ToVector3(),
                    Yaw            = KnownPosition.Yaw,
                    Pitch          = KnownPosition.Pitch,
                    OnGround       = false
                }.Write();

                new EntityVelocity(i.Wrapper)
                {
                    EntityId  = EntityId,
                    VelocityX = (short)Velocity.X,
                    VelocityY = (short)Velocity.Y,
                    VelocityZ = (short)Velocity.Z
                }.Write();
            }
        }
예제 #26
0
        public override void OnTick()
        {
            base.OnTick();

            TimeToLive--;
            PickupDelay--;

            if (TimeToLive <= 0)
            {
                DespawnEntity();
                return;
            }

            if (PickupDelay > 0)
            {
                return;
            }

            var players = Level.GetSpawnedPlayers();

            foreach (var player in players)
            {
                if (KnownPosition.DistanceTo(player.KnownPosition) <= 1)
                {
                    //BUG: If this is sent, the client crashes for some unknown reason.
                    Level.RelayBroadcast(new McpeTakeItemEntity()
                    {
                        //entityId = player.EntityId,
                        //target = EntityId
                        entityId = EntityId,
                        target   = player.EntityId
                    });
                    player.Inventory.SetFirstEmptySlot((short)Item.Id, (byte)Count, Item.Metadata);                     //Add the items to the inventory

                    DespawnEntity();
                    break;
                }
            }
        }
예제 #27
0
파일: Projectile.cs 프로젝트: qtx0213/MiNET
        public override void OnTick()
        {
            base.OnTick();

            if (KnownPosition.Y <= 0 ||
                (Velocity.Distance <= 0 && DespawnOnImpact) ||
                (Velocity.Distance <= 0 && !DespawnOnImpact && Ttl <= 0))
            {
                DespawnEntity();
                return;
            }

            Ttl--;

            if (KnownPosition.Y <= 0 || Velocity.Distance <= 0)
            {
                return;
            }

            Entity entityCollided = CheckEntityCollide(KnownPosition.ToVector3(), Velocity);

            bool collided = false;

            if (entityCollided != null)
            {
                double speed  = Math.Sqrt(Velocity.X * Velocity.X + Velocity.Y * Velocity.Y + Velocity.Z * Velocity.Z);
                double damage = Math.Ceiling(speed * Damage);
                if (IsCritical)
                {
                    damage += Level.Random.Next((int)(damage / 2 + 2));

                    McpeAnimate animate = McpeAnimate.CreateObject();
                    animate.entityId = entityCollided.EntityId;
                    animate.actionId = 4;
                    Level.RelayBroadcast(animate);
                }

                Player player = entityCollided as Player;

                if (player != null)
                {
                    damage = player.CalculatePlayerDamage(player, damage);
                }

                entityCollided.HealthManager.TakeHit(this, (int)damage, DamageCause.Projectile);
                entityCollided.HealthManager.LastDamageSource = Shooter;
                collided = true;
            }
            else
            {
                var velocity2 = Velocity;
                velocity2 *= (1.0d - Drag);
                velocity2 -= new Vector3(0, Gravity, 0);
                double distance = velocity2.Distance;
                velocity2 = velocity2.Normalize() / 2;

                for (int i = 0; i < Math.Ceiling(distance) * 2; i++)
                {
                    PlayerLocation nextPos = (PlayerLocation)KnownPosition.Clone();
                    nextPos.X += (float)velocity2.X * i;
                    nextPos.Y += (float)velocity2.Y * i;
                    nextPos.Z += (float)velocity2.Z * i;

                    BlockCoordinates coord = new BlockCoordinates(nextPos);
                    Block            block = Level.GetBlock(coord);
                    collided = block.Id != 0 && (block.GetBoundingBox()).Contains(nextPos.ToVector3());
                    if (collided)
                    {
                        SetIntersectLocation(block.GetBoundingBox(), KnownPosition);
                        break;
                    }
                }
            }

            if (collided)
            {
                Velocity = Vector3.Zero;
            }
            else
            {
                KnownPosition.X += (float)Velocity.X;
                KnownPosition.Y += (float)Velocity.Y;
                KnownPosition.Z += (float)Velocity.Z;

                Velocity *= (1.0 - Drag);
                Velocity -= new Vector3(0, Gravity, 0);

                KnownPosition.Yaw   = (float)Velocity.GetYaw();
                KnownPosition.Pitch = (float)Velocity.GetPitch();
            }

            // For debugging of flight-path
            if (BroadcastMovement)
            {
                BroadcastMoveAndMotion();
            }
        }
예제 #28
0
        private bool CheckBlockCollide(PlayerLocation location)
        {
            var bbox = GetBoundingBox();
            var pos  = location.ToVector3();

            var coords = new BlockCoordinates(
                (int)Math.Floor(KnownPosition.X),
                (int)Math.Floor((bbox.Max.Y + bbox.Min.Y) / 2.0),
                (int)Math.Floor(KnownPosition.Z));

            Dictionary <double, Block> blocks = new Dictionary <double, Block>();

            for (int x = -1; x < 2; x++)
            {
                for (int z = -1; z < 2; z++)
                {
                    for (int y = -1; y < 2; y++)
                    {
                        Block block = Level.GetBlock(coords.X + x, coords.Y + y, coords.Z + z);
                        if (block is Air)
                        {
                            continue;
                        }

                        BoundingBox blockbox = block.GetBoundingBox() + 0.3f;
                        if (blockbox.Intersects(GetBoundingBox()))
                        {
                            //if (!blockbox.Contains(KnownPosition.ToVector3())) continue;

                            if (block is FlowingLava || block is StationaryLava)
                            {
                                HealthManager.Ignite(1200);
                                continue;
                            }

                            if (!block.IsSolid)
                            {
                                continue;
                            }

                            blockbox = block.GetBoundingBox();

                            var midPoint = blockbox.Min + new Vector3(0.5f);
                            blocks.Add(Vector3.Distance((pos - Velocity), midPoint), block);
                        }
                    }
                }
            }

            if (blocks.Count == 0)
            {
                return(false);
            }

            var firstBlock = blocks.OrderBy(pair => pair.Key).First().Value;

            BoundingBox boundingBox = firstBlock.GetBoundingBox();

            if (!SetIntersectLocation(boundingBox, KnownPosition.ToVector3()))
            {
                // No real hit
                return(false);
            }

            // Use to debug hits, makes visual impressions (can be used for paintball too)
            var substBlock = new Stone {
                Coordinates = firstBlock.Coordinates
            };

            Level.SetBlock(substBlock);
            // End debug block

            Velocity = Vector3.Zero;
            return(true);
        }
예제 #29
0
        public override void Update(IUpdateArgs args)
        {
            if (WaitingOnChunk && Age % 4 == 0)
            {
                NoAi = true;

                if (Level.GetChunk(KnownPosition.GetCoordinates3D(), true) != null)
                {
                    Velocity       = Vector3.Zero;
                    WaitingOnChunk = false;
                    NoAi           = false;
                }
            }

            ChunkCoordinates oldChunkCoordinates = new ChunkCoordinates(base.KnownPosition);
            bool             sprint = IsSprinting;
            bool             sneak  = IsSneaking;

            if (!CanFly && IsFlying)
            {
                IsFlying = false;
            }

            if (IsSprinting && !CanSprint)
            {
                IsSprinting = false;
            }

            Controller.Update(args.GameTime);
            //KnownPosition.HeadYaw = KnownPosition.Yaw;

            if (IsSprinting && !sprint)
            {
                FOVModifier = 10;

                Network.EntityAction((int)EntityId, EntityAction.StartSprinting);
            }
            else if (!IsSprinting && sprint)
            {
                FOVModifier = 0;

                Network.EntityAction((int)EntityId, EntityAction.StopSprinting);
            }

            if (IsSneaking != sneak)
            {
                if (IsSneaking)
                {
                    Network.EntityAction((int)EntityId, EntityAction.StartSneaking);
                    Camera.UpdateOffset(new Vector3(0f, -0.15f, 0.35f));
                }
                else
                {
                    Network.EntityAction((int)EntityId, EntityAction.StopSneaking);
                    Camera.UpdateOffset(Vector3.Zero);
                }
            }

            //	DoHealthAndExhaustion();

            var previousCheckedInput = _prevCheckedInput;

            if ((Controller.CheckInput && Controller.CheckMovementInput))
            {
                _prevCheckedInput = true;
                if (!previousCheckedInput || World.FormManager.IsShowingForm)
                {
                    return;
                }

                UpdateRayTracer();

                //if (Controller.InputManager.IsDown(InputCommand.LeftClick) && DateTime.UtcNow - _lastAnimate >= TimeSpan.FromMilliseconds(500))
                //{
                //	SwingArm(true);
                //}

                var hitEntity = HitEntity;
                if (hitEntity != null && Controller.InputManager.IsPressed(InputCommand.LeftClick) && hitEntity is LivingEntity)
                {
                    if (_destroyingBlock)
                    {
                        StopBreakingBlock(forceCanceled: true);
                    }

                    InteractWithEntity(hitEntity, true);
                }
                else if (hitEntity != null && Controller.InputManager.IsPressed(InputCommand.RightClick) && hitEntity is LivingEntity)
                {
                    if (_destroyingBlock)
                    {
                        StopBreakingBlock(forceCanceled: true);
                    }

                    InteractWithEntity(hitEntity, false);
                }
                else if (hitEntity == null && !_destroyingBlock &&
                         Controller.InputManager.IsPressed(InputCommand.LeftClick) &&
                         !HasRaytraceResult)
                {
                    HandleLeftClick(Inventory[Inventory.SelectedSlot], Inventory.SelectedSlot);
                }
                else if (hitEntity == null && !_destroyingBlock && Controller.InputManager.IsDown(InputCommand.LeftClick) && !IsWorldImmutable && HasRaytraceResult)                 //Destroying block.
                {
                    StartBreakingBlock();
                }
                else if (_destroyingBlock && Controller.InputManager.IsUp(InputCommand.LeftClick))
                {
                    StopBreakingBlock();
                }
                else if (_destroyingBlock && Controller.InputManager.IsDown(InputCommand.LeftClick))
                {
                    if (_destroyingTarget != new BlockCoordinates(Vector3.Floor(Raytraced)))
                    {
                        StopBreakingBlock(true, true);

                        if (Gamemode != Gamemode.Creative)
                        {
                            StartBreakingBlock();
                        }
                    }
                    else
                    {
                        if ((DateTime.UtcNow - _lastAnimate).TotalMilliseconds > 500)
                        {
                            _lastAnimate = DateTime.UtcNow;
                            SwingArm(true);
                        }

                        var timeRan = (DateTime.UtcNow - _destroyingTick).TotalMilliseconds / 50d;
                        if (timeRan >= _destroyTimeNeeded)
                        {
                            StopBreakingBlock(true);
                        }
                    }
                }
                else if (Controller.InputManager.IsPressed(InputCommand.RightClick))
                {
                    bool handledClick = false;
                    var  item         = Inventory[Inventory.SelectedSlot];
                    // Log.Debug($"Right click!");
                    if (item != null)
                    {
                        handledClick = HandleClick(item, Inventory.SelectedSlot);
                    }

                    /*if (!handledClick && Inventory.OffHand != null && !(Inventory.OffHand is ItemAir))
                     * {
                     *      handledClick = HandleRightClick(Inventory.OffHand, 1);
                     * }*/
                }

                if (hitEntity != null && HasCollision)
                {
                    if (IsColliding(hitEntity))
                    {
                        //var distance = DistanceToHorizontal(hitEntity);
                        //	Velocity += (KnownPosition.ToVector3() - hitEntity.KnownPosition.ToVector3());
                    }
                }
            }
            else
            {
                if (_destroyingBlock)
                {
                    StopBreakingBlock();
                }

                _prevCheckedInput     = false;
                _lastTimeWithoutInput = DateTime.UtcNow;
            }

            if (PreviousSlot != Inventory.SelectedSlot)
            {
                var slot = Inventory.SelectedSlot;
                Network?.HeldItemChanged(Inventory[Inventory.SelectedSlot], (short)slot);
                PreviousSlot = slot;
            }

            base.Update(args);
        }
예제 #30
0
        public override void OnTick(Entity[] entities)
        {
            //base.OnTick();

            if (KnownPosition.Y <= 0 ||
                (Velocity.Length() <= 0 && DespawnOnImpact) ||
                (Velocity.Length() <= 0 && !DespawnOnImpact && Ttl <= 0))
            {
                if (DespawnOnImpact || (!DespawnOnImpact && Ttl <= 0))
                {
                    DespawnEntity();
                    return;
                }
                else
                {
                    IsCritical = false;
                }
                return;
            }

            Ttl--;

            if (KnownPosition.Y <= 0 || Velocity.Length() <= 0)
            {
                return;
            }

            Entity entityCollided = CheckEntityCollide(KnownPosition, Velocity);

            bool collided = false;

            if (entityCollided != null)
            {
                if (OnEntityColission(entityCollided))
                {
                    double speed  = Math.Sqrt(Velocity.X * Velocity.X + Velocity.Y * Velocity.Y + Velocity.Z * Velocity.Z);
                    double damage = Math.Ceiling(speed * Damage);
                    if (IsCritical)
                    {
                        damage += Level.Random.Next((int)(damage / 2 + 2));

                        McpeAnimate animate = McpeAnimate.CreateObject();
                        animate.runtimeEntityId = entityCollided.EntityId;
                        animate.actionId        = 4;
                        Level.RelayBroadcast(animate);
                    }

                    if (PowerLevel > 0)
                    {
                        damage = damage + ((PowerLevel + 1) * 0.25);
                    }


                    Player player = entityCollided as Player;

                    if (player != null)
                    {
                        damage = player.DamageCalculator.CalculatePlayerDamage(this, player, null, damage, DamageCause.Projectile);
                        player.LastAttackTarget = entityCollided;
                    }

                    entityCollided.HealthManager.TakeHit(this, (int)damage, DamageCause.Projectile);
                    entityCollided.HealthManager.LastDamageSource = Shooter;

                    DespawnEntity();
                    return;
                }
            }
            else
            {
                var velocity2 = Velocity;
                velocity2 *= (float)(1.0d - Drag);
                velocity2 -= new Vector3(0, (float)Gravity, 0);
                double distance = velocity2.Length();
                velocity2 = Vector3.Normalize(velocity2) / 2;

                for (int i = 0; i < Math.Ceiling(distance) * 2; i++)
                {
                    Vector3 nextPos = KnownPosition.ToVector3();
                    nextPos.X += velocity2.X * i;
                    nextPos.Y += velocity2.Y * i;
                    nextPos.Z += velocity2.Z * i;

                    Block block = Level.GetBlock(nextPos);
                    collided = block.IsSolid && block.GetBoundingBox().Contains(nextPos);
                    if (collided && OnBlockColission(block))
                    {
                        SetIntersectLocation(block.GetBoundingBox(), KnownPosition.ToVector3());
                        break;
                    }
                }
            }

            if (collided)
            {
                Velocity = Vector3.Zero;
            }
            else
            {
                KnownPosition.X += (float)Velocity.X;
                KnownPosition.Y += (float)Velocity.Y;
                KnownPosition.Z += (float)Velocity.Z;

                Velocity *= (float)(1.0 - Drag);
                Velocity -= new Vector3(0, (float)Gravity, 0);

                KnownPosition.Yaw   = (float)Velocity.GetYaw();
                KnownPosition.Pitch = (float)Velocity.GetPitch();
            }

            // For debugging of flight-path
            if (BroadcastMovement)
            {
                //LastUpdatedTime = DateTime.UtcNow;

                BroadcastMoveAndMotion();
            }
        }