Exemplo n.º 1
0
        public void Update(GameTime gameTime)
        {
            if (currentControlScheme == ControlScheme.A)
            {
                ControlSchemeA();
            }
            if (currentControlScheme == ControlScheme.B)
            {
                ControlSchemeB();
            }


            RayCastResult result;
            Vector3       pos = ParentObject.Transform.AbsoluteTransform.Translation;

            pos += new Vector3(0, -2, 0);
            BEPUutilities.Vector3 chopperPos = new BEPUutilities.Vector3(pos.X, pos.Y, pos.Z);
            BEPUutilities.Ray     r          = new BEPUutilities.Ray(chopperPos, BEPUutilities.Vector3.Down);


            if (SystemCore.PhysicsSimulation.RayCast(r, out result))
            {
                if (result.HitObject.Tag is Chopper)
                {
                }
                else
                {
                    //float distance = result.HitData.T;
                    //if (distance < 5)
                    //    Ascend(lateralForce/2);
                    //else
                    //    Descend(lateralForce/2);
                }
            }
        }
 public static bool Raycast(Ray ray, out RaycastHit raycastHit, float maxDistance = float.MaxValue)
 {
     BEPUphysics.RayCastResult result;
     BEPUutilities.Ray r = new BEPUutilities.Ray()
     {
         Direction = ray.direction,
         Position = ray.origin,
     };
     bool ret = PhysicsUsage.PhysicsManager.instance.Space.RayCast(r, maxDistance, out result);
     if (ret)
     {
         var other = result.HitObject;
         var otherEntity = other as BEPUphysics.BroadPhaseEntries.MobileCollidables.EntityCollidable;
         var otherCollider = otherEntity.Entity.Tag as Collider;
         raycastHit = new RaycastHit()
             {
                 m_Collider = otherCollider,
                 m_Point = result.HitData.Location,
                 m_Normal = result.HitData.Normal,
                 m_Distance = result.HitData.T,
             };
     }
     else
     {
         raycastHit = new RaycastHit();
     }
     return ret;
 }
Exemplo n.º 3
0
        public static Ray Convert(BEPUutilities.Ray ray)
        {
            Ray toReturn;

            Convert(ref ray.Position, out toReturn.Position);
            Convert(ref ray.Direction, out toReturn.Direction);
            return(toReturn);
        }
Exemplo n.º 4
0
        public override void Update(GameTime gameTime)
        {
            if (input.EvaluateInputBinding("MainMenu"))
            {
                SystemCore.ScreenManager.AddAndSetActive(new MainMenuScreen());
            }


            if (input.EvaluateInputBinding("CameraForward"))
            {
                mouseCamera.MoveForward();
            }
            if (input.EvaluateInputBinding("CameraBackward"))
            {
                mouseCamera.MoveBackward();
            }
            if (input.EvaluateInputBinding("CameraLeft"))
            {
                mouseCamera.MoveLeft();
            }
            if (input.EvaluateInputBinding("CameraRight"))
            {
                mouseCamera.MoveRight();
            }

            RayCastResult result;

            if (input.MouseLeftPress())
            {
                Matrix            camWorld = Matrix.Invert(SystemCore.ActiveCamera.View);
                BEPUutilities.Ray ray      = new BEPUutilities.Ray(camWorld.Translation.ToBepuVector(), camWorld.Forward.ToBepuVector());

                if (SystemCore.PhysicsSimulation.RayCast(ray, out result))
                {
                    Debugger.Break();
                }
            }

            mouseCamera.Update(gameTime, input.MouseDelta.X, input.MouseDelta.Y);
            input.CenterMouse();

            List <GameObject> activeGameObjects = SystemCore.GetSubsystem <GameObjectManager>().GetAllObjects();
            BoundingBox       testVolume        = new BoundingBox(new Vector3(-100, -100, -100), new Vector3(100, 100, 100));

            foreach (GameObject activeGameObject in activeGameObjects)
            {
                if (testVolume.Contains(activeGameObject.Transform.AbsoluteTransform.Translation) == ContainmentType.Disjoint)
                {
                    activeGameObject.Transform.SetPosition(-activeGameObject.Transform.AbsoluteTransform.Translation);
                }
            }

            base.Update(gameTime);
        }
