public new void Setup()
 {
     base.Setup();
     collisionService  = new CollisionService(EngineConfigFake, WorldStateService, VectorCalculatorService);
     collisionHandlers = new List <ICollisionHandler>
     {
         new FoodCollisionHandler(WorldStateService, EngineConfigFake),
         new PlayerCollisionHandler(WorldStateService, collisionService, EngineConfigFake, VectorCalculatorService)
     };
     collisionHandlerResolver = new CollisionHandlerResolver(collisionHandlers);
     actionHandlers           = new List <IActionHandler>
     {
         new ForwardActionHandler(),
         new StartAfterburnerActionHandler(WorldStateService, EngineConfigFake),
         new StopAfterburnerActionHandler(WorldStateService),
         new StopActionHandler()
     };
     actionHandlerResolver = new ActionHandlerResolver(actionHandlers);
     actionService         = new ActionService(WorldStateService, actionHandlerResolver);
     tickProcessingService = new TickProcessingService(
         collisionHandlerResolver,
         VectorCalculatorService,
         WorldStateService,
         collisionService);
     engineService = new EngineService(WorldStateService, actionService, EngineConfigFake, tickProcessingService);
 }
        public void Update()
        {
            foreach (RadioButton button in buttons)
            {
                if (CollisionService.CheckMouseCollision(button))
                {
                    button.isBeingMousedOver = true;
                }
                else
                {
                    button.isBeingMousedOver = false;
                }

                // If we select this button, set isSelected to true for this button, but false for all other buttons in this button group.
                if (button.isBeingMousedOver && GlobalParameters.GlobalMouse.LeftClickHold())
                {
                    button.isSelected = true;
                    foreach (RadioButton otherButton in buttons)
                    {
                        if (!otherButton.Equals(button))
                        {
                            otherButton.isSelected = false;
                        }
                    }
                }
                button.Update();
            }
        }
Esempio n. 3
0
        protected override async ValueTask Init()
        {
            this.AddService(new InputService());

            var collisionService = new CollisionService(this, new Size(64, 64));

            this.AddService(collisionService);

            var sceneGraph = new SceneGraph(this);

            this.AddService(sceneGraph);

            var player = BuildPlayer();

            sceneGraph.Root.AddChild(player);

            for (var i = 0; i != 6; ++i)
            {
                AddAsteroid(sceneGraph);
            }

            var context = await _canvas.CreateCanvas2DAsync();

            var renderService = new RenderService(this, context);

            this.AddService(renderService);
        }
        public void No_Objects_Should_Not_Collide()
        {
            var space            = new Space3D();
            var collisionService = new CollisionService();
            var result           = collisionService.Collide(space);

            Assert.False(result.IsCollision);
        }
        public void One_Object_Should_Not_Collide()
        {
            var space = new Space3D();

            space.AddShape(new Cube(2), new Position3D(1, 2, 3));
            var collisionService = new CollisionService();
            var result           = collisionService.Collide(space);

            Assert.False(result.IsCollision);
            Assert.Equal(0, result.CollisionVolume);
        }
Esempio n. 6
0
 public override void Update()
 {
     if (CollisionService.CheckMouseCollision(this))
     {
         isBeingMousedOver = true;
     }
     else
     {
         isBeingMousedOver = false;
     }
 }
        protected override async ValueTask Init()
        {
            var collisionService = new CollisionService(this, new Size(64, 64));

            this.AddService(collisionService);

            var playScene = new Scenes.PlayScene(this, _assetsResolver, collisionService);

            this.SceneManager.AddScene(SceneNames.Play, playScene);

            await this.SceneManager.SetCurrentScene(SceneNames.Play);
        }
Esempio n. 8
0
        protected override async ValueTask Init()
        {
            this.AddService(new InputService());

            var collisionService = new CollisionService(this, new Size(64, 64));

            this.AddService(collisionService);

            this.SceneManager.AddScene(SceneNames.Welcome, new Scenes.WelcomeScene(this, _assetsResolver));
            this.SceneManager.AddScene(SceneNames.Play, new Scenes.PlayScene(this, _assetsResolver));

            await this.SceneManager.SetCurrentScene(SceneNames.Welcome);
        }
