public TestBattleZone(int width, int height) { zoneNumber = -3; this.width = width; this.height = height; setDrawLocation(new Vector2(0, 0)); createLists(); level1 = new CollisionMap(height, width); collisionMap.Add(level1); level1Trans = new TransitionMap(height, width); transitionMap.Add(level1Trans); level1TrafficMap = new TrafficMap(height, width); trafficMap.Add(level1TrafficMap); level1EnemyMap = new EnemyMap(height, width); enemyMap.Add(level1EnemyMap); fillLevel1(); fillLevel1Trans(); createSpawners(); }
void SetMode(string modeName) { if (objectInfo.draw) { int newMode = System.Array.IndexOf(COF.ModeNames[2], modeName); if (newMode == -1 || !objectInfo.mode[newMode]) { Debug.LogWarning("Failed to set mode '" + modeName + "' of object " + name); return; } if (objectInfo.hasCollision[mode]) { CollisionMap.SetPassable(Iso.Snap(iso.pos), objectInfo.sizeX, objectInfo.sizeY, true, gameObject); } mode = newMode; var cof = COF.Load(@"data\global\objects", objectInfo.token, "HTH", modeName); animator.shadow = objectInfo.blocksLight[mode]; animator.cof = cof; animator.loop = objectInfo.cycleAnim[mode]; animator.SetFrameRange(objectInfo.start[mode], objectInfo.frameCount[mode]); animator.frameDuration = objectInfo.frameDuration[mode]; if (objectInfo.hasCollision[mode]) { CollisionMap.SetPassable(Iso.Snap(iso.pos), objectInfo.sizeX, objectInfo.sizeY, false, gameObject); } } }
private void ClearCollisionMaps() { GameObject.Find("CollisionMap").GetComponent <Tilemap>().ClearAllTiles(); GameObject.Find("PitCollisionMap").GetComponent <Tilemap>().ClearAllTiles(); CollisionMap = new int[CollisionMap.GetLength(0), CollisionMap.GetLength(1)]; }
public void SpawnCops(RandomDungeon dungeon, CollisionMap collisionMap, Vector2 avatarStartPosition) { List <Vector2Int> walkablePositions = collisionMap.EmptyPositions(); walkablePositions.RemoveAll((pos) => VectorHelper.OrthogonalDistance(pos, avatarStartPosition) < 10); // Spawn a few cops in the level int numCops = Random.Range(3, 6); for (int i = 0; i < numCops; ++i) { if (walkablePositions.Count == 0) { return; } string enemy = (Random.Range(0, 2) == 0 ? "CopRanged" : "CopMelee"); GameObject newEnemy = GameObject.Instantiate(PrefabManager.instance.PrefabByName(enemy)); Vector2Int pos2 = walkablePositions[Random.Range(0, walkablePositions.Count)]; walkablePositions.Remove(pos2); Vector3 pos = MapCoordinateHelper.MapToWorldCoords(pos2); newEnemy.transform.position = pos; collisionMap.MarkSpace(pos2.x, pos2.y, newEnemy.GetComponent <SimpleMovement>().uniqueCollisionIdentity); } }
public override void Tick(RealmTime time) { //start of changes (CondEffects in ItemData) //if (!CondChecked) //{ // if (ProjectileOwner is Player && SlotId != -1) // { // var inv = (ProjectileOwner as Player).Inventory; // if (inv[SlotId] != null) // { // if (inv.Data[SlotId] != null && inv.Data[SlotId].CondChance != 0 && inv.Data[SlotId].CondEffect != -1) // { // CondChance = inv.Data[SlotId].CondChance; // CondEffect = inv.Data[SlotId].CondEffect; // CondChecked = true; // } // else // { // CondChecked = true; // } // } // else // { // CondChecked = true; // } // } // else // { // CondChecked = true; // } //} //end of changes (CondEffects in ItemData) if (collisionMap == null) { collisionMap = ProjectileOwner is Player ? Owner.EnemiesCollision : Owner.PlayersCollision; } long elapsedTicks = time.TotalElapsedMs - BeginTime; if (elapsedTicks > Descriptor.LifetimeMS) { Destroy(true); return; } long counter = time.ElaspedMsDelta; while (counter > Manager.Logic.MsPT && TickCore(elapsedTicks - counter, time)) { counter -= Manager.Logic.MsPT; } if (Owner != null) { TickCore(elapsedTicks, time); } base.Tick(time); }
protected override void Start() { base.Start(); CollisionMap.Move(iso.pos, iso.pos, size, gameObject); Events.InvokeUnitInitialized(this); UpdateMode(); }
public void UpdateCollisionMapDebug(bool walls) { Tilemap debug = walls ? GameObject.Find("CollisionMap").GetComponent <Tilemap>() : GameObject.Find("PitCollisionMap").GetComponent <Tilemap>(); //Tilemap debug = GameObject.Find("CollisionMap").GetComponent<Tilemap>(); debug.ClearAllTiles(); for (int i = 0; i < CollisionMap.GetLength(0); i++) { for (int j = 0; j < CollisionMap.GetLength(1); j++) { int collisionIndex = CollisionMap[i, j]; if (walls && collisionIndex == 1) { debug.SetTile(new Vector3Int(Bounds.xMin + i, Bounds.yMin + j, 0), MapManager.Instance.selectedDungeonData.tileSet.FloorTiles.ElementAt(0).value); } else if (!walls && collisionIndex == 2) { Vector3Int pos = new Vector3Int(Bounds.xMin + i, Bounds.yMin + j, 0); debug.SetTile(pos, _pits.GetTile(pos)); //FloorTiles[0]); } } } }
private static void ApplyTileCollisions(DT1.Tile tile, int x, int y) { var pos = Iso.MapTileToWorld(x, y); var collisionMapOffset = Iso.Snap(Iso.MapToIso(pos)); int flagIndex = 0; DT1.BlockFlags mask = DT1.BlockFlags.Walk | DT1.BlockFlags.PlayerWalk; for (int dy = 2; dy > -3; --dy) { for (int dx = -2; dx < 3; ++dx, ++flagIndex) { Vector2i subCellPos = collisionMapOffset + new Vector2i(dx, dy); bool passable = (tile.flags[flagIndex] & mask) == 0; CollisionLayers blockedLayers = passable ? CollisionLayers.None : CollisionLayers.Walk; if (tile.orientation == 0) { CollisionMap.SetBlocked(subCellPos, blockedLayers); } else if (CollisionMap.Passable(subCellPos, CollisionLayers.Walk) && !passable) { CollisionMap.SetBlocked(subCellPos, blockedLayers); } } } }
private void Start() { mProjectileThrower = GetComponentInChildren <ProjectileThrower>(); mSimpleMovement = GetComponent <SimpleMovement>(); mCollisionMap = GameObject.FindObjectOfType <CollisionMap>(); mTeleport = GetComponent <EnemyTeleport>(); }
private static void Spawn(MonStat monStat, int x, int y, int level, Transform root) { if (!CollisionMap.Passable(new Vector2i(x, y) * Iso.SubTileCount, monStat.ext.sizeX)) { return; } int count = Random.Range(monStat.minGrp, monStat.maxGrp + 1); for (int i = 0; i < count; ++i) { var mon = World.SpawnMonster(monStat, Iso.MapTileToWorld(x, y), root); mon.level = level; } if (monStat.minion1 != null) { int minionCount = Random.Range(monStat.partyMin, monStat.partyMax); for (int i = 0; i < minionCount; ++i) { var mon = World.SpawnMonster(monStat.minion1, Iso.MapTileToWorld(x, y), root); mon.level = level; } } }
public override void Tick(RealmTime time) { try { if (collisionMap == null) { collisionMap = ProjectileOwner is Player ? Owner.EnemiesCollision : Owner.PlayersCollision; } long elapsedTicks = time.tickTimes - BeginTime; if (elapsedTicks > Descriptor.LifetimeMS) { Destroy(true); return; } long counter = time.thisTickTimes; while (counter > LogicTicker.MsPT && TickCore(elapsedTicks - counter, time)) { counter -= LogicTicker.MsPT; } if (Owner != null) { TickCore(elapsedTicks, time); } base.Tick(time); } catch { Program.logger.Error("Crash halted - Projectiles!"); } }
public override void Initialize() { base.Initialize(); this.spriteBatch = new SpriteBatch(GraphicsDevice); this.pixel = new Texture2D(this.GraphicsDevice, 1, 1); pixel.SetData <Color>(new Color[] { Color.White }); initialized = true; this.collisions = new CollisionMap(); int x = 0; int y = 0; foreach (TileBehavior b in TileBehavior.Values) { collisions.Add(new Rectangle(x, y, 16, 16)); if (x + 32 >= this.Width) { y += 16; x = 0; } else { x += 16; } } }
protected override void Awake() { base.Awake(); CollisionMap.SetBlocked(Iso.MapToIso(transform.position), CollisionLayers.Item); _animator = GetComponent <SpriteAnimator>(); _renderer = GetComponent <SpriteRenderer>(); }
public void SetMap(string path) { FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); BinaryReader r = new BinaryReader(fs); CurMap = new Map.Map(); r.ReadInt32(); CurMap.Read(r); r.Close(); fs.Close(); Graph = CurMap.UpdateGraph(64, 64); Graph.X = (AppInfo.W / 2) - 32; Graph.Y = (AppInfo.H / 2) - 32; float mz, maz; mz = 1000; maz = -1000; foreach (var n in Graph.Root.Nodes) { if (n.Z < mz) { mz = n.Z; } if (n.Z > maz) { maz = n.Z; } } Console.WriteLine("MinZ:" + mz + " MaxZ:" + maz); ColMap = Graph.CreateCollisionMap(); }
public IEncodable Decode(BinaryInput stream) { Name = stream.ReadString(); ID = stream.ReadInt32(); EntityType = (EntityType)stream.ReadByte(); ShadowType = (ShadowType)stream.ReadByte(); ShadowType = ShadowType.Perspective; isSubEntity = stream.ReadBoolean(); ShadowOffset = stream.ReadInt32(); stream.ReadInt32(); CollisionMap = stream.ReadObject <CollisionMap>(); Texture = stream.ReadObject <TileableTexture>(); int c = stream.ReadInt32(); for (int i = 0; i < c; i++) { Animations.Add(stream.ReadObject <Animation>()); } return(this); }
protected void LoopPresets(uint pRoom, Room2 room, Level lvl) { for (var pPreset = room.pPreset; pPreset != 0;) { var preset = game.Debugger.Read <PresetUnit>(pPreset); var tileLevelNo = CollisionMap.GetTileLevelNo(game, room, preset.dwTxtFileNo); if (tileLevelNo != 0) { var exit = new LevelExit { dwTargetLevel = tileLevelNo, ptPos = new Point((int)((room.dwPosX * 5) + preset.dwPosX), (int)((room.dwPosY * 5) + preset.dwPosY)), dwType = (uint)ExitType.Tile, dwId = preset.dwTxtFileNo, pRoom2 = pRoom }; if (!levelExits.ContainsKey(lvl.dwLevelNo)) { levelExits.Add(lvl.dwLevelNo, new List <LevelExit>()); } if (levelExits[lvl.dwLevelNo].Find(it => it.dwTargetLevel == tileLevelNo) == null) { levelExits[lvl.dwLevelNo].Add(exit); } } DrawPreset(room, lvl, preset); pPreset = preset.pPresetNext; } }
public override void Tick(RealmTime time) { if (collisionMap == null) { collisionMap = ProjectileOwner is Player ? Owner.EnemiesCollision : Owner.PlayersCollision; } long elapsedTicks = time.tickTimes - BeginTime; if (elapsedTicks > Descriptor.LifetimeMS) { Destroy(true); return; } long counter = time.thisTickTimes; while (counter > Manager.Logic.MsPT && TickCore(elapsedTicks - counter, time)) { counter -= Manager.Logic.MsPT; } if (Owner != null) { TickCore(elapsedTicks, time); } base.Tick(time); }
private CollisionMap getCollisionMap(Vector3 clickCoordinatePosition) { Coordinate playerCoordinate = new Coordinate(player.transform.position); Coordinate clickCoordinate = new Coordinate(clickCoordinatePosition); // Create a list of coordinates of objects the player cannot pass. List <Coordinate> blockedCoordinates = new List <Coordinate>(); foreach (GameObject unmovableObject in gameObjects.unmovableObjects) { blockedCoordinates.Add(new Coordinate(unmovableObject.transform.position)); } foreach (GameObject movableObject in gameObjects.movableObjects) { blockedCoordinates.Add(new Coordinate(movableObject.transform.position)); } CollisionMap map = new CollisionMap(GameObjectContainer.Instance.gridSize, GameObjectContainer.Instance.gridSize, playerCoordinate, clickCoordinate); // Add coordinates to the collision map foreach (Coordinate coord in blockedCoordinates) { map.setBlock(coord, true); } return(map); }
public static StaticObject SpawnObject(ObjectInfo objectInfo, Vector3 pos, bool fit = false, Transform parent = null) { if (fit) { pos = Iso.MapToIso(pos); if (!CollisionMap.Fit(pos, out pos, objectInfo.sizeX)) { return(null); } pos = Iso.MapToWorld(pos); } var gameObject = new GameObject(objectInfo.description); gameObject.transform.position = pos; var staticObject = gameObject.AddComponent <StaticObject>(); staticObject.objectInfo = objectInfo; staticObject.title = objectInfo.name; gameObject.transform.SetParent(parent, true); return(staticObject); }
private static void GenerateImage(ImageOutputConfiguration config, Dictionary <string, int> words, string baseName, int seed) { if (!config.IsEnabled) { return; } Console.Write("Generating cloud image..."); var width = config.Width; var height = config.Height; var rand = new Random(seed); var fontFamily = new FontFamily(config.Font); var collisionMap = new CollisionMap(width, height); var measurer = new StringMeasurer(); var minimumFontSize = config.MinimumFontSize; var compactness = config.Compactness; var placer = new WordPlacer(measurer, collisionMap, width, height, rand, fontFamily, minimumFontSize, compactness); var imageGenerator = new ImageGenerator(placer, width, height, fontFamily); var image = imageGenerator.Generate(words); image.Save(baseName); Console.WriteLine("[Done]"); }
public TestZone(int width, int height) { zoneNumber = -1; this.width = width; this.height = height; setDrawLocation(new Vector2(0, 0)); createLists(); //levels.Add(Image.FromFile("../../../Images/Zones/TestGrassZoneFloor1.png")); //levels.Add(Image.FromFile("../../../Images/Zones/TestGrassZoneFloor2.png")); level1 = new CollisionMap(height, width); level2 = new CollisionMap(height, width); collisionMap.Add(level1); collisionMap.Add(level2); level1Trans = new TransitionMap(height, width); level2Trans = new TransitionMap(height, width); transitionMap.Add(level1Trans); transitionMap.Add(level2Trans); fillLevel1(); fillLevel2(); fillLevel1Trans(); fillLevel2Trans(); level1TrafficMap = new TrafficMap(height, width); level2TrafficMap = new TrafficMap(height, width); trafficMap.Add(level1TrafficMap); trafficMap.Add(level2TrafficMap); fillLevel1TrafficMap(); level1EnemyMap = new EnemyMap(height, width); level2EnemyMap = new EnemyMap(height, width); enemyMap.Add(level1EnemyMap); enemyMap.Add(level2EnemyMap); }
// Start is called before the first frame update void Start() { mKillable = GetComponent <Killable>(); mCollisionMap = GameObject.FindObjectOfType <CollisionMap>(); mReviveTime = Random.Range(10f, 25f); }
private bool Move(Vector2 movement) { var newPos = iso.pos + movement; CollisionMap.Move(iso.pos, newPos, size, gameObject); iso.pos = newPos; return(true); }
protected override IEnumerator ActivationCoroutine() { yield return(base.ActivationCoroutine()); if (WasAccepted()) { NumberPopupGenerator.instance.GeneratePopup(gameObject, "Strength Increased", NumberPopupReason.Good); CharacterStatModifier modifier = Game.instance.playerStats.gameObject.AddComponent <CharacterStatModifier>(); modifier.SetRelativeModification(CharacterStatType.Strength, 2); CollisionMap collisionMap = GameObject.FindObjectOfType <CollisionMap>(); // Spawn a bunch of enemies and give the player more strength. List <Vector2Int> walkablePositions = new List <Vector2Int>(); Vector2Int playerPosition = MapCoordinateHelper.WorldToMapCoords(Game.instance.avatar.transform.position); for (int xOffset = -4; xOffset <= 4; ++xOffset) { for (int yOffset = -4; yOffset <= 4; ++yOffset) { if (Mathf.Abs(xOffset) < 2 || Mathf.Abs(yOffset) < 2) { continue; } int x = playerPosition.x + xOffset; int y = playerPosition.y + yOffset; if (collisionMap.SpaceMarking(x, y) == 0) { walkablePositions.Add(new Vector2Int(x, y)); } } } DungeonFloorData data = CurrentDungeonFloorData(); int numEnemies = 5; for (int i = 0; i < numEnemies; ++i) { if (walkablePositions.Count == 0) { continue; } string enemy = data.enemyData.rareEnemy.name; GameObject newEnemy = GameObject.Instantiate(PrefabManager.instance.PrefabByName(enemy)); Vector2Int pos2 = walkablePositions[Random.Range(0, walkablePositions.Count)]; walkablePositions.Remove(pos2); Vector3 pos = MapCoordinateHelper.MapToWorldCoords(pos2); newEnemy.transform.position = pos; collisionMap.MarkSpace(pos2.x, pos2.y, newEnemy.GetComponent <SimpleMovement>().uniqueCollisionIdentity); } } yield break; }
static private void StepTo(Node node) { CollisionLayers collisionMask = CollisionLayers.Walk; Node newNode = null; int dirStart; int dirEnd; if (node.directionIndex == -1) { dirStart = 0; dirEnd = 8; } else if (node.directionIndex % 2 == 0) { dirStart = ((node.directionIndex - 1) + 8) % 8; dirEnd = dirStart + 3; } else { dirStart = ((node.directionIndex - 2) + 8) % 8; dirEnd = dirStart + 5; } for (int i = dirStart; i < dirEnd; ++i) { int dir = i % 8; Vector2i pos = node.pos + directions[dir]; bool passable = CollisionMap.Passable(pos, collisionMask, size: size, ignore: self); if (passable) { if (newNode == null) { newNode = Node.Get(); } newNode.pos = pos; bool closed = closeNodes.Contains(newNode); if (!closed) { newNode.parent = node; newNode.gScore = node.gScore + 1; newNode.hScore = Vector2i.manhattanDistance(target, newNode.pos); newNode.score = newNode.gScore + newNode.hScore; newNode.directionIndex = dir; openNodes.Add(newNode); closeNodes.Add(newNode); newNode = null; } } } if (newNode != null) { newNode.Recycle(); } }
private void Awake() { if (materialProperties == null) { materialProperties = new MaterialPropertyBlock(); } CollisionMap.SetPassable(Iso.MapToIso(transform.position), false); animator = GetComponent <SpriteAnimator>(); }
protected override void Start() { base.Start(); CollisionMap.Move(iso.pos, iso.pos, size, gameObject); if (monStat != null) { AudioManager.instance.Play(monStat.sound.init, transform); } }
private void Awake() { if (materialProperties == null) { materialProperties = new MaterialPropertyBlock(); } CollisionMap.SetBlocked(Iso.MapToIso(transform.position), CollisionLayers.Item); animator = GetComponent <SpriteAnimator>(); }
void OnEnable() { map = new Cell[width * height]; for (int i = 0; i < map.Length; ++i) { map[i].blocked = CollisionLayers.All; } origin = width * 5 + 5; instance = this; }
public void ShouldBeEmptyWhenNothingWasAdded() { // Arrange var sut = new CollisionMap(1, 1); // Act var actual = sut.Rectangles.ToList(); // Assert Assert.Empty(actual); }
public void ShouldCheckForOutOfRightBound() { // Arrange var sut = new CollisionMap(5, 5); // Act var actual = sut.Check(new RectangleF(6, 1, 3, 3).Yield()); // Assert Assert.False(actual); }
public void ShouldCheckForLeftBorder() { // Arrange var sut = new CollisionMap(5, 5); // Act var actual = sut.Check(new RectangleF(-1, 1, 3, 3).Yield()); // Assert Assert.False(actual); }
/// <summary> /// Sole constructor. </summary> public CompactLabelToOrdinal(int initialCapacity, float loadFactor, int numHashArrays) { this.hashArrays = new HashArray[numHashArrays]; this.capacity = DetermineCapacity((int)Math.Pow(2, numHashArrays), initialCapacity); Init(); this.collisionMap = new CollisionMap(this.labelRepository); this.counter = 0; this.loadFactor = loadFactor; this.threshold = (int)(this.loadFactor * this.capacity); }
public IEncodable Decode(BinaryInput stream) { Name = stream.ReadString(); ID = stream.ReadInt32(); EntityType = (EntityType) stream.ReadByte(); ShadowType = (ShadowType) stream.ReadByte(); ShadowType = ShadowType.Perspective; isSubEntity = stream.ReadBoolean(); ShadowOffset = stream.ReadInt32(); stream.ReadInt32(); CollisionMap = stream.ReadObject<CollisionMap>(); Texture = stream.ReadObject<TileableTexture>(); int c = stream.ReadInt32(); for (int i = 0; i < c; i++) { Animations.Add(stream.ReadObject<Animation>()); } return this; }
public override void Initialize() { base.Initialize(); this.spriteBatch = new SpriteBatch(GraphicsDevice); this.pixel = new Texture2D(this.GraphicsDevice, 1, 1); pixel.SetData<Color>(new Color[] {Color.White}); initialized = true; this.collisions = new CollisionMap(); int x = 0; int y = 0; foreach (TileBehavior b in TileBehavior.Values) { collisions.Add(new Rectangle(x, y, 16, 16)); if (x + 32 >= this.Width) { y += 16; x = 0; } else { x += 16; } } }
public override void Tick(RealmTime time) { try { if (collisionMap == null) collisionMap = ProjectileOwner is Player ? Owner.EnemiesCollision : Owner.PlayersCollision; long elapsedTicks = time.tickTimes - BeginTime; if (elapsedTicks > Descriptor.LifetimeMS) { Destroy(true); return; } long counter = time.thisTickTimes; while (counter > LogicTicker.MsPT && TickCore(elapsedTicks - counter, time)) counter -= LogicTicker.MsPT; if (Owner != null) TickCore(elapsedTicks, time); base.Tick(time); } catch { Program.logger.Error("Crash halted - Projectiles!"); } }
public EntityTemplate() { Name = string.Empty; CollisionMap = new CollisionMap(); Animations = new List<Animation>(); }
public override void Init() { // IPlayerMovementFunction movementFunction; var sceneProperties = new SceneProperties(); var themeData = contentLoader.LoadAsset<ThemeData>("Themes/CampaignWorld1"); var sceneData = contentLoader.LoadAsset<SceneData>("Scenarios/Campaign/Level1"); Scene scene = new Scene(sceneData); ITheme theme = new Theme(themeData); ICollisionMap collistionMap = new CollisionMap(scene); var playerPresentation = objectsFactory.CreateAnimatedSprite("Sprites/Hero/Sprites"); player.Init(scene2d, playerPresentation as IAnimatedObject, sceneProperties, collistionMap); player.SetRelativePosition(new Vector2(sceneProperties.TileSize)); player.AddChild(playerPresentation); IMovementFunction movementFunction = functionsFactory.CreatePlayerMovement(player); movementFunction.RegisterMovmentListener(player); scene2d.Init(camera, theme, sceneProperties, scene, player); }
public override void Tick(RealmTime time) { try { if (collisionMap == null) collisionMap = ProjectileOwner is Player ? Owner.EnemiesCollision : Owner.PlayersCollision; long elapsedTicks = time.tickTimes - BeginTime; if (elapsedTicks > Descriptor.LifetimeMS) { Destroy(true); return; } long counter = time.thisTickTimes; while (counter > LogicTicker.MsPT && TickCore(elapsedTicks - counter, time)) counter -= LogicTicker.MsPT; if (Owner != null) TickCore(elapsedTicks, time); base.Tick(time); } catch { Console.ForegroundColor = ConsoleColor.DarkBlue; Console.Out.WriteLine("Crash halted - Error in Projectile.cs!"); Console.ForegroundColor = ConsoleColor.White; } }
public override void Tick(RealmTime time) { if (collisionMap == null) collisionMap = ProjectileOwner is Player ? Owner.EnemiesCollision : Owner.PlayersCollision; long elapsedTicks = time.tickTimes - BeginTime; if (elapsedTicks > Descriptor.LifetimeMS) { Destroy(true); return; } long counter = time.thisTickTimes; while (counter > Manager.Logic.MsPT && TickCore(elapsedTicks - counter, time)) counter -= Manager.Logic.MsPT; if (Owner != null) TickCore(elapsedTicks, time); base.Tick(time); }
protected void FromWorldMap(System.IO.Stream dat) { log.InfoFormat("Loading map for world {0}({1})...", Id, Name); Wmap map = new Wmap(); this.Map = map; entityInc = 0; entityInc += Map.Load(dat, 0); int w = Map.Width, h = Map.Height; Obstacles = new byte[w, h]; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { var tile = Map[x, y]; ObjectDesc desc; if (XmlDatas.TileDescs[tile.TileId].NoWalk) Obstacles[x, y] = 3; if (XmlDatas.ObjectDescs.TryGetValue(tile.ObjType, out desc)) { if (desc.Class == "Wall" || desc.Class == "ConnectedWall" || desc.Class == "CaveWall") Obstacles[x, y] = 2; else if (desc.OccupySquare || desc.EnemyOccupySquare) Obstacles[x, y] = 1; } } EnemiesCollision = new CollisionMap<Entity>(0, w, h); PlayersCollision = new CollisionMap<Entity>(1, w, h); ProjectilesCollision = new CollisionMap<Entity>(1, w, h); Projectiles.Clear(); StaticObjects.Clear(); Enemies.Clear(); Players.Clear(); foreach (var i in Map.InstantiateEntities(Manager)) { if (i.ObjectDesc != null && (i.ObjectDesc.OccupySquare || i.ObjectDesc.EnemyOccupySquare)) Obstacles[(int)(i.X - 0.5), (int)(i.Y - 0.5)] = 2; EnterWorld(i); } }
public override void Tick(RealmTime time) { try { if (collisionMap == null) collisionMap = ProjectileOwner is Player || ProjectileOwner.Self.isPet ? Owner.EnemiesCollision : Owner.PlayersCollision; var elapsedTicks = time.tickTimes - BeginTime; if (elapsedTicks > Descriptor.LifetimeMS) { Destroy(true); return; } long counter = time.thisTickTimes; while (counter > LogicTicker.MsPT && TickCore(elapsedTicks - counter, time)) counter -= LogicTicker.MsPT; if (Owner != null) TickCore(elapsedTicks, time); base.Tick(time); } catch (Exception ex) { Logger.Error(ex); } }
private void FromWorldMap(Stream dat) { var map = new Wmap(Manager.GameData); Map = map; entityInc = 0; entityInc += Map.Load(dat, 0); int w = Map.Width, h = Map.Height; Obstacles = new byte[w, h]; for (var y = 0; y < h; y++) for (var x = 0; x < w; x++) { try { var tile = Map[x, y]; ObjectDesc desc; if (Manager.GameData.Tiles[tile.TileId].NoWalk) Obstacles[x, y] = 3; if (Manager.GameData.ObjectDescs.TryGetValue(tile.ObjType, out desc)) { if (desc.Class == "Wall" || desc.Class == "ConnectedWall" || desc.Class == "CaveWall") Obstacles[x, y] = 2; else if (desc.OccupySquare || desc.EnemyOccupySquare) Obstacles[x, y] = 1; } } catch (Exception ex) { Log.Error(ex); } } EnemiesCollision = new CollisionMap<Entity>(0, w, h); PlayersCollision = new CollisionMap<Entity>(1, w, h); Projectiles.Clear(); StaticObjects.Clear(); Enemies.Clear(); Players.Clear(); foreach (var i in Map.InstantiateEntities(Manager)) { if (i.ObjectDesc != null && (i.ObjectDesc.OccupySquare || i.ObjectDesc.EnemyOccupySquare)) Obstacles[(int)(i.X - 0.5), (int)(i.Y - 0.5)] = 2; EnterWorld(i); } }
/// <summary> /// Initialize CollisionHandler by passing it the collision map. An individual image fraction is then refered to as a zone. /// </summary> public static void Initialize(CollisionMap _map, List<Enemy> enem, Player player, List<Platform> plat, List<Ladder> ladders, ContentManager _content) { for (int i = 0; i < enem.Count; i++) gameObjects.Add(enem[i]); for (int i = 0; i < plat.Count; i++) gameObjects.Add(plat[i]); for (int i = 0; i < ladders.Count; i++) gameObjects.Add(ladders[i]); gameObjects.Add(player); content = _content; Map = _map; resizeFactor = Map.ResizeFactor; Map.LoadAllTextures(_content); Map.LoadAllTextureData(); zone_height = Map.CropSize.Y; zone_width = Map.CropSize.X; map_width = Map.CropSize.X * Map.Fractions / 2; map_height = Map.CropSize.Y * 2; }
private void Grow() { HashArray temp = this.hashArrays[this.hashArrays.Length - 1]; for (int i = this.hashArrays.Length - 1; i > 0; i--) { this.hashArrays[i] = this.hashArrays[i - 1]; } this.capacity *= 2; this.hashArrays[0] = new HashArray(this.capacity); for (int i = 1; i < this.hashArrays.Length; i++) { int[] sourceOffsetArray = this.hashArrays[i].offsets; int[] sourceCidsArray = this.hashArrays[i].cids; for (int k = 0; k < sourceOffsetArray.Length; k++) { for (int j = 0; j < i && sourceOffsetArray[k] != 0; j++) { int[] targetOffsetArray = this.hashArrays[j].offsets; int[] targetCidsArray = this.hashArrays[j].cids; int newIndex = IndexFor(StringHashCode(this.labelRepository, sourceOffsetArray[k]), targetOffsetArray.Length); if (targetOffsetArray[newIndex] == 0) { targetOffsetArray[newIndex] = sourceOffsetArray[k]; targetCidsArray[newIndex] = sourceCidsArray[k]; sourceOffsetArray[k] = 0; } } } } for (int i = 0; i < temp.offsets.Length; i++) { int offset = temp.offsets[i]; if (offset > 0) { int hash = StringHashCode(this.labelRepository, offset); AddLabelOffset(hash, temp.cids[i], offset); } } CollisionMap oldCollisionMap = this.collisionMap; this.collisionMap = new CollisionMap(oldCollisionMap.Capacity(), this.labelRepository); this.threshold = (int)(this.capacity * this.loadFactor); var it = oldCollisionMap.entryIterator(); while (it.MoveNext()) { var e = it.Current; AddLabelOffset(StringHashCode(this.labelRepository, e.offset), e.cid, e.offset); } }
protected void FromWorldMap(System.IO.Stream dat) { log.InfoFormat("Loading map for world {0}({1})...", Id, Name); this.Map = new Wmap(Manager.GameData); entityInc = 0; entityInc += Map.Load(dat, 0); int w = Map.Width, h = Map.Height; EnemiesCollision = new CollisionMap<Entity>(0, w, h); PlayersCollision = new CollisionMap<Entity>(1, w, h); Projectiles.Clear(); StaticObjects.Clear(); Enemies.Clear(); Players.Clear(); foreach (var i in Map.InstantiateEntities(Manager)) { EnterWorld(i); } }
// void ExportAll() { // string outFileName = EditorUtility.SaveFilePanel( "Select folder to export to", m_lastExportDirectory, "filenameignored", "bin" ); // m_lastExportDirectory = System.IO.Path.GetDirectoryName( outFileName ); SaveLastExportDirectory(); m_project.Export( m_lastExportDirectory ); // // Export all images // string[] imageFiles = m_project.m_imageFiles; foreach( string imageFile in imageFiles ) { Debug.Log( "Exporting file '" + imageFile + "'" ); string outFileNameNoExt = System.IO.Path.GetFileNameWithoutExtension( imageFile ).ToLower(); string outBaseName = m_lastExportDirectory + System.IO.Path.DirectorySeparatorChar + outFileNameNoExt; // PalettizedImageConfig imageConfig = new PalettizedImageConfig( imageFile + ".config" ); PalettizedImage imageData = PalettizedImage.LoadImage( imageFile, imageConfig ); // if( imageData != null ) { // imageConfig.SetImage( imageData ); // Convert to tile banks / planar images // PlanarImage planarImage = new PlanarImage( imageData); TileBank tileBank = new TileBank( imageData, (imageConfig.m_importAsSprite==false) ); TilePalette tilePalette = new TilePalette( imageData ); // Export it if( imageConfig.m_importAsSprite ) { Sprite sprite = new Sprite( imageConfig ); string alternativeAmigaSpriteName; if( imageConfig.m_importAsBSprite ) { AmigaSprite amigaSprite = new AmigaSprite( imageData, imageConfig); alternativeAmigaSpriteName = "_sprite_bank_amiga_b_hw.bin"; amigaSprite.Export( outBaseName + alternativeAmigaSpriteName ); } else { AmigaBob amigaBob = new AmigaBob( imageData, imageConfig); alternativeAmigaSpriteName = "_sprite_bank_amiga_a_bob.bin"; amigaBob.Export( outBaseName + alternativeAmigaSpriteName ); } tileBank.ExportMegaDrive( outBaseName + "_sprite_bank.bin" ); tilePalette.Export( outBaseName + "_palette.bin" ); sprite.Export( outBaseName + "_sprite.bin" ); } else { TileMap tileMap = new TileMap( tileBank, imageData ); tileBank.ExportMegaDrive( outBaseName + "_bank.bin" ); tileBank.ExportAmiga( outBaseName + "_bank_amiga.bin" ); tileMap.Export( outBaseName + "_map.bin" ); tilePalette.Export( outBaseName + "_palette.bin" ); } } } // // Export all maps // string[] mapFiles = m_project.m_mapFiles; foreach( string mapFile in mapFiles ) { Debug.Log( "Exporting map '" + mapFile + "'" ); string outFileNameNoExt = System.IO.Path.GetFileNameWithoutExtension( mapFile ).ToLower(); string outBaseName = m_lastExportDirectory + System.IO.Path.DirectorySeparatorChar + outFileNameNoExt; // TileMap tileMap = TileMap.LoadJson( mapFile ); CollisionMap collisionmap = new CollisionMap( tileMap ); tileMap.Export( outBaseName + "_map.bin" ); collisionmap.Export( outBaseName + "_collisionmap.bin" ); } // // Export all game objects // foreach( string goFile in m_project.m_gameObjectCollectionFiles ) { Debug.Log( "Exporting game object '" + goFile + "'" ); string outFileNameNoExt = m_project.GetOutFileNameNoExt( goFile ); string outBaseName = m_lastExportDirectory + System.IO.Path.DirectorySeparatorChar; GameObjectCollection ggo = new GameObjectCollection( goFile ); ggo.Export( outBaseName + m_project.GetGreatGameObjectName( goFile ), m_project ); } Debug.Log("Export is finished!"); }
//Moves the character based on direction. Interact based on these movements. public void Update(LinkedList<Entity> entities, CollisionMap collideMap) { Velocity = (int)(Velocity * (1.0 - FrictionPercentPerFrame)); //When moving diagonally, //North/South is moved then the other directions. //This is slightly problematic because at high speeds you may glitch through objects because you go in an L-shape. //move the character //As soon an anything happens we stop doing interactions. //This is to prevent errors such as attacking an enemy twice. One event per update. if (VelocityDirection == Direction.N || VelocityDirection == Direction.NW || VelocityDirection == Direction.NE) { if (MoveNorth(entities,collideMap)) return; } if (VelocityDirection == Direction.S || VelocityDirection == Direction.SW || VelocityDirection == Direction.SE) { if (MoveSouth(entities, collideMap)) return; } if (VelocityDirection == Direction.W || VelocityDirection == Direction.SW || VelocityDirection == Direction.NW) MoveWest(entities,collideMap); if (VelocityDirection == Direction.E || VelocityDirection == Direction.SE || VelocityDirection == Direction.NE) MoveEast(entities,collideMap); }
private bool MoveNorth(LinkedList<Entity> e, CollisionMap c) { // Move. DeltaY -= Velocity; //Check for any interactions. if (Interactions(e,Direction.N)) return true; //Move if we have the velocity to. while (DeltaY < 0) { for (int i = 0; i != Size; i++) { if (c.Collide(X + i, Y - 1)) { DeltaY = 0; return false; } } DeltaY = DeltaY + DeltaScale; Y--; if (Interactions(e, Direction.N)) { DeltaY = DeltaScale / 2; DeltaX = DeltaScale / 2; return true; } } return false; }
private bool MoveSouth(LinkedList<Entity> e, CollisionMap c) { // Move south. DeltaY += Velocity; //Check for any interactions. if (Interactions(e, Direction.S)) return true; //Move if we have the velocity to. while (DeltaY >= DeltaScale) { for (int i = 0; i != Size; i++) { if (c.Collide(X + i, Y + Size)) { DeltaY = DeltaScale - 1; return false; } } DeltaY = DeltaY - DeltaScale; Y++; if (Interactions(e, Direction.S)) { DeltaY = DeltaScale / 2; DeltaX = DeltaScale / 2; return true; } } return false; }
private bool MoveWest(LinkedList<Entity> e, CollisionMap c) { // Move south. DeltaX -= Velocity; //Check for any interactions. if (Interactions(e, Direction.W)) return true; //Move if we have the velocity to. while (DeltaX < 0) { for (int i = 0; i != Size; i++) { if (c.Collide(X - 1, Y + i)) { DeltaX = 0; return false; } } DeltaX = DeltaX + DeltaScale; X--; //halt movement. if (Interactions(e, Direction.W)) { DeltaY = DeltaScale / 2; DeltaX = DeltaScale / 2; return true; } } return false; }