Exemplo n.º 5
0
        private void RaycastTest()
        {
            RayCastResult result;
            Matrix        camWorld = Matrix.Invert(SystemCore.ActiveCamera.View);

            BEPUutilities.Ray ray =
                new BEPUutilities.Ray(camWorld.Translation.ToBepuVector() + camWorld.Forward.ToBepuVector() * 3f,
                                      camWorld.Forward.ToBepuVector());

            if (SystemCore.PhysicsSimulation.RayCast(ray, out result))
            {
                hitPos = result.HitData.Location.ToXNAVector();
                DebugShapeRenderer.AddLine(hitPos,
                                           hitPos + Vector3.Normalize(result.HitData.Normal.ToXNAVector() * 5f), Color.Blue);
            }
        }
Exemplo n.º 6
0
        public override void Fire()
        {
            // Play 'pop' sound
            Actor          owner = GameResources.ActorManager.GetActorById(OwnerActorId);
            WeaponResource wr    = owner.GetBehavior <WeaponResource>();

            wr.Value -= ResourceCostToUse;
            BipedControllerComponent bipedControl = owner.GetComponent <BipedControllerComponent>(ActorComponent.ComponentType.Control);
            Vector3 aim = (bipedControl.WorldAim.HasValue ? bipedControl.WorldAim.Value :
                           BepuConverter.Convert(bipedControl.Controller.ViewDirection));
            Matrix muzzleTransform = Matrix.CreateTranslation(MuzzleOffset) * Matrix.CreateWorld(BepuConverter.Convert(
                                                                                                     bipedControl.Controller.Body.Position), aim, Vector3.Up);
            BepuRay       shootRay = new BepuRay(BepuConverter.Convert(muzzleTransform.Translation), BepuConverter.Convert(muzzleTransform.Forward));
            RayCastResult result;

            GameResources.ActorManager.SimSpace.RayCast(shootRay, 500.0f, out result);

            EntityCollidable otherEntityCollidable = result.HitObject as EntityCollidable;
            Terrain          otherTerrain          = result.HitObject as Terrain;

            if (otherEntityCollidable != null &&
                otherEntityCollidable.Entity != null &&
                otherEntityCollidable.Entity.Tag != null)
            {
                Actor      actorHit = GameResources.ActorManager.GetActorById((int)(otherEntityCollidable.Entity.Tag));
                IDamagable damage   = actorHit.GetBehaviorThatImplementsType <IDamagable>();
                if (damage != null)
                {
                    damage.TakeDamage(Damage);
                    // TODO: P2: Query hit actor for appropiate damage effect e.g. blood and create it;
                }
                HitSparks(result.HitData.Location);
            }
            else if (otherTerrain != null)
            {
                HitSparks(result.HitData.Location);
            }
        }
Exemplo n.º 7
0
 public bool RayCast(BEPUutilities.Ray ray, out RayCastResult result)
 {
     return(space.RayCast(ray, out result));
 }