Esempio n. 9
0
        void Start()
        {
            if (player == null)
            {
                throw new MissingComponentException("Missing Player component");
            }
            if (blockParticle == null)
            {
                throw new MissingComponentException("Missing Block Particle component");
            }
            if (chunkMeshPrefab == null)
            {
                throw new MissingComponentException("Missing Chunk Mesh component");
            }
            if (solidBlockMaterial == null)
            {
                throw new MissingComponentException("Missing Solid Block Material component");
            }
            if (transparentBlockMaterial == null)
            {
                throw new MissingComponentException("Missing Transparent Block Material component");
            }
            if (waterBlockMaterial == null)
            {
                throw new MissingComponentException("Missing Water Block Material component");
            }

            Vector3 playerStartPosition;

            playerStartPosition.x = 64.5f;
            playerStartPosition.y = 148;
            playerStartPosition.z = 64.5f;
            Instantiate(player, playerStartPosition, Quaternion.identity);

            instance = this;
            BlockDefinition.InitializeAllTypes();
            AsyncService.Initialize();
            ChunkRepository.Initialize();
            CollisionService.Initialize();
            GeneratorService.Initialize();
            RenderService.Initialize();

            SetSeed(UnityEngine.Random.Range(Int32.MinValue + 1, Int32.MaxValue - 1));

            fogDistance = 0.0f;

            AsyncService.Load();

            // Remove the next line if you want your game to stop processing when it loses focus
            Application.runInBackground = true;
        }
        protected override ValueTask Init(GameContext game)
        {
            _inputService     = game.GetService <InputService>();
            _collisionService = game.GetService <CollisionService>();

            _transform = this.Owner.Components.Get <TransformComponent>();
            _renderer  = this.Owner.Components.Get <SpriteRenderComponent>();

            var map = game.SceneManager.Current.FindGameObjectByName(ObjectNames.Map);

            _mapRenderer = map.Components.Get <MapRenderComponent>();

            return(base.Init(game));
        }
 public new void Setup()
 {
     base.Setup();
     collisionService  = new CollisionService(EngineConfigFake, WorldStateService, VectorCalculatorService);
     collisionHandlers = new List <ICollisionHandler>
     {
         new FoodCollisionHandler(WorldStateService, EngineConfigFake),
         new PlayerCollisionHandler(WorldStateService, collisionService, EngineConfigFake, VectorCalculatorService)
     };
     collisionHandlerResolver    = new CollisionHandlerResolver(collisionHandlers);
     vectorCalculatorServiceMock = new Mock <IVectorCalculatorService>();
     tickProcessingService       = new TickProcessingService(
         collisionHandlerResolver,
         VectorCalculatorService,
         WorldStateService,
         collisionService);
 }
        public MainViewModel(GlobalSimulationParameters simulationParams, MovementService movement, Logger logger, CollisionService collisions, InteractionService interactService, EnvironmentService environment)
        {
            SimulationParams = simulationParams;
            Environment      = environment;
            _movement        = movement;
            _logger          = logger;
            _collisions      = collisions;
            _interactService = interactService;
            SimulationParams.PropertyChanged += SimulationParamsOnPropertyChanged;

            GenerateCommand  = new RelayCommand(ExecuteGenerate);
            StartMoveCommand = new RelayCommand(ExecuteStartMove);
            StopMoveCommand  = new RelayCommand(ExecuteStopMove);

            Entities = new List <Entity.Entity>();
            Logs     = new ObservableCollection <string>();

            _logger.RegisterListener(InternalLog);

            GenerateRng();
        }
Esempio n. 13
0
        private Spawner BuildBulletSpawner(CollisionService collisionService)
        {
            var spriteSheet = _assetsResolver.Get <SpriteSheet>("assets/sheet.json");

            var spawner = new Spawner(() =>
            {
                var bullet = new GameObject();
                bullet.Components.Add <TransformComponent>();

                var bulletSpriteRenderer        = bullet.Components.Add <SpriteRenderComponent>();
                bulletSpriteRenderer.Sprite     = spriteSheet.Get("fire01.png");
                bulletSpriteRenderer.LayerIndex = (int)RenderLayers.Items;

                var bulletBBox = bullet.Components.Add <BoundingBoxComponent>();
                bulletBBox.SetSize(bulletSpriteRenderer.Sprite.Bounds.Size);

                var speed = 7000f;

                var bulletRigidBody      = bullet.Components.Add <MovingBody>();
                bulletRigidBody.MaxSpeed = speed;

                var brain     = bullet.Components.Add <BulletBrain>();
                brain.Speed   = speed;
                brain.Display = this.Game.Display;

                collisionService.Add(bulletBBox);

                return(bullet);
            }, bullet =>
            {
                bullet.Components.Get <MovingBody>().Reset();

                bullet.Components.Get <TransformComponent>().Local.Reset();
                bullet.Components.Get <TransformComponent>().World.Reset();
            });

            spawner.Components.Add <TransformComponent>();

            return(spawner);
        }
