private Cuboidd findSteppableCollisionbox(Cuboidd entityCollisionBox, double motionY, Vec3d walkVector) { Cuboidd stepableBox = null; for (int i = 0; i < collisionTester.CollisionBoxList.Count; i++) { Cuboidd collisionbox = collisionTester.CollisionBoxList.cuboids[i]; EnumIntersect intersect = CollisionTester.AabbIntersect(collisionbox, entityCollisionBox, walkVector); if (intersect == EnumIntersect.NoIntersect) { continue; } // Already stuck somewhere? Can't step stairs // Would get stuck vertically if I go up? Can't step up either if (intersect == EnumIntersect.Stuck || (intersect == EnumIntersect.IntersectY && motionY > 0)) { return(null); } double heightDiff = collisionbox.Y2 - entityCollisionBox.Y1; if (heightDiff <= 0) { continue; } if (heightDiff <= stepHeight) { stepableBox = collisionbox; } } return(stepableBox); }
private void OnSlowTick(float dt) { if (api.Side == EnumAppSide.Client) { return; } neibBlock = api.World.BlockAccessor.GetBlock(pos.AddCopy(fromFacing.GetOpposite())); if (neibBlock.CombustibleProps == null || neibBlock.CombustibleProps.BurnDuration <= 0) { api.World.BlockAccessor.SetBlock(0, pos); api.World.BlockAccessor.RemoveBlockEntity(pos); // Sometimes block entities don't get removed properly o.O return; } Entity[] entities = api.World.GetEntitiesAround(pos.ToVec3d().Add(0.5, 0.5, 0.5), 3, 3, (e) => e.Alive); Vec3d ownPos = pos.ToVec3d(); for (int i = 0; i < entities.Length; i++) { Entity entity = entities[i]; if (CollisionTester.AabbIntersect(entity.CollisionBox, entity.ServerPos.X, entity.ServerPos.Y, entity.ServerPos.Z, fireCuboid, ownPos)) { entity.ReceiveDamage(new DamageSource() { Source = EnumDamageSource.Block, sourceBlock = fireBlock, sourcePos = ownPos, Type = EnumDamageType.Fire }, 2f); } } }
public void CheckForCombat() { foreach (Entity enemy in enemies) { var playerRef = player.Get <Player>(); var enemyRef = enemy.Get <Enemy>(); var playerBody = player.Get <Body>(); var enemyBody = enemy.Get <Body>(); if (enemy.Has <Body>()) { if (CollisionTester.DistanceToAttack(playerBody.BoundingBox, enemyBody.BoundingBox)) { // This is the collision handler for when // Our hero hits an enemy if (enemyRef.ImmuneTimer < 1f) { enemyRef.OnCombat = true; // If player attacks if (playerRef.State == State.Combat) { var enemyHP = enemy.Get <Health>().LifePoints -= 1; enemyRef.ImmuneTimer = 3.5f; if (enemyHP < 1) { enemy.Destroy(); enemies.Remove(enemy); return; } } } // This is the collision handler for when // An enemy hits our hero if (playerRef.ImmuneTimer < 1f) { if (playerRef.State != State.Guard) { if (enemyRef.State == State.Combat) { var playerHP = player.Get <Health>().LifePoints -= 1; playerRef.ImmuneTimer = 3.5f; if (playerHP < 1) { MusicPlayer.Stop(); ScreenManager.LoadScreen(new GameOverScreen(Game), new FadeTransition(GraphicsDevice, Color.Black, 1.5f)); } } } } } else { enemyRef.OnCombat = false; } } } }
public void UpdateMotionOnly(GameTime gameTime) { float dt = (float)gameTime.ElapsedGameTime.TotalSeconds; foreach (var actor in this.GetActors()) { if (actor is DynamicActor) { var dactor = (DynamicActor)actor; var apoly = actor.GetBoundingPoly(); var proximity = actor.GetProximityOverlaps(); var potCollides = from tile in proximity from otherActor in tile.ProximityActors.CloneToList() where otherActor != actor select otherActor; var collideSet = new HashSet <Actor>(potCollides); foreach (var otherActor in collideSet) { if (CollisionTester.TestCollision(apoly, otherActor.GetBoundingPoly())) { actor.OnCollided(otherActor); if (!(otherActor is DynamicActor) || actor.CollisionClass == CollisionClass.IsolatedNoPersist) { otherActor.OnCollided(actor); //required only for IsolatedNoPersist and static actors, because the otherActor will not detect the collision. (since actor isn't persisted to tile [isolatednopersist] or doesn't check for collisions [static]) } } } if (actor.CollisionClass == CollisionClass.Normal) { var actualVel = getActualVelocity(dactor, dactor.DesiredVelocity); dactor.ActualVelocity = actualVel; var newPos = dactor.Position + actualVel * dt; var newRot = dactor.DesiredRotation; if (actualVel.LengthSquared() > 0) { MoveActor(dactor, newPos, newRot); } } else if (actor.CollisionClass == CollisionClass.IsolatedNoPersist) { dactor.ActualVelocity = dactor.DesiredVelocity; dactor.Position += dactor.ActualVelocity * dt; dactor.Rotation = dactor.DesiredRotation; } } } }
private void OnSlowServerTick(float dt) { if (!canBurn(FuelPos)) { KillFire(false); return; } Entity[] entities = Api.World.GetEntitiesAround(FirePos.ToVec3d().Add(0.5, 0.5, 0.5), 3, 3, (e) => true); Vec3d ownPos = FirePos.ToVec3d(); for (int i = 0; i < entities.Length; i++) { Entity entity = entities[i]; if (!CollisionTester.AabbIntersect(entity.SelectionBox, entity.ServerPos.X, entity.ServerPos.Y, entity.ServerPos.Z, fireCuboid, ownPos)) { continue; } if (entity.Alive) { entity.ReceiveDamage(new DamageSource() { Source = EnumDamageSource.Block, SourceBlock = fireBlock, SourcePos = ownPos, Type = EnumDamageType.Fire }, 2f); } if (Api.World.Rand.NextDouble() < 0.125) { entity.Ignite(); } } if (FuelPos != FirePos && Api.World.BlockAccessor.GetBlock(FirePos).LiquidCode == "water") { KillFire(false); return; } if (Api.World.BlockAccessor.GetRainMapHeightAt(FirePos.X, FirePos.Z) <= FirePos.Y) // It's more efficient to do this quick check before GetPrecipitation { // Die on rainfall tmpPos.Set(FirePos.X + 0.5, FirePos.Y + 0.5, FirePos.Z + 0.5); double rain = wsys.GetPrecipitation(tmpPos); if (rain > 0.15) { Api.World.PlaySoundAt(new AssetLocation("sounds/effect/extinguish"), FirePos.X + 0.5, FirePos.Y, FirePos.Z + 0.5, null, false, 16); if (rand.NextDouble() < rain / 2) { KillFire(false); return; } } } }
public void SetRally(Vector2 loc) { if (CollisionTester.TestPointInside(loc, this.polygon)) { createDefaultRally(); } else { rally = loc; } }
public override void Update(GameTime gameTime) { player.Rotate(Mouse.GetPosition(this.window), gameTime); score.Rotate(Mouse.GetPosition(this.window), gameTime); foreach (Bullet bullet in bullets) { bullet.Rotate(this); if (CollisionTester.PixelPerfectTest(player.playerSprite, bullet.bulletSprite, 200)) { if (score.CheckColors(CollisionTester.firstCollisionColor, CollisionTester.secondCollisionColor)) { menu.UpdateScoreText(score.score); if (delay >= 0.8f) delay -= 0.05f; bulletVelocity += 3; } else { delay = 3.5f; bulletVelocity = 90; } toRemove = bullet; } bullet.Move(this, bulletVelocity); } if (toRemove != null) { bullets.Remove(toRemove); toRemove = null; } if (gameTime.timeScale == 1) { if (spawnTime.ElapsedTime.AsSeconds() > delay) { bullets.Add(new Bullet(this)); spawnTime.Restart(); } } else { menu.CheckHovers(Mouse.GetPosition(this.window)); } }
private void OnSlowTick(float dt) { if (Api.Side == EnumAppSide.Client) { return; } BlockPos neibPos = Pos.AddCopy(fromFacing.Opposite); neibBlock = Api.World.BlockAccessor.GetBlock(neibPos); if (!canBurn(neibBlock, neibPos)) { Api.World.BlockAccessor.SetBlock(0, Pos); Api.World.BlockAccessor.TriggerNeighbourBlockUpdate(Pos); return; } Entity[] entities = Api.World.GetEntitiesAround(Pos.ToVec3d().Add(0.5, 0.5, 0.5), 3, 3, (e) => e.Alive); Vec3d ownPos = Pos.ToVec3d(); for (int i = 0; i < entities.Length; i++) { Entity entity = entities[i]; if (CollisionTester.AabbIntersect(entity.CollisionBox, entity.ServerPos.X, entity.ServerPos.Y, entity.ServerPos.Z, fireCuboid, ownPos)) { entity.ReceiveDamage(new DamageSource() { Source = EnumDamageSource.Block, SourceBlock = fireBlock, SourcePos = ownPos, Type = EnumDamageType.Fire }, 2f); } } if (Api.World.BlockAccessor.GetRainMapHeightAt(Pos.X, Pos.Y) <= Pos.Y) // It's more efficient to do this quick check before GetPrecipitation { // Die on rainfall tmpPos.Set(Pos.X + 0.5, Pos.Y + 0.5, Pos.Z + 0.5); double rain = wsys.GetPrecipitation(tmpPos); if (rain > 0.1) { Api.World.PlaySoundAt(new AssetLocation("sounds/effect/extinguish"), Pos.X + 0.5, Pos.Y, Pos.Z + 0.5, null, false, 16); if (rand.NextDouble() < rain / 2) { Api.World.BlockAccessor.SetBlock(0, Pos); Api.World.BlockAccessor.TriggerNeighbourBlockUpdate(Pos); return; } } } }
public virtual bool TryPutItem(IPlayer player) { if (OwnStackSize >= MaxStackSize) { return(false); } ItemSlot hotbarSlot = player.InventoryManager.ActiveHotbarSlot; if (hotbarSlot.Itemstack == null) { return(false); } ItemSlot invSlot = inventory[0]; if (invSlot.Itemstack == null) { invSlot.Itemstack = hotbarSlot.Itemstack.Clone(); invSlot.Itemstack.StackSize = 0; api.World.PlaySoundAt(SoundLocation, pos.X, pos.Y, pos.Z, null, RandomizeSoundPitch); } if (invSlot.Itemstack.Equals(api.World, hotbarSlot.Itemstack, GlobalConstants.IgnoredStackAttributes)) { int q = GameMath.Min(hotbarSlot.StackSize, TakeQuantity, MaxStackSize - OwnStackSize); invSlot.Itemstack.StackSize += q; if (player.WorldData.CurrentGameMode != EnumGameMode.Creative) { hotbarSlot.TakeOut(q); hotbarSlot.OnItemSlotModified(null); } api.World.PlaySoundAt(SoundLocation, pos.X, pos.Y, pos.Z, player, RandomizeSoundPitch); MarkDirty(); Cuboidf[] collBoxes = api.World.BlockAccessor.GetBlock(pos).GetCollisionBoxes(api.World.BlockAccessor, pos); if (collBoxes != null && collBoxes.Length > 0 && CollisionTester.AabbIntersect(collBoxes[0], pos.X, pos.Y, pos.Z, player.Entity.CollisionBox, player.Entity.LocalPos.XYZ)) { player.Entity.LocalPos.Y += collBoxes[0].Y2 - (player.Entity.LocalPos.Y - (int)player.Entity.LocalPos.Y); } (player as IClientPlayer)?.TriggerFpAnimation(EnumHandInteract.HeldItemInteract); return(true); } return(false); }
//private void UpdatePickupables(Player player) //{ // for (int i = 0; i < GameState.Pickupables.Count; i++) // { // Pickupable pickup = GameState.Pickupables[i]; // if (CollisionTester.BoundingBoxTest(player, pickup)) // { // pickup.Pickup(player); // GameState.Pickupables.RemoveAt(i); // } // } //} private void UpdatePickupables(Player player) { var iter = GameState.PickupableRep.GetIterator(); while (iter.HasNext()) { Pickupable pickup = (Pickupable)iter.Next(); if (CollisionTester.BoundingBoxTest(player, pickup)) { pickup.Pickup(player); iter.Remove(); } } }
/// <summary> /// Default constructor. /// </summary> /// <param name="title"> Level title.</param> /// <param name="game"> Game.</param> public Level(string title, SuperPlatformerGame game) { CurrentTime = 0; Gravity = 550; // Create the lists. _entities = new List <Entity>(); _pendingEntities = new List <Entity>(); _decorations = new List <MonoSprite>(); _backgroundTiles = new List <Tile>(); // Time moves on. _time = new TimedEvent(OnTimeTick, 1000); _time.Enable(); // Time to respawn _respawnTimer = new TimedEvent(OnRespawnTimerElapsed, 3000); // Wait X seconds before switching to end level scene on level finished. _endTimer = new TimedEvent(() => { game.SceneActivator.ActivateScene(new EndLevelScene(game)); }, 4000); _scale = SuperPlatformerGame.SCALE; _viewport = game.GraphicsDevice.Viewport; _title = title; _collisions = new CollisionTester(); _camera = new Camera2D(_viewport); Player = new Player(game.Content.Load <Texture2D>("Images/Player/Protagonist"), Vector2.Zero, 16, 22, game.KeyboardDevice, this, game.Content); // Listen to some player events Player.OnSizeChanged += OnPlayerSizeChange; Player.OnDied += OnPlayerDeath; Score = new ScoreCollector(); TypePlayer = PlayerType.PROTAGONIST; Display = new HUD(this, _camera, game.Content); _collidables = new List <Entity>(); _camera.Follow(Player); }
public OngoingMatchScreen(Game game) : base(game) { Translucent = false; Components.Add(Ball = new Ball(game)); Components.Add(AiPaddle = new Paddle(game, Team.Red)); Components.Add(PlayerPaddle = new Paddle(game, Team.Blue)); Components.Add(ScoreDisplay = new ScoreDisplay(game)); Components.Add(FirstServerFinder = new FirstServerFinder(Game, Ball)); Components.Add(ServeBallHandler = new ServeBallHandler(Game)); Components.Add(CollisionTester = new CollisionTester(game, Ball, new List <Paddle>() { AiPaddle, PlayerPaddle })); }
/// <summary> /// returns the tiles overlapped by this actor. non-dynamic actors use this EXACT method. /// </summary> /// <returns></returns> public virtual HashSet <Tile> GetProximityOverlaps() { var region = this.GetBoundingPoly(); HashSet <Tile> overlaps = new HashSet <Tile>(); var disk = stage.TileGrid.GetDiskCells(stage.TileGrid.ScreenToUV(region.Center), stage.TileGrid.ScreenToUVRad(region.MaxRadius) + 1); //+1 to account for regions crossing over hexes foreach (var tile in disk) { if (CollisionTester.TestCollision(region, tile.BoundingHex)) { overlaps.Add(tile); } } return(overlaps); }
private List <Cuboidd> FindSteppableCollisionboxSmooth(Cuboidd entityCollisionBox, Cuboidd entitySensorBox, double motionY, Vec3d walkVector) { var stepableBoxes = new List <Cuboidd>(); GetCollidingCollisionBox(entity.World.BlockAccessor, entitySensorBox.ToFloat(), new Vec3d(), out var blocks, true); for (int i = 0; i < blocks.Count; i++) { Cuboidd collisionbox = blocks.cuboids[i]; Block block = blocks.blocks[i]; if (!block.CanStep) { // Blocks which are low relative to this entity (e.g. small troughs are low for the player) can still be stepped on if (entity.CollisionBox.Height < 5 * block.CollisionBoxes[0].Height) { continue; } } EnumIntersect intersect = CollisionTester.AabbIntersect(collisionbox, entityCollisionBox, walkVector); //if (intersect == EnumIntersect.NoIntersect) continue; // Already stuck somewhere? Can't step stairs // Would get stuck vertically if I go up? Can't step up either if ((intersect == EnumIntersect.Stuck && !block.AllowStepWhenStuck) || (intersect == EnumIntersect.IntersectY && motionY > 0)) { return(null); } double heightDiff = collisionbox.Y2 - entityCollisionBox.Y1; //if (heightDiff <= -0.02 || !IsBoxInFront(entityCollisionBox, walkVector, collisionbox)) continue; if (heightDiff <= (entity.CollidedVertically ? 0 : -0.05)) { continue; } if (heightDiff <= stepHeight) { //if (IsBoxInFront(entityCollisionBox, walkVector, collisionbox)) { stepableBoxes.Add(collisionbox); } } } return(stepableBoxes); }
private Cuboidd findSteppableCollisionbox(Cuboidd entityCollisionBox, double motionY, Vec3d walkVector) { Cuboidd stepableBox = null; int maxCount = collisionTester.CollisionBoxList.Count; for (int i = 0; i < maxCount; i++) { Block block = collisionTester.CollisionBoxList.blocks[i]; if (!block.CanStep) { // Blocks which are low relative to this entity (e.g. small troughs are low for the player) can still be stepped on if (entity.CollisionBox.Height < 5 * block.CollisionBoxes[0].Height) { continue; } } Cuboidd collisionbox = collisionTester.CollisionBoxList.cuboids[i]; EnumIntersect intersect = CollisionTester.AabbIntersect(collisionbox, entityCollisionBox, walkVector); if (intersect == EnumIntersect.NoIntersect) { continue; } // Already stuck somewhere? Can't step stairs // Would get stuck vertically if I go up? Can't step up either if ((intersect == EnumIntersect.Stuck && !block.AllowStepWhenStuck) || (intersect == EnumIntersect.IntersectY && motionY > 0)) { return(null); } double heightDiff = collisionbox.Y2 - entityCollisionBox.Y1; if (heightDiff <= 0) { continue; } if (heightDiff <= stepHeight) { stepableBox = collisionbox; } } return(stepableBox); }
internal bool Construct(ItemSlot slot, IWorldAccessor world, BlockPos pos, IPlayer player) { Block belowBlock = world.BlockAccessor.GetBlock(pos.DownCopy()); if (!belowBlock.CanAttachBlockAt(world.BlockAccessor, this, pos.DownCopy(), BlockFacing.UP) && (belowBlock != this || FillLevel(world.BlockAccessor, pos.DownCopy()) != 8)) { return(false); } world.BlockAccessor.SetBlock(BlockId, pos); BlockEntity be = world.BlockAccessor.GetBlockEntity(pos); if (be is BlockEntityPeatPile) { BlockEntityPeatPile pile = (BlockEntityPeatPile)be; if (player.WorldData.CurrentGameMode == EnumGameMode.Creative) { pile.inventory[0].Itemstack = slot.Itemstack.Clone(); pile.inventory[0].Itemstack.StackSize = 1; } else { pile.inventory[0].Itemstack = slot.TakeOut(player.Entity.Controls.Sprint ? pile.BulkTakeQuantity : pile.DefaultTakeQuantity); } pile.MarkDirty(); world.BlockAccessor.MarkBlockDirty(pos); world.PlaySoundAt(new AssetLocation("sounds/block/dirt"), pos.X, pos.Y, pos.Z, player, false); } if (CollisionTester.AabbIntersect( GetCollisionBoxes(world.BlockAccessor, pos)[0], pos.X, pos.Y, pos.Z, player.Entity.SelectionBox, player.Entity.SidedPos.XYZ )) { player.Entity.SidedPos.Y += GetCollisionBoxes(world.BlockAccessor, pos)[0].Y2; } (player as IClientPlayer)?.TriggerFpAnimation(EnumHandInteract.HeldItemInteract); return(true); }
internal bool Construct(IItemSlot slot, IWorldAccessor world, BlockPos pos, IPlayer player) { Block belowBlock = world.BlockAccessor.GetBlock(pos.DownCopy()); if (!belowBlock.SideSolid[BlockFacing.UP.Index] && (belowBlock != this || FillLevel(world.BlockAccessor, pos.DownCopy()) != 8)) { return(false); } world.BlockAccessor.SetBlock(BlockId, pos); BlockEntity be = world.BlockAccessor.GetBlockEntity(pos); if (be is BlockEntityIngotPile) { BlockEntityIngotPile pile = (BlockEntityIngotPile)be; if (player.WorldData.CurrentGameMode == EnumGameMode.Creative) { pile.inventory.GetSlot(0).Itemstack = slot.Itemstack.Clone(); pile.inventory.GetSlot(0).Itemstack.StackSize = 1; } else { pile.inventory.GetSlot(0).Itemstack = slot.TakeOut(1); } pile.MarkDirty(); world.BlockAccessor.MarkBlockDirty(pos); world.PlaySoundAt(new AssetLocation("sounds/block/ingot"), pos.X, pos.Y, pos.Z, player, false); } if (CollisionTester.AabbIntersect( GetCollisionBoxes(world.BlockAccessor, pos)[0], pos.X, pos.Y, pos.Z, player.Entity.CollisionBox, player.Entity.LocalPos.XYZ )) { player.Entity.LocalPos.Y += GetCollisionBoxes(world.BlockAccessor, pos)[0].Y2; } return(true); }
private void SlowEnemiesInRange() { var center = Transform.Transform(new Point(Width / 2, Height / 2)); Collider = new CirlceCollider(this, Transform, center, slowRadius); if (CollisionTester.Collision(this)) { foreach (var obj in CollisionTester.CollidingObjects) { Enemy enemy = obj as Enemy; if (enemy != null) { enemy.Slow(slowDurationMilliseconds, slowRate); } } } }
public IEnumerable <Actor> QueryPoint(Vector2 point) { RectPoly pRect = new RectPoly(point, 0, 0, 0); var tile = TileGrid[TileGrid.ScreenToUV(point)]; var potCollides = tile.ProximityActors.CloneToList(); var collideSet = new HashSet <Actor>(potCollides); foreach (var actor in collideSet) { if (CollisionTester.TestPointInside(point, actor.GetBoundingPoly())) { yield return(actor); } } }
private void DamageEnemiesInRange() { var centerOfExplosion = CollisionTester.CollidingObject.Collider.Center; Collider = new CirlceCollider(this, Transform, centerOfExplosion, explosionRadius); if (CollisionTester.Collision(this)) { foreach (var obj in CollisionTester.CollidingObjects) { Enemy enemy = obj as Enemy; if (enemy != null) { enemy.Damage(Damage, this); } } } }
public bool CheckMovementCollision(float xOffset, float yOffset, List <Obstacle> obstacles) { foreach (Obstacle obstacle in obstacles) { // kinda works Translate(xOffset, yOffset); if (CollisionTester.TileBoundingBoxTest(this, obstacle)) { Translate(-xOffset, -yOffset); return(true); } else { Translate(-xOffset, -yOffset); } } return(false); }
/// <summary> /// returns all actors contained within region. warning: does not detect IsolatedNoPersist types /// </summary> /// <param name="region"></param> /// <returns></returns> public IEnumerable <Actor> Query(IPolygon region) { var disk = TileGrid.GetDiskCells(TileGrid.ScreenToUV(region.Center), TileGrid.ScreenToUVRad(region.MaxRadius) + 1); //+1 to account for regions crossing over hexes var potCollides = from tile in disk from actor in tile.ProximityActors.CloneToList() select actor; var collideSet = new HashSet <Actor>(potCollides); foreach (var actor in collideSet) { if (CollisionTester.TestCollision(actor.GetBoundingPoly(), region)) { yield return(actor); } } }
public bool CreateStorage(IWorldAccessor world, BlockSelection blockSel, IPlayer player) { BlockPos pos; if (blockSel.Face == null) { pos = blockSel.Position; } else { pos = blockSel.Position.AddCopy(blockSel.Face); } Block belowBlock = world.BlockAccessor.GetBlock(pos.DownCopy()); if (!belowBlock.CanAttachBlockAt(world.BlockAccessor, this, pos.DownCopy(), BlockFacing.UP) && (belowBlock != this || FillLevel(world.BlockAccessor, pos.DownCopy()) != 1)) { return(false); } world.BlockAccessor.SetBlock(BlockId, pos); BlockEntity be = world.BlockAccessor.GetBlockEntity(pos); if (be is BlockEntityGroundStorage beg) { beg.OnPlayerInteractStart(player, blockSel); beg.MarkDirty(true); } if (CollisionTester.AabbIntersect( GetCollisionBoxes(world.BlockAccessor, pos)[0], pos.X, pos.Y, pos.Z, player.Entity.SelectionBox, player.Entity.SidedPos.XYZ )) { player.Entity.SidedPos.Y += GetCollisionBoxes(world.BlockAccessor, pos)[0].Y2; } (player as IClientPlayer)?.TriggerFpAnimation(EnumHandInteract.HeldItemInteract); return(true); }
public bool ForceSpawnObject(Sprite objectSprite) { bool objectSpawned = false; while (!objectSpawned) { objectSpawned = true; //destrObj.Position = new Vector2f(64 * Rnd.Next(60), 64 * Rnd.Next(45)); objectSprite.Position = new Vector2f(GameState.Random.Next(GameState.TileMap.Length * 64), GameState.Random.Next(GameState.TileMap.Width * 64)); foreach (Sprite collidable in GameState.Collidables.ToList()) { if (CollisionTester.BoundingBoxTest(collidable, objectSprite)) { objectSpawned = false; break; } } } return(objectSpawned); }
public virtual void Update() { if (!isFired) { MoveToPoint(new Point(FiringWeapon.ProjectileSpawnPoint.X, FiringWeapon.ProjectileSpawnPoint.Y - Height)); SetProjectile(); isFired = true; } else { MoveTowards(targetDirection, Speed * MoverDeltaTime); if (CollisionTester.Collision(this)) { Collided = true; } else if (OutSideOfGame()) { Destroy(); } } }
private void SpawnPortal(PortalProspect portal, Caretaker m1, Caretaker m2) { //defaultLogger.LogMessage(3, CollisionTester.BoundingBoxTest(MainPlayer, portal).ToString()); //defaultLogger.LogMessage(4, MainPlayer.Position.ToString()); //defaultLogger.LogMessage(4, portal.Position.ToString()); if (isMementoSet && (CollisionTester.BoundingBoxTest(MainPlayer, portal) || Keyboard.IsKeyPressed(Keyboard.Key.Num9))) { portal.RestoreMemento(m2.Memento); MainPlayer.Position = new Vector2f(16 * 64f, 16 * 64f); isMementoSet = false; OurLogger.Log("200; 200"); } else if (!isMementoSet && (CollisionTester.BoundingBoxTest(MainPlayer, portal) || Keyboard.IsKeyPressed(Keyboard.Key.Num0))) { portal.RestoreMemento(m1.Memento); MainPlayer.Position = new Vector2f(16 * 64f, 16 * 64f); OurLogger.Log("400; 400"); isMementoSet = true; } }
private ModelStateWriter generateNewObject(RosSharp.RosBridgeClient.MessageTypes.Gazebo.ModelState modelstate) { RosSharp.RosBridgeClient.MessageTypes.Geometry.Pose pose = modelstate.pose; Twist twist = modelstate.twist; string name = modelstate.model_name; GameObject ado = Instantiate(generatedCubePrefab); generatedObjects.Add(ado); ado.name = name; ado.transform.SetParent(genCubeParentTransform, true); ModelStateWriter modelStateWriter = ado.AddComponent <ModelStateWriter>(); CollisionTester collisionTester = ado.AddComponent <CollisionTester>(); collisionTester.currentExecuter = this.currentExecutor; collisionTester.sucker = this.LoaderSucker; suctionCupStatusSubscriber.collisionTesters.Add(collisionTester); BoxCollider boxCollider = ado.GetComponent <BoxCollider>(); boxCollider.isTrigger = true; foreach (UnityEngine.Transform child in ado.transform) { if (child.name.Contains("ROSCoords")) { child.localPosition = new UnityEngine.Vector3((float)pose.position.x, (float)pose.position.y, (float)pose.position.z); child.localPosition = child.localPosition * 1000f; ado.transform.localPosition = coordinateTargetSelector.transformVectorRos2UnityLocal(child.localPosition); modelStateWriter.rosTransform = child; } } modelStateWriter.targetTransform = ado.transform; modelStateWriter.updateTransform = true; modelStateWriter.coordinateTargetSelector = this.coordinateTargetSelector; coordinateTargetSelector.addOnClickHandlerAndBoundingBoxes(name); return(modelStateWriter); }
/// <summary> /// calls collideCallback on the first colliding actor to pass the filter /// </summary> /// <param name="source"></param> /// <param name="targ"></param> /// <param name="filter"></param> /// <param name="collideCallback"></param> /// <returns></returns> public bool TestLOS(Vector2 source, Vector2 targ, Func <Actor, bool> filter, Action <Actor> collideCallback) { float incr = 0.10f; Point prevUV = TileGrid.ScreenToUV(source); IEnumerable <Actor> potCollides = TileGrid[prevUV].ProximityActors.CloneToList(); float len = (targ - source).Length(); Vector2 dir = Vector2.Normalize(targ - source); for (float dist = 0; dist < len; dist += incr) { Vector2 testPt = source + dist * dir; var tUV = TileGrid.ScreenToUV(testPt); if (TileGrid.IsValidUV(tUV)) { if (tUV != prevUV) { potCollides = TileGrid[tUV].ProximityActors.CloneToList(); prevUV = tUV; } var col = potCollides.FirstOrDefault(a => filter(a) && CollisionTester.TestPointInside(testPt, a.GetBoundingPoly())); if (col != null) { collideCallback(col); return(false); } } } return(true); }
/// <summary> /// checks if an actor is colliding with any other actors (checks the tiles in the actor's tile overlaps) /// </summary> /// <param name="actor"></param> /// <returns></returns> public bool IsColliding(Actor actor) { actor.stage = this; var actorBounds = actor.GetBoundingPoly(); var proximity = actor.GetProximityOverlaps(); var potCollides = from tile in proximity from otherActor in tile.ProximityActors where otherActor != actor select otherActor; var collideSet = new HashSet <Actor>(potCollides); foreach (Actor tileActor in collideSet) { if (CollisionTester.TestCollision(actorBounds, tileActor.GetBoundingPoly())) { return(true); } } return(false); }
public virtual bool TryPutItem(IPlayer player) { if (TotalStackSize >= Capacity) { return(false); } ItemSlot hotbarSlot = player.InventoryManager.ActiveHotbarSlot; if (hotbarSlot.Itemstack == null) { return(false); } ItemSlot invSlot = inventory[0]; if (invSlot.Empty) { if (hotbarSlot.TryPutInto(Api.World, invSlot, 1) > 0) { Api.World.PlaySoundAt(StorageProps.PlaceRemoveSound, Pos.X, Pos.Y, Pos.Z, player, 0.88f + (float)Api.World.Rand.NextDouble() * 0.24f, 16); } return(true); } if (invSlot.Itemstack.Equals(Api.World, hotbarSlot.Itemstack, GlobalConstants.IgnoredStackAttributes)) { bool putBulk = player.Entity.Controls.Sprint; int q = GameMath.Min(hotbarSlot.StackSize, putBulk ? BulkTransferQuantity : TransferQuantity, Capacity - TotalStackSize); // add to the pile and average item temperatures int oldSize = invSlot.Itemstack.StackSize; invSlot.Itemstack.StackSize += q; if (oldSize + q > 0) { float tempPile = invSlot.Itemstack.Collectible.GetTemperature(Api.World, invSlot.Itemstack); float tempAdded = hotbarSlot.Itemstack.Collectible.GetTemperature(Api.World, hotbarSlot.Itemstack); invSlot.Itemstack.Collectible.SetTemperature(Api.World, invSlot.Itemstack, (tempPile * oldSize + tempAdded * q) / (oldSize + q), false); } if (player.WorldData.CurrentGameMode != EnumGameMode.Creative) { hotbarSlot.TakeOut(q); hotbarSlot.OnItemSlotModified(null); } Api.World.PlaySoundAt(StorageProps.PlaceRemoveSound, Pos.X, Pos.Y, Pos.Z, player, 0.88f + (float)Api.World.Rand.NextDouble() * 0.24f, 16); MarkDirty(); Cuboidf[] collBoxes = Api.World.BlockAccessor.GetBlock(Pos).GetCollisionBoxes(Api.World.BlockAccessor, Pos); if (collBoxes != null && collBoxes.Length > 0 && CollisionTester.AabbIntersect(collBoxes[0], Pos.X, Pos.Y, Pos.Z, player.Entity.SelectionBox, player.Entity.SidedPos.XYZ)) { player.Entity.SidedPos.Y += collBoxes[0].Y2 - (player.Entity.SidedPos.Y - (int)player.Entity.SidedPos.Y); } (player as IClientPlayer)?.TriggerFpAnimation(EnumHandInteract.HeldItemInteract); return(true); } return(false); }