Exemplo n.º 8
0
        private void PreAnimationUpdateHandler(object sender, UpdateStepEventArgs e)
        {
            float elapsedTime = (float)(e.GameTime.ElapsedGameTime.TotalSeconds);

            Actor avatar = GameResources.ActorManager.GetActorById(ActorId);
            BipedControllerComponent bipedControl = avatar.GetComponent<BipedControllerComponent>(ActorComponent.ComponentType.Control);

            // Update the camera.
            Vector3 desiredCameraPosition;
            if (mInputMode == InputMode.Aloof)
            {
                Matrix cameraRotation = Matrix.CreateFromYawPitchRoll(mMmoCameraDesc.Yaw, mMmoCameraDesc.Pitch, 0.0f);
                BepuRay boomRay = new BepuRay(mAvatarBepuEntity.Position, BepuConverter.Convert(cameraRotation.Backward));
                RayCastResult result;

                GameResources.ActorManager.SimSpace.RayCast(boomRay, mMmoCameraDesc.Distance, CameraClipFilter, out result);

                desiredCameraPosition = result.HitObject != null ?
                    BepuConverter.Convert(BEPUutilities.Vector3.Lerp(result.HitData.Location, mAvatarBepuEntity.Position, 0.05f)) :
                    BepuConverter.Convert(mAvatarBepuEntity.Position) + mMmoCameraDesc.Distance * cameraRotation.Backward;
            }
            else if (mInputMode == InputMode.Aiming)
            {
                Matrix viewRotation = Matrix.CreateWorld(Vector3.Zero, BepuConverter.Convert(
                    bipedControl.Controller.ViewDirection), Vector3.Up);
                desiredCameraPosition = BepuConverter.Convert(mAvatarBepuEntity.Position) + Vector3.Transform(
                    mAimingCameraOffset, viewRotation);
            }
            else
            {
                desiredCameraPosition = mCamera.Transform.Translation;
            }

            Vector3 newCameraPosition = desiredCameraPosition;

            Vector3 desiredCameraDirection;
            if (mInputMode == InputMode.Aloof)
            {
                desiredCameraDirection = BepuConverter.Convert(mAvatarBepuEntity.Position) - newCameraPosition;
            }
            else if (mInputMode == InputMode.Aiming)
            {
                desiredCameraDirection = BepuConverter.Convert(bipedControl.Controller.ViewDirection);
            }
            else
            {
                desiredCameraDirection = mCamera.Transform.Forward;
            }
            desiredCameraDirection.Normalize();

            Vector3 newCameraDirection = desiredCameraDirection;

            if (mCameraSmoothingEngaged)
            {
                Vector3 positionDelta = desiredCameraPosition - mCamera.Transform.Translation;
                Quaternion directionDelta = SpaceUtils.GetSweptQuaternion(mCamera.Transform.Forward, desiredCameraDirection);

                const float POSITION_DELTA_THRESHHOLD = 4.0f;
                const float DIRECTION_DELTA_THRESHHOLD = MathHelper.Pi / 16.0f;

                float positionDeltaLength = positionDelta.Length();
                float directionDeltaAngle = (float)(SpaceUtils.GetQuaternionAngle(directionDelta));

                float fractionComplete = Math.Min(POSITION_DELTA_THRESHHOLD / positionDeltaLength,
                    DIRECTION_DELTA_THRESHHOLD / directionDeltaAngle);

                if (fractionComplete < 1.0f)
                {
                    newCameraPosition = Vector3.Lerp(mCamera.Transform.Translation, desiredCameraPosition, fractionComplete);
                    Quaternion smoothedCamRotation = Quaternion.Slerp(Quaternion.Identity, directionDelta, fractionComplete);
                    newCameraDirection = Vector3.Transform(mCamera.Transform.Forward, smoothedCamRotation);
                }
            }
            else
            {
                mCameraSmoothingEngaged = true;
            }

            mCamera.Transform = Matrix.CreateWorld(newCameraPosition, newCameraDirection, Vector3.Up);
        }
Exemplo n.º 9
0
 public static Ray ToSharp(this BEPUutilities.Ray r)
 {
     return(new Ray(r.Position.ToSharp(), r.Direction.ToSharp()));
 }
Exemplo n.º 10
0
        public override void Fire()
        {
            // Play 'pop' sound
            Actor owner = GameResources.ActorManager.GetActorById(OwnerActorId);
            WeaponResource wr = owner.GetBehavior<WeaponResource>();
            wr.Value -= ResourceCostToUse;
            BipedControllerComponent bipedControl = owner.GetComponent<BipedControllerComponent>(ActorComponent.ComponentType.Control);
            Vector3 aim = (bipedControl.WorldAim.HasValue ? bipedControl.WorldAim.Value :
                BepuConverter.Convert(bipedControl.Controller.ViewDirection));
            Matrix muzzleTransform = Matrix.CreateTranslation(MuzzleOffset) * Matrix.CreateWorld(BepuConverter.Convert(
                bipedControl.Controller.Body.Position), aim, Vector3.Up);
            BepuRay shootRay = new BepuRay(BepuConverter.Convert(muzzleTransform.Translation), BepuConverter.Convert(muzzleTransform.Forward));
            RayCastResult result;

            GameResources.ActorManager.SimSpace.RayCast(shootRay, 500.0f, out result);

            EntityCollidable otherEntityCollidable = result.HitObject as EntityCollidable;
            Terrain otherTerrain = result.HitObject as Terrain;
            if (otherEntityCollidable != null &&
                otherEntityCollidable.Entity != null &&
                otherEntityCollidable.Entity.Tag != null)
            {
                Actor actorHit = GameResources.ActorManager.GetActorById((int)(otherEntityCollidable.Entity.Tag));
                IDamagable damage = actorHit.GetBehaviorThatImplementsType<IDamagable>();
                if (damage != null)
                {
                    damage.TakeDamage(Damage);
                    // TODO: P2: Query hit actor for appropiate damage effect e.g. blood and create it;
                }
                HitSparks(result.HitData.Location);
            }
            else if (otherTerrain != null)
            {
                HitSparks(result.HitData.Location);
            }
        }