Esempio n. 14
0
        public void LoadLevel(string levelName)
        {
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data\\" + levelName + ".json");

            CurrentLevel = Level.Load(new FileInfo(path));

            var players = CurrentLevel.Entities.Where(e => e is Player);

            _playerLayer.Entities.AddRange(players);

            _layers.InsertRange(0, CurrentLevel.MapLayers);

#if DEBUG
            _layers.Add(CurrentLevel.CollisionLayer);
#endif

            // replace the collision service with one setup for this level
            var collisionMap     = new CollisionMap(CurrentLevel);
            var collisionService = new CollisionService(collisionMap);

            ServiceLocator.Add <ICollisionService>(collisionService);
        }
Esempio n. 15
0
        private void InitSceneGraph(CollisionService collisionService)
        {
            _explosionsSpawner = BuildExplosionsSpawner();
            this.Root.AddChild(_explosionsSpawner);

            _asteroidsSpawner = BuildAsteroidsSpawner(collisionService);
            this.Root.AddChild(_asteroidsSpawner);

            var bulletSpawner = BuildBulletSpawner(collisionService);

            this.Root.AddChild(bulletSpawner);

            _player = BuildPlayer(bulletSpawner);
            this.Root.AddChild(_player);

            var ui = BuidUI(bulletSpawner, _player);

            this.Root.AddChild(ui);

            var background = BuildBackground();

            this.Root.AddChild(background);
        }
Esempio n. 16
0
    void Update()
    {
        ironVoxel.Domain.Block hitBlock;
        Vector3 hitBlockLocation;
        Vector3 hitBlockNormal;
        bool    hit;
        Vector3 checkPosition = transform.position + collisionCheckOffset;

        hit = CollisionService.RaytraceCollision(checkPosition, Vector3.down, gravity.magnitude + radius, false,
                                                 out hitBlock, out hitBlockLocation, out hitBlockNormal);
        if (!hit)
        {
            velocity += gravity;
        }
        else
        {
            Vector3 position;
            position.x = transform.position.x;
            position.z = transform.position.z;

            position.y         = hitBlockLocation.y - collisionCheckOffset.y + radius;
            transform.position = position;
        }

        if (velocity.magnitude > 0.0001f)
        {
            hit = CollisionService.RaytraceCollision(checkPosition, velocity.normalized, velocity.magnitude + radius, false,
                                                     out hitBlock, out hitBlockLocation, out hitBlockNormal);

            if (hit)
            {
                velocity = Vector3.Reflect(velocity, hitBlockNormal) * restitution;
            }
        }

        transform.position = transform.position + velocity;
    }
Esempio n. 17
0
    public static void TickBullets(World model)
    {
        foreach (var bullet in model.bullets.Values)
        {
            bullet.dir += model.wind;
            bullet.pos += bullet.dir * bullet.speed;

            UnityEngine.Camera  cam = UnityEngine.Camera.main;
            UnityEngine.Vector2 bulletViewportPos = cam.WorldToViewportPoint(bullet.pos.Vector3());
            UnityEngine.Vector3 bulletWorldPos    = bullet.pos.Vector3();

            if (bulletViewportPos.x < 0 || bulletViewportPos.x > 1)
            {
                bullet.dir = new Position(-bullet.dir.x, bullet.dir.y).Normalize();
                bullet.pos = new Position(
                    cam.ViewportToWorldPoint(
                        new UnityEngine.Vector2(UnityEngine.Mathf.Clamp01(bulletViewportPos.x), bulletViewportPos.y)
                        )
                    );
                bullet.ricochetLifeHits--;

                AudioController.Instance.PlaySound(AudioController.Sound.Ricoshet);
            }
            if (bulletViewportPos.y < 0 || bulletViewportPos.y > 1)
            {
                bullet.dir = new Position(bullet.dir.x, -bullet.dir.y).Normalize();
                bullet.pos = new Position(
                    cam.ViewportToWorldPoint(
                        new UnityEngine.Vector2(bulletViewportPos.x, UnityEngine.Mathf.Clamp01(bulletViewportPos.y))
                        )
                    );
                bullet.ricochetLifeHits--;
                AudioController.Instance.PlaySound(AudioController.Sound.Ricoshet);
            }

            foreach (var bandit in model.bandits.Values)
            {
                Circle bulletCircle = CollisionService.CreateCircle(bullet.pos, bullet.dir * bullet.radius, bullet.radius);
                Circle banditCircle = CollisionService.CreateCircle(bandit.pos, new Position(), bandit.radius);

                Position hitPoint;
                if (CollisionService.DynamicToStaticCircleCollision(bulletCircle, banditCircle, out hitPoint))
                {
                    model.gizmos.Add(hitPoint);

                    Position delta  = hitPoint - bandit.pos;
                    Position normal = delta.Normalize();

                    Position pushDir = (bullet.dir * 0.5f + normal * 0.75f).Normalize();


                    bullet.pos = hitPoint;
                    bullet.dir = pushDir;
                    bullet.ricochetLifeHits--;
                    bullet.hits++;

                    bandit.pos += pushDir * -2f;
                    bandit.hp--;

                    if (bandit.hp <= 0)
                    {
                        bandit.isActive = false;
                    }
                    else if (bandit.hp > 0)
                    {
                        model.events.Enqueue(new BanditDamagedEvent(bandit.id));
                    }
                }
            }

            if (bullet.ricochetLifeHits <= 0)
            {
                bullet.isActive = false;
            }
        }
    }
 public CollisionServiceTests()
 {
     _collisionService = new CollisionService();
 }