Exemplo n.º 11
0
 public static void Convert(ref BEPUutilities.Ray ray, out Ray xnaRay)
 {
     Convert(ref ray.Position, out xnaRay.Position);
     Convert(ref ray.Direction, out xnaRay.Direction);
 }
Exemplo n.º 12
0
        public void ImpactHandler(object sender, UpdateStepEventArgs e)
        {
            GameResources.ActorManager.PostPhysicsUpdateStep -= ImpactHandler;
            // TODO: P2: Some boooom sound effects...

            TransformComponent myXForm = Owner.GetComponent <TransformComponent>(ActorComponent.ComponentType.Transform);
            // Do a sphere cast to get actors in the blast radius
            List <RayCastResult> inRangeActors = new List <RayCastResult>();
            SphereShape          blastZone     = new SphereShape(mBlastRadius);
            RigidTransform       blastPosition = new RigidTransform(BepuConverter.Convert(myXForm.Translation));

            BEPUutilities.Vector3 bepuZero = BEPUutilities.Vector3.Zero;
            GameResources.ActorManager.SimSpace.ConvexCast(blastZone, ref blastPosition, ref bepuZero, inRangeActors);

            RayCastDistanceComparer rcdc = new RayCastDistanceComparer();

            for (int a = 0; a < inRangeActors.Count; ++a)
            {
                EntityCollidable inRangeEntityCollidable = inRangeActors[a].HitObject as EntityCollidable;
                if (inRangeEntityCollidable != null &&
                    inRangeEntityCollidable.Entity != null &&
                    inRangeEntityCollidable.Entity.Tag != null)
                {
                    Actor      blastedActor = GameResources.ActorManager.GetActorById((int)(inRangeEntityCollidable.Entity.Tag));
                    IDamagable actorDamage  = blastedActor.GetBehaviorThatImplementsType <IDamagable>();
                    DynamicCollisionComponent actorCollidable = blastedActor.GetComponent <DynamicCollisionComponent>(ActorComponent.ComponentType.Physics);
                    BepuVec3 blastToActorCenter = actorCollidable.Entity.Position - blastPosition.Position;
                    BepuRay  loeRay             = new BepuRay(blastPosition.Position, blastToActorCenter);
                    bool     hasCover           = false;
                    float    distance           = mBlastRadius;
                    if (actorDamage != null || (actorCollidable != null && actorCollidable.IsDynamic && !(actorCollidable.Entity.CollisionInformation.CollisionRules.Personal.HasFlag(BEPUphysics.CollisionRuleManagement.CollisionRule.NoSolver))))
                    {
                        List <RayCastResult> loeResults = new List <RayCastResult>();
                        GameResources.ActorManager.SimSpace.RayCast(loeRay, mBlastRadius, loeResults);
                        loeResults.Sort(rcdc);

                        for (int c = 0; c < loeResults.Count; ++c)
                        {
                            EntityCollidable possibleCover = loeResults[c].HitObject as EntityCollidable;
                            if (possibleCover != null &&
                                possibleCover.Entity == inRangeEntityCollidable.Entity)
                            {
                                // Hit
                                distance = loeResults[c].HitData.T;
                                break;
                            }
                            Terrain possibleCoverTerrain = loeResults[c].HitObject as Terrain;
                            if (possibleCoverTerrain != null)
                            {
                                hasCover = true;
                                break;
                            }
                            if (possibleCover != null &&
                                possibleCover.Entity != null &&
                                !possibleCover.Entity.IsDynamic)
                            {
                                hasCover = true;
                                break;
                            }
                        }
                    }

                    if (!hasCover && actorDamage != null)
                    {
                        actorDamage.TakeDamage((int)(MathHelper.Lerp(1.0f, 0.25f, distance / mBlastRadius) * mDamage));
                    }

                    if (!hasCover && actorCollidable != null && actorCollidable.IsDynamic && !(actorCollidable.Entity.CollisionInformation.CollisionRules.Personal.HasFlag(BEPUphysics.CollisionRuleManagement.CollisionRule.NoSolver)))
                    {
                        blastToActorCenter.Normalize();
                        blastToActorCenter = blastToActorCenter * 1200; // Math.Min(5000.0f / (distance + 1.0f));
                        actorCollidable.Entity.ApplyLinearImpulse(ref blastToActorCenter);
                        if (!actorCollidable.Entity.ActivityInformation.IsActive)
                        {
                            actorCollidable.Entity.ActivityInformation.Activate();
                        }
                    }
                }
            }

            DynamicCollisionComponent dcc = Owner.GetComponent <DynamicCollisionComponent>(ActorComponent.ComponentType.Physics);
            Vector3            myVelocity = BepuConverter.Convert(dcc.Entity.LinearVelocity);
            Actor              fireball   = GameResources.ActorManager.SpawnTemplate("ExplosionFire");
            TransformComponent fireXForm  = fireball.GetComponent <TransformComponent>(ActorComponent.ComponentType.Transform);

            fireXForm.Translation = myXForm.Translation;
            ExplosionFire fireBehavior = fireball.GetBehavior <ExplosionFire>();

            fireBehavior.Emit(myVelocity);
            Actor smoke = GameResources.ActorManager.SpawnTemplate("ExplosionSmoke");
            TransformComponent smokeXForm = smoke.GetComponent <TransformComponent>(ActorComponent.ComponentType.Transform);

            smokeXForm.Translation = myXForm.Translation;
            ExplosionSmoke smokeBehavior = smoke.GetBehavior <ExplosionSmoke>();

            smokeBehavior.Emit(myVelocity);

            Owner.Despawn();
        }
Exemplo n.º 13
0
 public static void Convert(ref Ray ray, out BEPUutilities.Ray bepuRay)
 {
     Convert(ref ray.Position, out bepuRay.Position);
     Convert(ref ray.Direction, out bepuRay.Direction);
 }
Exemplo n.º 14
0
        private void PreAnimationUpdateHandler(object sender, UpdateStepEventArgs e)
        {
            float elapsedTime = (float)(e.GameTime.ElapsedGameTime.TotalSeconds);

            Actor avatar = GameResources.ActorManager.GetActorById(ActorId);
            BipedControllerComponent bipedControl = avatar.GetComponent <BipedControllerComponent>(ActorComponent.ComponentType.Control);

            // Update the camera.
            Vector3 desiredCameraPosition;

            if (mInputMode == InputMode.Aloof)
            {
                Matrix        cameraRotation = Matrix.CreateFromYawPitchRoll(mMmoCameraDesc.Yaw, mMmoCameraDesc.Pitch, 0.0f);
                BepuRay       boomRay        = new BepuRay(mAvatarBepuEntity.Position, BepuConverter.Convert(cameraRotation.Backward));
                RayCastResult result;

                GameResources.ActorManager.SimSpace.RayCast(boomRay, mMmoCameraDesc.Distance, CameraClipFilter, out result);

                desiredCameraPosition = result.HitObject != null?
                                        BepuConverter.Convert(BEPUutilities.Vector3.Lerp(result.HitData.Location, mAvatarBepuEntity.Position, 0.05f)) :
                                            BepuConverter.Convert(mAvatarBepuEntity.Position) + mMmoCameraDesc.Distance * cameraRotation.Backward;
            }
            else if (mInputMode == InputMode.Aiming)
            {
                Matrix viewRotation = Matrix.CreateWorld(Vector3.Zero, BepuConverter.Convert(
                                                             bipedControl.Controller.ViewDirection), Vector3.Up);
                desiredCameraPosition = BepuConverter.Convert(mAvatarBepuEntity.Position) + Vector3.Transform(
                    mAimingCameraOffset, viewRotation);
            }
            else
            {
                desiredCameraPosition = mCamera.Transform.Translation;
            }

            Vector3 newCameraPosition = desiredCameraPosition;

            Vector3 desiredCameraDirection;

            if (mInputMode == InputMode.Aloof)
            {
                desiredCameraDirection = BepuConverter.Convert(mAvatarBepuEntity.Position) - newCameraPosition;
            }
            else if (mInputMode == InputMode.Aiming)
            {
                desiredCameraDirection = BepuConverter.Convert(bipedControl.Controller.ViewDirection);
            }
            else
            {
                desiredCameraDirection = mCamera.Transform.Forward;
            }
            desiredCameraDirection.Normalize();

            Vector3 newCameraDirection = desiredCameraDirection;

            if (mCameraSmoothingEngaged)
            {
                Vector3    positionDelta  = desiredCameraPosition - mCamera.Transform.Translation;
                Quaternion directionDelta = SpaceUtils.GetSweptQuaternion(mCamera.Transform.Forward, desiredCameraDirection);

                const float POSITION_DELTA_THRESHHOLD  = 4.0f;
                const float DIRECTION_DELTA_THRESHHOLD = MathHelper.Pi / 16.0f;

                float positionDeltaLength = positionDelta.Length();
                float directionDeltaAngle = (float)(SpaceUtils.GetQuaternionAngle(directionDelta));

                float fractionComplete = Math.Min(POSITION_DELTA_THRESHHOLD / positionDeltaLength,
                                                  DIRECTION_DELTA_THRESHHOLD / directionDeltaAngle);

                if (fractionComplete < 1.0f)
                {
                    newCameraPosition = Vector3.Lerp(mCamera.Transform.Translation, desiredCameraPosition, fractionComplete);
                    Quaternion smoothedCamRotation = Quaternion.Slerp(Quaternion.Identity, directionDelta, fractionComplete);
                    newCameraDirection = Vector3.Transform(mCamera.Transform.Forward, smoothedCamRotation);
                }
            }
            else
            {
                mCameraSmoothingEngaged = true;
            }

            mCamera.Transform = Matrix.CreateWorld(newCameraPosition, newCameraDirection, Vector3.Up);
        }