Esempio n. 19
0
 public PlayScene(GameContext game, IAssetsResolver assetsResolver, CollisionService collisionService) : base(game)
 {
     _assetsResolver   = assetsResolver;
     _collisionService = collisionService;
 }
Esempio n. 20
0
        private Spawner BuildAsteroidsSpawner(CollisionService collisionService)
        {
            var spriteNames = new[]
            {
                "meteorBrown_big1.png",
                "meteorBrown_big2.png",
                "meteorBrown_big3.png",
                "meteorBrown_big4.png",
                "meteorGrey_big1.png",
                "meteorGrey_big2.png",
                "meteorGrey_big3.png",
                "meteorGrey_big4.png",
            };
            int spriteIndex = 0;

            var spriteSheet = _assetsResolver.Get <SpriteSheet>("assets/sheet.json");

            var spawner = new Spawner(() =>
            {
                var asteroid = new GameObject();

                var transform = asteroid.Components.Add <TransformComponent>();

                var spriteRenderer        = asteroid.Components.Add <SpriteRenderComponent>();
                var sprite                = spriteSheet.Get(spriteNames[spriteIndex]);
                spriteIndex               = spriteIndex + 1 % spriteNames.Length;
                spriteRenderer.Sprite     = sprite;
                spriteRenderer.LayerIndex = (int)RenderLayers.Enemies;

                var bbox = asteroid.Components.Add <BoundingBoxComponent>();
                bbox.SetSize(sprite.Bounds.Size);
                collisionService.Add(bbox);

                var brain      = asteroid.Components.Add <AsteroidBrain>();
                brain.Display  = this.Game.Display;
                brain.OnDeath += o =>
                {
                    _killedAsteroids++;
                    _gameStats.IncreaseScore();

                    var explosion          = _explosionsSpawner.Spawn();
                    var explosionTransform = explosion.Components.Get <TransformComponent>();
                    explosionTransform.Local.Clone(transform.Local);
                    explosionTransform.World.Clone(transform.Local);
                };

                return(asteroid);
            }, asteroid =>
            {
                var transform = asteroid.Components.Get <TransformComponent>();

                transform.World.Reset();
                transform.Local.Reset();

                transform.Local.Position.X = MathUtils.Random.NextBool() ? 0 : this.Game.Display.Size.Width;
                transform.Local.Position.Y = MathUtils.Random.NextBool() ? 0 : this.Game.Display.Size.Height;

                var brain       = asteroid.Components.Get <AsteroidBrain>();
                var dir         = _player.Components.Get <TransformComponent>().Local.Position - transform.Local.Position;
                brain.Direction = Vector2.Normalize(dir);
                brain.Speed     = (float)MathUtils.Random.NextDouble(0.15, 0.5);

                //var w = (double)this.Game.Display.Size.Width;
                //var rx = MathUtils.Random.NextDouble(0, .4, .6, 1);
                //var tx = MathUtils.Normalize(rx, 0, 1, -1, 1);
                //transform.Local.Position.X = (float)(tx * w / 2.5 + w / 2);

                //var h = (double)this.Game.Display.Size.Height;
                //var ry = MathUtils.Random.NextDouble(0, .35, .65, 1);
                //var ty = MathUtils.Normalize(ry, 0, 1, -1, 1);
                //transform.Local.Position.Y = (float)(ty * h / 2.5 + h / 2);
            });

            spawner.Components.Add <TransformComponent>();

            return(spawner);
        }