Exemplo n.º 15
0
 public override bool RayCast(BEPUutilities.Ray ray, float maximumLength, out BEPUutilities.RayHit rayHit)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 16
0
        public override void Update(/* inout */ SteeringBlender steering, Actor owner, IAgentStateManager agent)
        {
            if (!agent.HasProperty(AgentPropertyName.ActiveOpponent))
            {
                ZombieWaitState zws = new ZombieWaitState(6.0f);
                agent.CurrentState = zws;
                return;
            }

            Actor opponent = GameResources.ActorManager.GetActorById(agent.GetProperty <int>(AgentPropertyName.ActiveOpponent));
            BipedControllerComponent opponentBcc = opponent.GetComponent <BipedControllerComponent>(ActorComponent.ComponentType.Control);

            steering.Target = BepuConverter.Convert(opponentBcc.Controller.Body.Position);

            BipedControllerComponent bcc = owner.GetComponent <BipedControllerComponent>(ActorComponent.ComponentType.Control);

            BepuVec3       toOpponent   = opponentBcc.Controller.Body.Position - bcc.Controller.Body.Position;
            float          distance     = toOpponent.Length();
            ZombieSkillSet zss          = owner.GetBehaviorThatImplementsType <ZombieSkillSet>();
            BipedWeapon    chosenAttack = distance <= zss.MeleeSkill.EffectiveRangeMax ? zss.MeleeSkill : zss.RangedSkill;

            Matrix attackTransform = Matrix.CreateTranslation(chosenAttack.MuzzleOffset) * Matrix.CreateWorld(
                BepuConverter.Convert(bcc.Controller.Body.Position), BepuConverter.Convert(bcc.Controller.ViewDirection), Vector3.Up);

            BepuVec3 bulletPath = opponentBcc.Controller.Body.Position - BepuConverter.Convert(attackTransform.Translation);

            // If we don't have a shot, we need to specify what kind of movement we need to remedy that.
            ZombieTacticalMovementState.MovementType movement = ZombieTacticalMovementState.MovementType.None;

            if (distance < chosenAttack.EffectiveRangeMin)
            {
                movement = ZombieTacticalMovementState.MovementType.Retreat;
            }
            else if (distance > chosenAttack.EffectiveRangeMax)
            {
                movement = ZombieTacticalMovementState.MovementType.Close;
            }
            else
            {
                BepuRay       loeRay = new BepuRay(BepuConverter.Convert(attackTransform.Translation), bulletPath);
                LOSFilter     filter = new LOSFilter(bcc.Controller.Body.CollisionInformation, opponentBcc.Controller.Body.CollisionInformation);
                RayCastResult loeResult;
                GameResources.ActorManager.SimSpace.RayCast(loeRay, chosenAttack.EffectiveRangeMax * 1.5f, filter.Test, out loeResult);

                EntityCollidable otherEntityCollidable = loeResult.HitObject as EntityCollidable;
                if (otherEntityCollidable != null &&
                    otherEntityCollidable.Entity != null &&
                    otherEntityCollidable.Entity.Tag != null &&
                    (int)(otherEntityCollidable.Entity.Tag) == opponent.Id)
                {
                    toOpponent.Y = 0.0f;
                    toOpponent.Normalize();
                    float       aimTheta         = (float)(Math.Acos(MathHelper.Clamp(BepuVec3.Dot(toOpponent, bcc.Controller.ViewDirection), 0.0f, 1.0f)));
                    const float AIM_CONE_RADIANS = MathHelper.Pi / 12.0f;
                    if (aimTheta <= AIM_CONE_RADIANS)
                    {
                        // TODO: P2: Add some wander to this value:
                        bcc.WorldAim = BepuConverter.Convert(bulletPath);
                        //chosenAttack.CurrentOperation = WeaponFunctions.TriggerPulled;
                        BipedWeapon otherAttack = chosenAttack == zss.MeleeSkill ? zss.RangedSkill : zss.MeleeSkill;
                        otherAttack.UpdateInputState(false, bcc);
                        chosenAttack.UpdateInputState(true, bcc);
                        return;
                    }
                }
                else
                {
                    movement = ZombieTacticalMovementState.MovementType.Lateral;
                }
            }

            if (movement != ZombieTacticalMovementState.MovementType.None)
            {
                ZombieTacticalMovementState ztms = new ZombieTacticalMovementState(movement);
                agent.CurrentState = ztms;
            }
        }
Exemplo n.º 17
0
        private void ProcessAIStepHandler(object sender, UpdateStepEventArgs e)
        {
            // Check FOV, add any new foes to memory. And update existing ones. We may also have gained new memories by other means.

            // Get players and mobs in field of vision:
            List <RayCastResult> actorsInView = new List <RayCastResult>();

            ConeShape visionCone                 = new ConeShape(VisionDistance, VisionDistance);
            BipedControllerComponent bcc         = Owner.GetComponent <BipedControllerComponent>(ActorComponent.ComponentType.Control);
            RigidTransform           tipOverCone = new RigidTransform(BepuVec3.Forward * VisionDistance * 0.75f,
                                                                      BepuQuaternion.CreateFromAxisAngle(BepuVec3.Right, MathHelper.PiOver2));
            RigidTransform eyeLevelAndFacing = new RigidTransform(bcc.Controller.Body.Position - bcc.Controller.Down * bcc.Controller.Body.Height * 0.45f,
                                                                  BepuConverter.Convert(SpaceUtils.GetOrientation(BepuConverter.Convert(bcc.Controller.ViewDirection), Vector3.Up)));
            RigidTransform visionConeTransform;

            RigidTransform.Transform(ref tipOverCone, ref eyeLevelAndFacing, out visionConeTransform);
            BepuVec3           noSweep = BepuVec3.Zero;
            ViewInterestFilter filter  = new ViewInterestFilter(bcc.Controller.Body.CollisionInformation);

            GameResources.ActorManager.SimSpace.ConvexCast(visionCone, ref visionConeTransform, ref noSweep, filter.Test, actorsInView);

            for (int a = 0; a < actorsInView.Count; ++a)
            {
                // Does this actor warrant an addition to be made to our memory?
                // If so, check for LOS and recheck range. If those tests pass, modify the memory.
                EntityCollidable otherEntityCollidable = actorsInView[a].HitObject as EntityCollidable;
                // We can jump to the Id in the Tag property because we know the filter has validated this.
                int   actorId     = (int)(otherEntityCollidable.Entity.Tag);
                Actor viewedActor = GameResources.ActorManager.GetActorById(actorId);
                BipedControllerComponent viewedActorBcc = viewedActor.GetComponent <BipedControllerComponent>(ActorComponent.ComponentType.Control);
                BepuVec3 toSubject = viewedActorBcc.Controller.Body.Position - eyeLevelAndFacing.Position;

                // Check range:
                if (toSubject.LengthSquared() <= VisionDistance * VisionDistance)
                {
                    BepuRay losRay = new BepuRay(eyeLevelAndFacing.Position, toSubject);

                    RayCastResult losResult;
                    LOSFilter     losFilter = new LOSFilter(bcc.Controller.Body.CollisionInformation, otherEntityCollidable);
                    GameResources.ActorManager.SimSpace.RayCast(losRay, VisionDistance, losFilter.Test, out losResult);
                    EntityCollidable losEC = losResult.HitObject as EntityCollidable;

                    // Test for LOS:
                    if (losEC != null &&
                        losEC.Entity != null &&
                        losEC.Entity.Tag != null &&
                        (int)(losEC.Entity.Tag) == actorId)
                    {
                        // The viewed actor is either a player(foe) or a mob(ally).
                        if (GameResources.ActorManager.IsPlayer(actorId))
                        {
                            mMemory.SpotFoe(actorId);
                        }
                        else
                        {
                            IAgentStateManager agent = viewedActor.GetBehaviorThatImplementsType <IAgentStateManager>();
                            if (agent != null &&
                                agent.HasProperty(AgentPropertyName.ActiveOpponent))
                            {
                                int mobFoe = agent.GetProperty <int>(AgentPropertyName.ActiveOpponent);
                                mMemory.SenseFoe(mobFoe);
                            }
                        }
                    }
                }
            }

            // Evaluate current threats and select one to engage:
            int enemyId = mMemory.GetLargestThreat();

            if (enemyId != Actor.INVALID_ACTOR_ID)
            {
                if (mAgentProperties.ContainsKey(AgentPropertyName.ActiveOpponent))
                {
                    if ((int)(mAgentProperties[AgentPropertyName.ActiveOpponent]) != enemyId)
                    {
                        mAgentProperties[AgentPropertyName.ActiveOpponent] = enemyId;
                    }
                }
                else
                {
                    mAgentProperties.Add(AgentPropertyName.ActiveOpponent, enemyId);
                }
            }
            else
            {
                if (mAgentProperties.ContainsKey(AgentPropertyName.ActiveOpponent))
                {
                    mAgentProperties.Remove(AgentPropertyName.ActiveOpponent);
                }
            }

            TimeInState += e.GameTime.ElapsedGameTime;
            CurrentState.Update(mSteering, Owner, this);
            Vector2 locomotion = mSteering.ComputeForce(Owner);

            if (locomotion.LengthSquared() == 0.0f)
            {
                bcc.OrientationChange  = Quaternion.Identity;
                bcc.HorizontalMovement = Vector2.Zero;
            }
            else
            {
                bcc.OrientationChange  = Quaternion.CreateFromAxisAngle(Vector3.Up, (float)(Math.Atan2(-locomotion.X, locomotion.Y)));
                bcc.HorizontalMovement = locomotion.Length() * Vector2.UnitY;
            }

            mMemory.Fade(e.GameTime);
        }