public override void Update(GameTime gameTime) { KeyboardState currentKeyboardState = Keyboard.GetState(); MouseState currentMouseState = Mouse.GetState(); if (!_previousKeyboardState.IsKeyDown(Keys.Space) && currentKeyboardState.IsKeyDown(Keys.Space)) { if (_activeHull != null && _activeHull.Points.Count > 0) { _activeHull.Points.RemoveAt(_activeHull.Points.Count - 1); } } if (_previousMouseState.LeftButton == ButtonState.Released && currentMouseState.LeftButton == ButtonState.Pressed) { if (_activeHull == null) { _activeHull = new Hull(); _penumbra.Hulls.Add(_activeHull); } _activeHull.Points.Add(currentMouseState.Position.ToVector2()); } if (_previousMouseState.RightButton == ButtonState.Released && currentMouseState.RightButton == ButtonState.Pressed) { _activeHull = null; } _previousKeyboardState = currentKeyboardState; _previousMouseState = currentMouseState; }
public override void Activate(PenumbraComponent penumbra, ContentManager content) { _state = State.MovingInward; _progress = 0; penumbra.Lights.Add(new PointLight { Position = new Vector2(0, -100), Color = Color.White, Scale = new Vector2(600), Radius = 20 }); Vector2[] hullVertices = { new Vector2(-0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(0.5f, -0.5f), new Vector2(-0.5f, -0.5f) }; _hull1 = new Hull(hullVertices) { Position = new Vector2(0, 0), Scale = new Vector2(50f) }; _hull2 = new Hull(hullVertices) { Position = new Vector2(0, 0), Scale = new Vector2(50f) }; penumbra.Hulls.Add(_hull1); penumbra.Hulls.Add(_hull2); }
public void Initialize() { if (control == null) control = GetComponent<dfControl>(); s = gameObject.GetComponent<dfProgressBar>(); s.MinValue = 0; bvl = GetComponentInChildren<barValueLabel>(); switch (owner) { case spawnBars.hudOwner.Player: hull = Target.GetComponentInChildren<Hull>(); break; case spawnBars.hudOwner.Enemy: hull = Target.GetComponentInChildren<Hull>(); if (Target.layer == LayerMask.NameToLayer("NonPlayer")) { Target.GetComponent<NPCController>().setBars(transform.parent.gameObject);//Redundant because it is also in Shieldbar script } else Target.GetComponent<EnemyController>().setBars(transform.parent.gameObject);//Redundant because it is also in Shieldbar script break; } if (isGUITarget) { GUIReciever.hull = hull; GUIReciever.GUITarget = this; } if (owner != spawnBars.hudOwner.GUI) { hull.hBar = this; setValue(); } }
public override void Activate(PenumbraComponent penumbra, ContentManager content) { _light = new PointLight { Position = new Vector2(-150, 0), Color = Color.White, Scale = new Vector2(700), Radius = 20 }; penumbra.Lights.Add(_light); _hull1 = new Hull(new Vector2(-0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(0.5f, -0.5f), new Vector2(-0.5f, -0.5f)) { Position = HullPos1, Scale = new Vector2(90f) }; _hull2 = new Hull(new Vector2(-0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(0.5f, -0.5f), new Vector2(-0.5f, -0.5f)) { Position = HullPos2, Scale = new Vector2(70f) }; _hull3 = new Hull(new Vector2(-0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(0.5f, -0.5f), new Vector2(-0.5f, -0.5f)) { Position = HullPos3, Scale = new Vector2(80f) }; penumbra.Hulls.Add(_hull1); penumbra.Hulls.Add(_hull2); penumbra.Hulls.Add(_hull3); }
protected override void Start() { base.Start(); hull = FindObjectOfType(typeof(Hull)) as Hull; inventory = FindObjectOfType(typeof(Inventory)) as Inventory; constructionMode = ConstructionMode.Idle; }
public void AddEntry(int _ID, Hull _hull) { if(hullTable==null) { hullTable = new List<HullTableEntry>(); } hullTable.Add(new HullTableEntry(_ID, _hull)); _hull.ID = _ID; }
public bool HullExists(Hull _hull) { if (hullTable == null) { return false; } //return hullTable.ContainsValue(_hullPrefab); return hullTable.Any(entry => entry.hull == _hull); }
public void GetBlueprint(out ShipBlueprint blueprint, Hull hullBeingBuilt) { blueprint = new ShipBlueprint(hull); foreach (var slotIndex_Comp in SlotIndex_Comp_List) { blueprint.AddComponent(hullBeingBuilt.index_slot_table[slotIndex_Comp.slotIndex], slotIndex_Comp.component); } blueprint.GenerateMetaData(MetaData.BlueprintName); }
public static int GetID(Hull hull) { #if FULL_DEBUG int hull_ID; if (!hull_id_table.TryGetValue(hull, out hull_ID)) { Debug.LogError("Hull " +hull.hullName + " not found"); } return hull_ID; #else return hull_id_table[hull]; #endif }
/// <summary> /// Return the convex hull of the supplied points, /// Optionally check for duplicate points /// </summary> /// <param name="points">List of 2D vertices</param> /// <param name="rejectDuplicatePoints">Whether to omit duplicated points</param> /// <returns></returns> public List<Vertex> ConvexHull(List<Vertex> points, bool rejectDuplicatePoints) { Hull hull = new Hull(); List<Triad> triads = new List<Triad>(); Analyse(points, hull, triads, rejectDuplicatePoints, true); List<Vertex> hullVertices = new List<Vertex>(); foreach (HullVertex hv in hull) hullVertices.Add(new Vertex(hv.x, hv.y)); return hullVertices; }
protected void Start() { hull = FindObjectOfType(typeof(Hull)) as Hull; inventory = FindObjectOfType(typeof(Inventory)) as Inventory; crewGauge = FindObjectOfType(typeof(CrewGauge)) as CrewGauge; fuelGauge = FindObjectOfType(typeof(FuelGauge)) as FuelGauge; energyGauge = FindObjectOfType(typeof(EnergyGauge)) as EnergyGauge; massGauge = FindObjectOfType(typeof(MassGauge)) as MassGauge; powerGauge = FindObjectOfType(typeof(PowerGauge)) as PowerGauge; accelerationGauge = FindObjectOfType(typeof(AccelerationGauge)) as AccelerationGauge; fuelConsumptionGauge = FindObjectOfType(typeof(FuelConsumptionGauge)) as FuelConsumptionGauge; }
/// <summary> /// Creates a BlueprintTemplate form a blueprint. Validation of blueprint should be done already. /// </summary> /// <param name="blueprint"></param> public BlueprintTemplate(ShipBlueprint blueprint) { this.hull = blueprint.Hull; foreach (var slot_comp in blueprint.Slot_component_table) { SlotIndex_Comp_List.Add( new SlotIndexCompEntry { slotIndex = slot_comp.Key.index, component = slot_comp.Value }); } this.metaData = blueprint.MetaData; }
public void DestroyPart(Hull part) { if (map.ContainsValue(part)) { foreach (DictionaryEntry de in map) { if (de.Value == part) { GameObject go = de.Key as GameObject; DestroyPart(go); return; } } } }
private void GenerateHulls(PenumbraComponent penumbra) { const float increment = MathHelper.TwoPi / NumHulls; const float distance = 185; for (int i = 0; i < NumHulls; i++) { float angle = increment * i; var hull = new Hull(new Vector2(-0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(0.5f, -0.5f), new Vector2(-0.5f, -0.5f)) { Position = Rotate(new Vector2(0, distance), angle), Scale = new Vector2(50f) }; _hulls.Add(hull); penumbra.Hulls.Add(hull); } }
public TurnBasedUnit BuildShip(ShipType shipType, BlueprintTemplate bpTemplate, Vector3 position, Quaternion rotation) { hullBeingBuilt = GameObject.Instantiate(bpTemplate.Hull, position, rotation) as Hull; #if FULL_DEBUG ||LOW_DEBUG if (!hullBeingBuilt) { Debug.LogError("ship null"); } else { Debug.Log("Building ship from template " + bpTemplate.MetaData.BlueprintName); } #endif hullBeingBuilt.Init(); bpTemplate.GetBlueprint(out blueprintBeingBuilt, hullBeingBuilt); return InstantiateShip(true, shipType, position, rotation); }
public override void Activate(PenumbraComponent penumbra, ContentManager content) { Texture2D tex = content.Load<Texture2D>("LightTexture"); _light = new TexturedLight(tex) { Position = new Vector2(-penumbra.GraphicsDevice.Viewport.Width / 2f, 0), Origin = new Vector2(0.5f, 1), Color = Color.White, Radius = 150, Rotation = MathHelper.PiOver2 }; penumbra.Lights.Add(_light); _hull = new Hull(new Vector2(-0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(0.5f, -0.5f), new Vector2(-0.5f, -0.5f)) { Position = Vector2.Zero, Scale = new Vector2(50) }; penumbra.Hulls.Add(_hull); }
public virtual void Init() { weapon = GetComponentInChildren<Weapon>(); engine = GetComponentInChildren<Engine>(); cockpit = GetComponentInChildren<Cockpit> (); hull = GetComponentInChildren<Hull> (); wings = GetComponentInChildren<Wings> (); maxHealth = health = hull.maxHealth; rigidbody2D.mass = hull.mass; shipCollider = GetComponentInChildren<PolygonCollider2D>(); if (wings.maxShield > 0) { wings.parent = this; shipCollider.enabled = false; shieldCollider = GetComponentInChildren<CircleCollider2D>(); shieldCollider.enabled = true; } //activeWeapons = weapons; hitTime = Time.time; }
public override void Activate(PenumbraComponent penumbra, ContentManager content) { _hull = new Hull(new Vector2(-0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(0.5f, -0.5f), new Vector2(-0.5f, -0.5f)) { Position = new Vector2(0, 0), Scale = new Vector2(50f) }; penumbra.Hulls.Add(_hull); _light1 = new PointLight { Position = new Vector2(-250, 0), Color = LightColors[0], Intensity = 1f, Scale = new Vector2(800), Radius = 20 }; _light2 = new PointLight { Position = new Vector2(0, 150), Color = LightColors[1], Intensity = 1.2f, Scale = new Vector2(400), Radius = 30 }; _light3 = new PointLight { Position = new Vector2(0, -50), Color = LightColors[2], Scale = new Vector2(600), Radius = 25, Intensity = 0.8f }; penumbra.Lights.Add(_light1); penumbra.Lights.Add(_light2); penumbra.Lights.Add(_light3); }
private void VerifyTriads(List<Triad> triads, Hull hull) { for (int t = 0; t < triads.Count; t++) { if (t == 17840) t = t + 0; Triad tri = triads[t]; if (tri.ac == -1) VerifyHullContains(hull, tri.a, tri.c); else VerifyTriadContains(triads[tri.ac], t, tri.a, tri.c); if (tri.ab == -1) VerifyHullContains(hull, tri.a, tri.b); else VerifyTriadContains(triads[tri.ab], t, tri.a, tri.b); if (tri.bc == -1) VerifyHullContains(hull, tri.b, tri.c); else VerifyTriadContains(triads[tri.bc], t, tri.b, tri.c); } }
public HullTableEntry(int _ID, Hull _hull) { ID = _ID; hull = _hull; }
public void AutoGenIDAndAdd(Hull hull) { AddEntry(GenNextID(), hull); }
private List <HitscanResult> DoRayCast(Vector2 rayStart, Vector2 rayEnd) { List <HitscanResult> hits = new List <HitscanResult>(); Vector2 dir = rayEnd - rayStart; dir = dir.LengthSquared() < 0.00001f ? Vector2.UnitY : Vector2.Normalize(dir); //do an AABB query first to see if the start of the ray is inside a fixture var aabb = new FarseerPhysics.Collision.AABB(rayStart - Vector2.One * 0.001f, rayStart + Vector2.One * 0.001f); GameMain.World.QueryAABB((fixture) => { //ignore sensors and items if (fixture?.Body == null || fixture.IsSensor) { return(true); } if (fixture.Body.UserData is Item item && (item.GetComponent <Door>() == null && !item.Prefab.DamagedByProjectiles || item.Condition <= 0)) { return(true); } if (fixture.Body?.UserData as string == "ruinroom") { return(true); } //ignore everything else than characters, sub walls and level walls if (!fixture.CollisionCategories.HasFlag(Physics.CollisionCharacter) && !fixture.CollisionCategories.HasFlag(Physics.CollisionWall) && !fixture.CollisionCategories.HasFlag(Physics.CollisionLevel)) { return(true); } if (fixture.Body.UserData is VoronoiCell && this.item.Submarine != null) { return(true); } fixture.Body.GetTransform(out FarseerPhysics.Common.Transform transform); if (!fixture.Shape.TestPoint(ref transform, ref rayStart)) { return(true); } hits.Add(new HitscanResult(fixture, rayStart, -dir, 0.0f)); return(true); }, ref aabb); GameMain.World.RayCast((fixture, point, normal, fraction) => { //ignore sensors and items if (fixture?.Body == null || fixture.IsSensor) { return(-1); } if (fixture.Body.UserData is Item item && (item.GetComponent <Door>() == null && !item.Prefab.DamagedByProjectiles || item.Condition <= 0)) { return(-1); } if (fixture.Body?.UserData as string == "ruinroom") { return(-1); } //ignore everything else than characters, sub walls and level walls if (!fixture.CollisionCategories.HasFlag(Physics.CollisionCharacter) && !fixture.CollisionCategories.HasFlag(Physics.CollisionWall) && !fixture.CollisionCategories.HasFlag(Physics.CollisionLevel)) { return(-1); } //ignore level cells if the item the point of impact are inside a sub if (fixture.Body.UserData is VoronoiCell && this.item.Submarine != null) { if (Hull.FindHull(ConvertUnits.ToDisplayUnits(point), this.item.CurrentHull) != null) { return(-1); } } hits.Add(new HitscanResult(fixture, point, normal, fraction)); return(hits.Count < 25 ? 1 : 0); }, rayStart, rayEnd, Physics.CollisionCharacter | Physics.CollisionWall | Physics.CollisionLevel); return(hits); }
void Clear() { HullTable hullTable = target as HullTable; id = hullTable.GenNextID(); ; hull = null; }
private void Repair(Vector2 rayStart, Vector2 rayEnd, float deltaTime, Character user, float degreeOfSuccess, List <Body> ignoredBodies) { var collisionCategories = Physics.CollisionWall | Physics.CollisionCharacter | Physics.CollisionItem | Physics.CollisionLevel | Physics.CollisionRepair; float lastPickedFraction = 0.0f; if (RepairMultiple) { var bodies = Submarine.PickBodies(rayStart, rayEnd, ignoredBodies, collisionCategories, ignoreSensors: RepairThroughHoles, allowInsideFixture: true); lastPickedFraction = Submarine.LastPickedFraction; Type lastHitType = null; hitCharacters.Clear(); foreach (Body body in bodies) { Type bodyType = body.UserData?.GetType(); if (!RepairThroughWalls && bodyType != null && bodyType != lastHitType) { //stop the ray if it already hit a door/wall and is now about to hit some other type of entity if (lastHitType == typeof(Item) || lastHitType == typeof(Structure)) { break; } } Character hitCharacter = null; if (body.UserData is Limb limb) { hitCharacter = limb.character; } else if (body.UserData is Character character) { hitCharacter = character; } //only do damage once to each character even if they ray hit multiple limbs if (hitCharacter != null) { if (hitCharacters.Contains(hitCharacter)) { continue; } hitCharacters.Add(hitCharacter); } if (FixBody(user, deltaTime, degreeOfSuccess, body)) { lastPickedFraction = Submarine.LastPickedBodyDist(body); if (bodyType != null) { lastHitType = bodyType; } } } } else { FixBody(user, deltaTime, degreeOfSuccess, Submarine.PickBody(rayStart, rayEnd, ignoredBodies, collisionCategories, ignoreSensors: RepairThroughHoles, customPredicate: (Fixture f) => { return(f?.Body?.UserData != null); }, allowInsideFixture: true)); lastPickedFraction = Submarine.LastPickedFraction; } if (ExtinguishAmount > 0.0f && item.CurrentHull != null) { fireSourcesInRange.Clear(); //step along the ray in 10% intervals, collecting all fire sources in the range for (float x = 0.0f; x <= lastPickedFraction; x += 0.1f) { Vector2 displayPos = ConvertUnits.ToDisplayUnits(rayStart + (rayEnd - rayStart) * x); if (item.CurrentHull.Submarine != null) { displayPos += item.CurrentHull.Submarine.Position; } Hull hull = Hull.FindHull(displayPos, item.CurrentHull); if (hull == null) { continue; } foreach (FireSource fs in hull.FireSources) { if (fs.IsInDamageRange(displayPos, 100.0f) && !fireSourcesInRange.Contains(fs)) { fireSourcesInRange.Add(fs); } } } foreach (FireSource fs in fireSourcesInRange) { fs.Extinguish(deltaTime, ExtinguishAmount); #if SERVER GameMain.Server.KarmaManager.OnExtinguishingFire(user, deltaTime); #endif } } if (GameMain.NetworkMember == null || GameMain.NetworkMember.IsServer) { if (Rand.Range(0.0f, 1.0f) < FireProbability * deltaTime) { Vector2 displayPos = ConvertUnits.ToDisplayUnits(rayStart + (rayEnd - rayStart) * lastPickedFraction * 0.9f); if (item.CurrentHull.Submarine != null) { displayPos += item.CurrentHull.Submarine.Position; } new FireSource(displayPos); } } }
private bool CollisionUpdate() { if (currentHull == null) { Hull collidedHull = Hull.FindHull(position); if (collidedHull != null) { if (prefab.DeleteOnCollision) { return(false); } OnWallCollisionOutside(collidedHull); } } else { Rectangle hullRect = currentHull.WorldRect; Vector2 collisionNormal = Vector2.Zero; if (velocity.Y < 0.0f && position.Y - prefab.CollisionRadius * size.Y < hullRect.Y - hullRect.Height) { if (prefab.DeleteOnCollision) { return(false); } collisionNormal = new Vector2(0.0f, 1.0f); } else if (velocity.Y > 0.0f && position.Y + prefab.CollisionRadius * size.Y > hullRect.Y) { if (prefab.DeleteOnCollision) { return(false); } collisionNormal = new Vector2(0.0f, -1.0f); } else if (velocity.X < 0.0f && position.X - prefab.CollisionRadius * size.X < hullRect.X) { if (prefab.DeleteOnCollision) { return(false); } collisionNormal = new Vector2(1.0f, 0.0f); } else if (velocity.X > 0.0f && position.X + prefab.CollisionRadius * size.X > hullRect.Right) { if (prefab.DeleteOnCollision) { return(false); } collisionNormal = new Vector2(-1.0f, 0.0f); } if (collisionNormal != Vector2.Zero) { bool gapFound = false; foreach (Gap gap in hullGaps) { if (gap.Open <= 0.9f || gap.IsHorizontal != (collisionNormal.X != 0.0f)) { continue; } if (gap.IsHorizontal) { if (gap.WorldRect.Y < position.Y || gap.WorldRect.Y - gap.WorldRect.Height > position.Y) { continue; } int gapDir = Math.Sign(gap.WorldRect.Center.X - currentHull.WorldRect.Center.X); if (Math.Sign(velocity.X) != gapDir || Math.Sign(position.X - currentHull.WorldRect.Center.X) != gapDir) { continue; } } else { if (gap.WorldRect.X > position.X || gap.WorldRect.Right < position.X) { continue; } float hullCenterY = currentHull.WorldRect.Y - currentHull.WorldRect.Height / 2; int gapDir = Math.Sign(gap.WorldRect.Y - hullCenterY); if (Math.Sign(velocity.Y) != gapDir || Math.Sign(position.Y - hullCenterY) != gapDir) { continue; } } gapFound = true; break; } if (!gapFound) { OnWallCollisionInside(currentHull, collisionNormal); } else { Hull newHull = Hull.FindHull(position, currentHull); if (newHull != currentHull) { currentHull = newHull; hullGaps = currentHull == null ? new List <Gap>() : currentHull.ConnectedGaps; OnChangeHull?.Invoke(position, currentHull); } } } } return(true); }
private void Repair(Vector2 rayStart, Vector2 rayEnd, float deltaTime, Character user, float degreeOfSuccess, List <Body> ignoredBodies) { var collisionCategories = Physics.CollisionWall | Physics.CollisionCharacter | Physics.CollisionItem | Physics.CollisionLevel | Physics.CollisionRepair; //if the item can cut off limbs, activate nearby bodies to allow the raycast to hit them if (statusEffectLists != null && statusEffectLists.ContainsKey(ActionType.OnUse)) { if (statusEffectLists[ActionType.OnUse].Any(s => s.SeverLimbsProbability > 0.0f)) { float rangeSqr = ConvertUnits.ToSimUnits(Range); rangeSqr *= rangeSqr; foreach (Character c in Character.CharacterList) { if (!c.Enabled || !c.AnimController.BodyInRest) { continue; } //do a broad check first if (Math.Abs(c.WorldPosition.X - item.WorldPosition.X) > 1000.0f) { continue; } if (Math.Abs(c.WorldPosition.Y - item.WorldPosition.Y) > 1000.0f) { continue; } foreach (Limb limb in c.AnimController.Limbs) { if (Vector2.DistanceSquared(limb.SimPosition, item.SimPosition) < rangeSqr && Vector2.Dot(rayEnd - rayStart, limb.SimPosition - rayStart) > 0) { c.AnimController.BodyInRest = false; break; } } } } } float lastPickedFraction = 0.0f; if (RepairMultiple) { var bodies = Submarine.PickBodies(rayStart, rayEnd, ignoredBodies, collisionCategories, ignoreSensors: false, customPredicate: (Fixture f) => { if (RepairThroughHoles && f.IsSensor && f.Body?.UserData is Structure) { return(false); } if (f.Body?.UserData as string == "ruinroom") { return(false); } return(true); }, allowInsideFixture: true); lastPickedFraction = Submarine.LastPickedFraction; Type lastHitType = null; hitCharacters.Clear(); foreach (Body body in bodies) { Type bodyType = body.UserData?.GetType(); if (!RepairThroughWalls && bodyType != null && bodyType != lastHitType) { //stop the ray if it already hit a door/wall and is now about to hit some other type of entity if (lastHitType == typeof(Item) || lastHitType == typeof(Structure)) { break; } } Character hitCharacter = null; if (body.UserData is Limb limb) { hitCharacter = limb.character; } else if (body.UserData is Character character) { hitCharacter = character; } //only do damage once to each character even if they ray hit multiple limbs if (hitCharacter != null) { if (hitCharacters.Contains(hitCharacter)) { continue; } hitCharacters.Add(hitCharacter); } if (FixBody(user, deltaTime, degreeOfSuccess, body)) { lastPickedFraction = Submarine.LastPickedBodyDist(body); if (bodyType != null) { lastHitType = bodyType; } } } } else { FixBody(user, deltaTime, degreeOfSuccess, Submarine.PickBody(rayStart, rayEnd, ignoredBodies, collisionCategories, ignoreSensors: false, customPredicate: (Fixture f) => { if (RepairThroughHoles && f.IsSensor && f.Body?.UserData is Structure) { return(false); } if (f.Body?.UserData as string == "ruinroom") { return(false); } if (f.Body?.UserData is Item targetItem) { if (!HitItems) { return(false); } if (HitBrokenDoors) { if (targetItem.GetComponent <Door>() == null && targetItem.Condition <= 0) { return(false); } } else { if (targetItem.Condition <= 0) { return(false); } } } return(f.Body?.UserData != null); }, allowInsideFixture: true)); lastPickedFraction = Submarine.LastPickedFraction; } if (ExtinguishAmount > 0.0f && item.CurrentHull != null) { fireSourcesInRange.Clear(); //step along the ray in 10% intervals, collecting all fire sources in the range for (float x = 0.0f; x <= lastPickedFraction; x += 0.1f) { Vector2 displayPos = ConvertUnits.ToDisplayUnits(rayStart + (rayEnd - rayStart) * x); if (item.CurrentHull.Submarine != null) { displayPos += item.CurrentHull.Submarine.Position; } Hull hull = Hull.FindHull(displayPos, item.CurrentHull); if (hull == null) { continue; } foreach (FireSource fs in hull.FireSources) { if (fs.IsInDamageRange(displayPos, 100.0f) && !fireSourcesInRange.Contains(fs)) { fireSourcesInRange.Add(fs); } } } foreach (FireSource fs in fireSourcesInRange) { fs.Extinguish(deltaTime, ExtinguishAmount); #if SERVER GameMain.Server.KarmaManager.OnExtinguishingFire(user, deltaTime); #endif } } if (GameMain.NetworkMember == null || GameMain.NetworkMember.IsServer) { if (Rand.Range(0.0f, 1.0f) < FireProbability * deltaTime) { Vector2 displayPos = ConvertUnits.ToDisplayUnits(rayStart + (rayEnd - rayStart) * lastPickedFraction * 0.9f); if (item.CurrentHull.Submarine != null) { displayPos += item.CurrentHull.Submarine.Position; } new FireSource(displayPos); } } }
public override void ReceiveSignal(Signal signal, Connection connection) { Item source = signal.source; if (source == null || source.CurrentHull == null) { return; } Hull sourceHull = source.CurrentHull; if (!hullDatas.TryGetValue(sourceHull, out HullData hullData)) { hullData = new HullData(); hullDatas.Add(sourceHull, hullData); } if (hullData.Distort) { return; } switch (connection.Name) { case "water_data_in": //cheating a bit because water detectors don't actually send the water level float waterAmount; if (source.GetComponent <WaterDetector>() == null) { waterAmount = Rand.Range(0.0f, 1.0f); } else { waterAmount = Math.Min(sourceHull.WaterVolume / sourceHull.Volume, 1.0f); } hullData.ReceivedWaterAmount = waterAmount; foreach (var linked in sourceHull.linkedTo) { if (!(linked is Hull linkedHull)) { continue; } if (!hullDatas.TryGetValue(linkedHull, out HullData linkedHullData)) { linkedHullData = new HullData(); hullDatas.Add(linkedHull, linkedHullData); } linkedHullData.ReceivedWaterAmount = waterAmount; } break; case "oxygen_data_in": if (!float.TryParse(signal.value, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out float oxy)) { oxy = Rand.Range(0.0f, 100.0f); } hullData.ReceivedOxygenAmount = oxy; foreach (var linked in sourceHull.linkedTo) { if (!(linked is Hull linkedHull)) { continue; } if (!hullDatas.TryGetValue(linkedHull, out HullData linkedHullData)) { linkedHullData = new HullData(); hullDatas.Add(linkedHull, linkedHullData); } linkedHullData.ReceivedOxygenAmount = oxy; } break; } }
public void Init(ParticlePrefab prefab, Vector2 position, Vector2 speed, float rotation, Hull hullGuess = null) { this.prefab = prefab; spriteIndex = Rand.Int(prefab.Sprites.Count); animState = 0; animFrame = 0; dragWait = 0; dragVec = Vector2.Zero; currentHull = Hull.FindHull(position, hullGuess); this.position = position; prevPosition = position; drawPosition = position; velocity = MathUtils.IsValid(speed) ? speed : Vector2.Zero; if (currentHull != null && currentHull.Submarine != null) { velocity += ConvertUnits.ToDisplayUnits(currentHull.Submarine.Velocity); } this.rotation = rotation + Rand.Range(prefab.StartRotationMinRad, prefab.StartRotationMaxRad); prevRotation = rotation; angularVelocity = Rand.Range(prefab.AngularVelocityMinRad, prefab.AngularVelocityMaxRad); if (GameMain.NilMod.ParticleWhitelist.Find(p => p == prefab.Name) != null) { totalLifeTime = prefab.LifeTime; lifeTime = prefab.LifeTime; } else { totalLifeTime = prefab.LifeTime * GameMain.NilMod.ParticleLifeMultiplier; lifeTime = prefab.LifeTime * GameMain.NilMod.ParticleLifeMultiplier; } size = prefab.StartSizeMin + (prefab.StartSizeMax - prefab.StartSizeMin) * Rand.Range(0.0f, 1.0f); sizeChange = prefab.SizeChangeMin + (prefab.SizeChangeMax - prefab.SizeChangeMin) * Rand.Range(0.0f, 1.0f); color = new Color(prefab.StartColor, 1.0f); alpha = prefab.StartAlpha; velocityChange = prefab.VelocityChangeDisplay; velocityChangeWater = prefab.VelocityChangeWaterDisplay; OnChangeHull = null; subEmitters.Clear(); foreach (ParticleEmitterPrefab emitterPrefab in prefab.SubEmitters) { subEmitters.Add(new ParticleEmitter(emitterPrefab)); } if (prefab.DeleteOnCollision || prefab.CollidesWithWalls) { hullGaps = currentHull == null ? new List <Gap>() : currentHull.ConnectedGaps; } if (prefab.RotateToDirection) { this.rotation = MathUtils.VectorToAngle(new Vector2(velocity.X, -velocity.Y)); prevRotation = rotation; } }
public override void Start() { base.Start(); var firstAidOrder = Order.GetPrefab("requestfirstaid"); doctor_firstAidIcon = firstAidOrder.SymbolSprite; doctor_firstAidIconColor = firstAidOrder.Color; subPatients = new List <Character>(); radioSpeakerName = TextManager.Get("Tutorial.Radio.Speaker"); doctor = Character.Controlled; doctor_suppliesCabinet = Item.ItemList.Find(i => i.HasTag("doctor_suppliescabinet"))?.GetComponent <ItemContainer>(); doctor_medBayCabinet = Item.ItemList.Find(i => i.HasTag("doctor_medbaycabinet"))?.GetComponent <ItemContainer>(); var patientHull1 = WayPoint.WayPointList.Find(wp => wp.IdCardDesc == "waitingroom").CurrentHull; var patientHull2 = WayPoint.WayPointList.Find(wp => wp.IdCardDesc == "airlock").CurrentHull; medBay = WayPoint.WayPointList.Find(wp => wp.IdCardDesc == "medbay").CurrentHull; var assistantInfo = new CharacterInfo(Character.HumanSpeciesName, "", JobPrefab.Get("assistant")); patient1 = Character.Create(assistantInfo, patientHull1.WorldPosition, "1"); patient1.GiveJobItems(null); patient1.CanSpeak = false; patient1.AddDamage(patient1.WorldPosition, new List <Affliction>() { new Affliction(AfflictionPrefab.Burn, 45.0f) }, stun: 0, playSound: false); patient1.AIController.Enabled = false; assistantInfo = new CharacterInfo(Character.HumanSpeciesName, "", JobPrefab.Get("assistant")); patient2 = Character.Create(assistantInfo, patientHull2.WorldPosition, "2"); patient2.GiveJobItems(null); patient2.CanSpeak = false; patient2.AIController.Enabled = false; var mechanicInfo = new CharacterInfo(Character.HumanSpeciesName, "", JobPrefab.Get("engineer")); var subPatient1 = Character.Create(mechanicInfo, WayPoint.GetRandom(SpawnType.Human, mechanicInfo.Job, Submarine.MainSub).WorldPosition, "3"); subPatient1.AddDamage(patient1.WorldPosition, new List <Affliction>() { new Affliction(AfflictionPrefab.Burn, 40.0f) }, stun: 0, playSound: false); subPatients.Add(subPatient1); var securityInfo = new CharacterInfo(Character.HumanSpeciesName, "", JobPrefab.Get("securityofficer")); var subPatient2 = Character.Create(securityInfo, WayPoint.GetRandom(SpawnType.Human, securityInfo.Job, Submarine.MainSub).WorldPosition, "3"); subPatient2.AddDamage(patient1.WorldPosition, new List <Affliction>() { new Affliction(AfflictionPrefab.InternalDamage, 40.0f) }, stun: 0, playSound: false); subPatients.Add(subPatient2); var engineerInfo = new CharacterInfo(Character.HumanSpeciesName, "", JobPrefab.Get("engineer")); var subPatient3 = Character.Create(securityInfo, WayPoint.GetRandom(SpawnType.Human, engineerInfo.Job, Submarine.MainSub).WorldPosition, "3"); subPatient3.AddDamage(patient1.WorldPosition, new List <Affliction>() { new Affliction(AfflictionPrefab.Burn, 20.0f) }, stun: 0, playSound: false); subPatients.Add(subPatient3); doctor_firstDoor = Item.ItemList.Find(i => i.HasTag("doctor_firstdoor")).GetComponent <Door>(); doctor_secondDoor = Item.ItemList.Find(i => i.HasTag("doctor_seconddoor")).GetComponent <Door>(); doctor_thirdDoor = Item.ItemList.Find(i => i.HasTag("doctor_thirddoor")).GetComponent <Door>(); tutorial_upperFinalDoor = Item.ItemList.Find(i => i.HasTag("tutorial_upperfinaldoor")).GetComponent <Door>(); doctor_firstDoorLight = Item.ItemList.Find(i => i.HasTag("doctor_firstdoorlight")).GetComponent <LightComponent>(); doctor_secondDoorLight = Item.ItemList.Find(i => i.HasTag("doctor_seconddoorlight")).GetComponent <LightComponent>(); doctor_thirdDoorLight = Item.ItemList.Find(i => i.HasTag("doctor_thirddoorlight")).GetComponent <LightComponent>(); SetDoorAccess(doctor_firstDoor, doctor_firstDoorLight, false); SetDoorAccess(doctor_secondDoor, doctor_secondDoorLight, false); SetDoorAccess(doctor_thirdDoor, doctor_thirdDoorLight, false); tutorial_submarineDoor = Item.ItemList.Find(i => i.HasTag("tutorial_submarinedoor")).GetComponent <Door>(); tutorial_submarineDoorLight = Item.ItemList.Find(i => i.HasTag("tutorial_submarinedoorlight")).GetComponent <LightComponent>(); SetDoorAccess(tutorial_submarineDoor, tutorial_submarineDoorLight, false); tutorial_lockedDoor_2 = Item.ItemList.Find(i => i.HasTag("tutorial_lockeddoor_2")).GetComponent <Door>(); SetDoorAccess(tutorial_lockedDoor_2, null, true); foreach (var patient in subPatients) { patient.CanSpeak = false; patient.AIController.Enabled = false; patient.GiveJobItems(); } Item reactorItem = Item.ItemList.Find(i => i.Submarine == Submarine.MainSub && i.GetComponent <Reactor>() != null); reactorItem.GetComponent <Reactor>().AutoTemp = true; }
void UpdateSelected() { selectedWing = wings[wingIndex]; selectedEngine = engines[engineIndex]; selectedWeapon = weapons[weaponIndex]; selectedHull = hulls[hullIndex]; selectedCockpit = cockpits[cockpitIndex]; }
public void AddPart(GameObject go, Hull part) { map.Add(go, part); }
private void FindNodes(Vector2 worldPosition, float range) { //see which submarines are within range so we can skip structures that are in far-away subs List <Submarine> submarinesInRange = new List <Submarine>(); foreach (Submarine sub in Submarine.Loaded) { if (item.Submarine == sub) { submarinesInRange.Add(sub); } else { Rectangle subBorders = new Rectangle( sub.Borders.X - (int)range, sub.Borders.Y + (int)range, sub.Borders.Width + (int)(range * 2), sub.Borders.Height + (int)(range * 2)); subBorders.Location += MathUtils.ToPoint(sub.SubBody.Position); if (Submarine.RectContains(subBorders, worldPosition)) { submarinesInRange.Add(sub); } } } //get all walls within range List <Entity> entitiesInRange = new List <Entity>(100); foreach (Structure structure in Structure.WallList) { if (!structure.HasBody || structure.IsPlatform) { continue; } if (structure.Submarine != null && !submarinesInRange.Contains(structure.Submarine)) { continue; } var structureWorldRect = structure.WorldRect; if (worldPosition.X < structureWorldRect.X - range) { continue; } if (worldPosition.X > structureWorldRect.Right + range) { continue; } if (worldPosition.Y > structureWorldRect.Y + range) { continue; } if (worldPosition.Y < structureWorldRect.Y - structureWorldRect.Height - range) { continue; } if (structure.Submarine != null) { if (!submarinesInRange.Contains(structure.Submarine)) { continue; } if (OutdoorsOnly) { //check if the structure is within a hull //add a small offset away from the sub's center so structures right at the edge of a hull are still valid Vector2 offset = Vector2.Normalize(structure.WorldPosition - structure.Submarine.WorldPosition); if (Hull.FindHull(structure.Position + offset * Submarine.GridSize, useWorldCoordinates: false) != null) { continue; } } } entitiesInRange.Add(structure); } foreach (Character character in Character.CharacterList) { if (!character.Enabled) { continue; } if (OutdoorsOnly && character.Submarine != null) { continue; } if (character.Submarine != null && !submarinesInRange.Contains(character.Submarine)) { continue; } if (Vector2.DistanceSquared(character.WorldPosition, worldPosition) < range * range * RangeMultiplierInWalls) { entitiesInRange.Add(character); } } nodes.Clear(); nodes.Add(new Node(worldPosition, -1)); FindNodes(entitiesInRange, worldPosition, 0, range); //construct final nodes (w/ lengths and angles so they don't have to be recalculated when rendering the discharge) for (int i = 0; i < nodes.Count; i++) { if (nodes[i].ParentIndex < 0) { continue; } Node parentNode = nodes[nodes[i].ParentIndex]; float length = Vector2.Distance(nodes[i].WorldPosition, parentNode.WorldPosition) * Rand.Range(1.0f, 1.25f); float angle = MathUtils.VectorToAngle(parentNode.WorldPosition - nodes[i].WorldPosition); nodes[i] = new Node(nodes[i].WorldPosition, nodes[i].ParentIndex, length, angle); } }
public void sendUserEquipmentOnEnterLobby(NodeAddedEvent e, UserInMatchMakingLobbyPrototype user, [Context, JoinByUser] Weapon weapon, [Context, JoinByUser] Hull hull, [JoinByUser] UserInMatchMakingLobby user2Lobby, [JoinByBattleLobby] SingleNode <BattleLobbyComponent> lobby) { SetEquipmentEvent eventInstance = new SetEquipmentEvent(); if (user.userUseItemsPrototype.Preset.HasComponent <PresetEquipmentComponent>()) { PresetEquipmentComponent component = user.userUseItemsPrototype.Preset.GetComponent <PresetEquipmentComponent>(); eventInstance.WeaponId = Flow.Current.EntityRegistry.GetEntity(component.WeaponId).GetComponent <MarketItemGroupComponent>().Key; eventInstance.HullId = Flow.Current.EntityRegistry.GetEntity(component.HullId).GetComponent <MarketItemGroupComponent>().Key; base.ScheduleEvent(eventInstance, lobby); } }
private void CreateHulls() { var hullRects = new Rectangle[] { item.WorldRect, DockingTarget.item.WorldRect }; var subs = new Submarine[] { item.Submarine, DockingTarget.item.Submarine }; bodies = new Body[4]; if (DockingTarget.Door != null) { CreateDoorBody(); } if (Door != null) { DockingTarget.CreateDoorBody(); } if (IsHorizontal) { if (hullRects[0].Center.X > hullRects[1].Center.X) { hullRects = new Rectangle[] { DockingTarget.item.WorldRect, item.WorldRect }; subs = new Submarine[] { DockingTarget.item.Submarine, item.Submarine }; } int scaledDockedDistance = (int)(DockedDistance / 2 * item.Scale); hullRects[0] = new Rectangle(hullRects[0].Center.X, hullRects[0].Y, scaledDockedDistance, hullRects[0].Height); hullRects[1] = new Rectangle(hullRects[1].Center.X - scaledDockedDistance, hullRects[1].Y, scaledDockedDistance, hullRects[1].Height); //expand hulls if needed, so there's no empty space between the sub's hulls and docking port hulls int leftSubRightSide = int.MinValue, rightSubLeftSide = int.MaxValue; foreach (Hull hull in Hull.hullList) { for (int i = 0; i < 2; i++) { if (hull.Submarine != subs[i]) { continue; } if (hull.WorldRect.Y - 5 < hullRects[i].Y - hullRects[i].Height) { continue; } if (hull.WorldRect.Y - hull.WorldRect.Height + 5 > hullRects[i].Y) { continue; } if (i == 0) //left hull { if (hull.WorldPosition.X > hullRects[0].Center.X) { continue; } leftSubRightSide = Math.Max(hull.WorldRect.Right, leftSubRightSide); } else //upper hull { if (hull.WorldPosition.X < hullRects[1].Center.X) { continue; } rightSubLeftSide = Math.Min(hull.WorldRect.X, rightSubLeftSide); } } } if (leftSubRightSide == int.MinValue || rightSubLeftSide == int.MaxValue) { DebugConsole.NewMessage("Creating hulls between docking ports failed. Could not find a hull next to the docking port."); return; } //expand left hull to the rightmost hull of the sub at the left side //(unless the difference is more than 100 units - if the distance is very large //there's something wrong with the positioning of the docking ports or submarine hulls) int leftHullDiff = (hullRects[0].X - leftSubRightSide) + 5; if (leftHullDiff > 0) { if (leftHullDiff > 100) { DebugConsole.NewMessage("Creating hulls between docking ports failed. The leftmost docking port seems to be very far from any hulls in the left-side submarine."); return; } else { hullRects[0].X -= leftHullDiff; hullRects[0].Width += leftHullDiff; } } int rightHullDiff = (rightSubLeftSide - hullRects[1].Right) + 5; if (rightHullDiff > 0) { if (rightHullDiff > 100) { DebugConsole.NewMessage("Creating hulls between docking ports failed. The rightmost docking port seems to be very far from any hulls in the right-side submarine."); return; } else { hullRects[1].Width += rightHullDiff; } } int expand = 5; for (int i = 0; i < 2; i++) { hullRects[i].X -= expand; hullRects[i].Width += expand * 2; hullRects[i].Location -= MathUtils.ToPoint((subs[i].WorldPosition - subs[i].HiddenSubPosition)); hulls[i] = new Hull(MapEntityPrefab.Find(null, "hull"), hullRects[i], subs[i]); hulls[i].AddToGrid(subs[i]); hulls[i].FreeID(); for (int j = 0; j < 2; j++) { bodies[i + j * 2] = GameMain.World.CreateEdge( ConvertUnits.ToSimUnits(new Vector2(hullRects[i].X, hullRects[i].Y - hullRects[i].Height * j)), ConvertUnits.ToSimUnits(new Vector2(hullRects[i].Right, hullRects[i].Y - hullRects[i].Height * j))); } } if (rightHullDiff <= 100 && hulls[0].Submarine != null) { outsideBlocker = hulls[0].Submarine.PhysicsBody.FarseerBody.CreateRectangle( ConvertUnits.ToSimUnits(hullRects[0].Width + hullRects[1].Width), ConvertUnits.ToSimUnits(hullRects[0].Height), density: 0.0f, offset: ConvertUnits.ToSimUnits(new Vector2(hullRects[0].Right, hullRects[0].Y - hullRects[0].Height / 2) - hulls[0].Submarine.HiddenSubPosition)); outsideBlocker.UserData = this; } gap = new Gap(new Rectangle(hullRects[0].Right - 2, hullRects[0].Y, 4, hullRects[0].Height), true, subs[0]); } else { if (hullRects[0].Center.Y > hullRects[1].Center.Y) { hullRects = new Rectangle[] { DockingTarget.item.WorldRect, item.WorldRect }; subs = new Submarine[] { DockingTarget.item.Submarine, item.Submarine }; } int scaledDockedDistance = (int)(DockedDistance / 2 * item.Scale); hullRects[0] = new Rectangle(hullRects[0].X, hullRects[0].Y - hullRects[0].Height / 2 + scaledDockedDistance, hullRects[0].Width, scaledDockedDistance); hullRects[1] = new Rectangle(hullRects[1].X, hullRects[1].Y - hullRects[1].Height / 2, hullRects[1].Width, scaledDockedDistance); //expand hulls if needed, so there's no empty space between the sub's hulls and docking port hulls int upperSubBottom = int.MaxValue, lowerSubTop = int.MinValue; foreach (Hull hull in Hull.hullList) { for (int i = 0; i < 2; i++) { if (hull.Submarine != subs[i]) { continue; } if (hull.WorldRect.Right - 5 < hullRects[i].X) { continue; } if (hull.WorldRect.X + 5 > hullRects[i].Right) { continue; } if (i == 0) //lower hull { if (hull.WorldPosition.Y > hullRects[i].Y - hullRects[i].Height / 2) { continue; } lowerSubTop = Math.Max(hull.WorldRect.Y, lowerSubTop); } else //upper hull { if (hull.WorldPosition.Y < hullRects[i].Y - hullRects[i].Height / 2) { continue; } upperSubBottom = Math.Min(hull.WorldRect.Y - hull.WorldRect.Height, upperSubBottom); } } } if (upperSubBottom == int.MaxValue || lowerSubTop == int.MinValue) { DebugConsole.NewMessage("Creating hulls between docking ports failed. Could not find a hull next to the docking port."); return; } //expand lower hull to the topmost hull of the lower sub //(unless the difference is more than 100 units - if the distance is very large //there's something wrong with the positioning of the docking ports or submarine hulls) int lowerHullDiff = ((hullRects[0].Y - hullRects[0].Height) - lowerSubTop) + 5; if (lowerHullDiff > 0) { if (lowerHullDiff > 100) { DebugConsole.NewMessage("Creating hulls between docking ports failed. The lower docking port seems to be very far from any hulls in the lower submarine."); return; } else { hullRects[0].Height += lowerHullDiff; } } int upperHullDiff = (upperSubBottom - hullRects[1].Y) + 5; if (upperHullDiff > 0) { if (upperHullDiff > 100) { DebugConsole.NewMessage("Creating hulls between docking ports failed. The upper docking port seems to be very far from any hulls in the upper submarine."); return; } else { hullRects[1].Y += upperHullDiff; hullRects[1].Height += upperHullDiff; } } //difference between the edges of the hulls (to avoid a gap between the hulls) //0 is lower int midHullDiff = ((hullRects[1].Y - hullRects[1].Height) - hullRects[0].Y) + 2; if (midHullDiff > 100) { DebugConsole.NewMessage("Creating hulls between docking ports failed. The upper hull seems to be very far from the lower hull."); return; } else if (midHullDiff > 0) { hullRects[0].Height += midHullDiff / 2 + 1; hullRects[1].Y -= midHullDiff / 2 + 1; hullRects[1].Height += midHullDiff / 2 + 1; } int expand = 5; for (int i = 0; i < 2; i++) { hullRects[i].Y += expand; hullRects[i].Height += expand * 2; hullRects[i].Location -= MathUtils.ToPoint((subs[i].WorldPosition - subs[i].HiddenSubPosition)); hulls[i] = new Hull(MapEntityPrefab.Find(null, "hull"), hullRects[i], subs[i]); hulls[i].AddToGrid(subs[i]); hulls[i].FreeID(); for (int j = 0; j < 2; j++) { bodies[i + j * 2] = GameMain.World.CreateEdge( ConvertUnits.ToSimUnits(new Vector2(hullRects[i].X + hullRects[i].Width * j, hullRects[i].Y)), ConvertUnits.ToSimUnits(new Vector2(hullRects[i].X + hullRects[i].Width * j, hullRects[i].Y - hullRects[i].Height))); } } if (midHullDiff <= 100 && hulls[0].Submarine != null) { outsideBlocker = hulls[0].Submarine.PhysicsBody.FarseerBody.CreateRectangle( ConvertUnits.ToSimUnits(hullRects[0].Width), ConvertUnits.ToSimUnits(hullRects[0].Height + hullRects[1].Height), density: 0.0f, offset: ConvertUnits.ToSimUnits(new Vector2(hullRects[0].Center.X, hullRects[0].Y) - hulls[0].Submarine.HiddenSubPosition)); outsideBlocker.UserData = this; } gap = new Gap(new Rectangle(hullRects[0].X, hullRects[0].Y + 2, hullRects[0].Width, 4), false, subs[0]); } LinkHullsToGaps(); hulls[0].ShouldBeSaved = false; hulls[1].ShouldBeSaved = false; item.linkedTo.Add(hulls[0]); item.linkedTo.Add(hulls[1]); gap.FreeID(); gap.DisableHullRechecks = true; gap.ShouldBeSaved = false; item.linkedTo.Add(gap); foreach (Body body in bodies) { if (body == null) { continue; } body.BodyType = BodyType.Static; body.Friction = 0.5f; body.CollisionCategories = Physics.CollisionWall; } }
public void Init(ParticlePrefab prefab, Vector2 position, Vector2 speed, float rotation, Hull hullGuess = null, bool drawOnTop = false) { this.prefab = prefab; spriteIndex = Rand.Int(prefab.Sprites.Count); animState = 0; animFrame = 0; dragWait = 0; dragVec = Vector2.Zero; currentHull = Hull.FindHull(position, hullGuess); this.position = position; prevPosition = position; drawPosition = position; velocity = MathUtils.IsValid(speed) ? speed : Vector2.Zero; if (currentHull?.Submarine != null) { velocity += ConvertUnits.ToDisplayUnits(currentHull.Submarine.Velocity); } this.rotation = rotation + Rand.Range(prefab.StartRotationMinRad, prefab.StartRotationMaxRad); prevRotation = rotation; angularVelocity = Rand.Range(prefab.AngularVelocityMinRad, prefab.AngularVelocityMaxRad); totalLifeTime = prefab.LifeTime; lifeTime = prefab.LifeTime; startDelay = Rand.Range(prefab.StartDelayMin, prefab.StartDelayMax); size = prefab.StartSizeMin + (prefab.StartSizeMax - prefab.StartSizeMin) * Rand.Range(0.0f, 1.0f); sizeChange = prefab.SizeChangeMin + (prefab.SizeChangeMax - prefab.SizeChangeMin) * Rand.Range(0.0f, 1.0f); color = prefab.StartColor; changeColor = prefab.StartColor != prefab.EndColor; velocityChange = prefab.VelocityChangeDisplay; velocityChangeWater = prefab.VelocityChangeWaterDisplay; HighQualityCollisionDetection = false; OnChangeHull = null; subEmitters.Clear(); hasSubEmitters = false; foreach (ParticleEmitterPrefab emitterPrefab in prefab.SubEmitters) { subEmitters.Add(new ParticleEmitter(emitterPrefab)); hasSubEmitters = true; } if (prefab.UseCollision) { hullGaps = currentHull == null ? new List <Gap>() : currentHull.ConnectedGaps; } if (prefab.RotateToDirection) { this.rotation = MathUtils.VectorToAngle(new Vector2(velocity.X, -velocity.Y)); prevRotation = rotation; } DrawOnTop = drawOnTop; }
/// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); var blockTexture = Content.Load <Texture2D>("Square"); _sprites = new List <Sprite>() { new Player(Content.Load <Texture2D>("Ball")) { Position = new Vector2(125, 125), Colour = Color.Green, }, new Sprite(blockTexture) { Position = new Vector2(25, 75), }, new Door(Content.Load <Texture2D>("Door/Frame")) { ActualDoor = new Sprite(Content.Load <Texture2D>("Door/Door")) { IsVisible = false, }, Position = new Vector2(75, 75), }, new Sprite(blockTexture) { Position = new Vector2(125, 75), }, new Sprite(blockTexture) { Position = new Vector2(175, 75), }, new Door(Content.Load <Texture2D>("Door/Frame")) { ActualDoor = new Sprite(Content.Load <Texture2D>("Door/Door")) { IsVisible = false, }, Rotatation = MathHelper.ToRadians(90), Position = new Vector2(175, 125), }, new Sprite(blockTexture) { Position = new Vector2(175, 175), }, }; foreach (var sprite in _sprites) { if (sprite is Player) { continue; } if (sprite is Door) { continue; } Hull hull = GetHull(sprite); _penumbra.Hulls.Add(hull); } _playerLight = new PointLight() { Radius = 5, Scale = new Vector2(350), }; _penumbra.Lights.Add(_playerLight); }
public override void UpdateHUD(Character character, float deltaTime, Camera cam) { if (character == null || !character.IsKeyDown(InputType.Aim)) { return; } if (PlayerInput.KeyHit(InputType.PreviousFireMode)) { if (spraySetting > 0) { spraySetting--; } else { spraySetting = 2; } targetSections.Clear(); } if (PlayerInput.KeyHit(InputType.NextFireMode)) { if (spraySetting < 2) { spraySetting++; } else { spraySetting = 0; } targetSections.Clear(); } crosshairPointerPos = PlayerInput.MousePosition; Vector2 rayStart; Vector2 sourcePos = character?.AnimController == null ? item.SimPosition : character.AnimController.AimSourceSimPos; Vector2 barrelPos = item.SimPosition + TransformedBarrelPos; //make sure there's no obstacles between the base of the item (or the shoulder of the character) and the end of the barrel if (Submarine.PickBody(sourcePos, barrelPos, collisionCategory: Physics.CollisionItem | Physics.CollisionItemBlocking | Physics.CollisionWall) == null) { //no obstacles -> we start the raycast at the end of the barrel rayStart = ConvertUnits.ToSimUnits(item.WorldPosition) + TransformedBarrelPos; } else { targetHull = null; targetSections.Clear(); return; } Vector2 pos = character.CursorWorldPosition; Vector2 rayEnd = ConvertUnits.ToSimUnits(pos); rayStartWorldPosition = ConvertUnits.ToDisplayUnits(rayStart); if (Vector2.Distance(rayStartWorldPosition, pos) > Range) { targetHull = null; targetSections.Clear(); return; } #if DEBUG debugRayStartPos = ConvertUnits.ToDisplayUnits(rayStart); debugRayEndPos = ConvertUnits.ToDisplayUnits(rayEnd); #endif Submarine parentSub = character.Submarine ?? item.Submarine; if (parentSub != null) { rayStart -= parentSub.SimPosition; rayEnd -= parentSub.SimPosition; } var obstacles = Submarine.PickBodies(rayStart, rayEnd, collisionCategory: Physics.CollisionItem | Physics.CollisionItemBlocking | Physics.CollisionWall); foreach (var body in obstacles) { if (body.UserData is Item item) { var door = item.GetComponent <Door>(); if (door != null && door.CanBeTraversed) { continue; } } targetHull = null; targetSections.Clear(); return; } targetHull = Hull.GetCleanTarget(pos); if (targetHull == null) { targetSections.Clear(); return; } BackgroundSection mousedOverSection = targetHull.GetBackgroundSection(pos); if (mousedOverSection == null) { targetSections.Clear(); return; } // No need to refresh if (targetSections.Count > 0 && mousedOverSection == targetSections[0]) { return; } targetSections.Clear(); targetSections.Add(mousedOverSection); int mousedOverIndex = mousedOverSection.Index; // Start with 2x2 if (spraySetting > 0) { sprayArray[0].X = mousedOverIndex + 1; sprayArray[0].Y = mousedOverSection.RowIndex; sprayArray[1].X = mousedOverIndex + targetHull.xBackgroundMax; sprayArray[1].Y = mousedOverSection.RowIndex + 1; sprayArray[2].X = sprayArray[1].X + 1; sprayArray[2].Y = sprayArray[1].Y; for (int i = 0; i < 3; i++) { if (targetHull.DoesSectionMatch(sprayArray[i].X, sprayArray[i].Y)) { targetSections.Add(targetHull.BackgroundSections[sprayArray[i].X]); } } // Add more if it's 3x3 if (spraySetting == 2) { sprayArray[3].X = mousedOverIndex - 1; sprayArray[3].Y = mousedOverSection.RowIndex; sprayArray[4].X = sprayArray[1].X - 1; sprayArray[4].Y = sprayArray[1].Y; sprayArray[5].X = sprayArray[3].X - targetHull.xBackgroundMax; sprayArray[5].Y = sprayArray[3].Y - 1; sprayArray[6].X = sprayArray[5].X + 1; sprayArray[6].Y = sprayArray[5].Y; sprayArray[7].X = sprayArray[6].X + 1; sprayArray[7].Y = sprayArray[6].Y; for (int i = 3; i < sprayArray.Length; i++) { if (targetHull.DoesSectionMatch(sprayArray[i].X, sprayArray[i].Y)) { targetSections.Add(targetHull.BackgroundSections[sprayArray[i].X]); } } } } }
/// <summary> /// Constructs a new ball. /// </summary> /// <param name="initialPosition">The initial position of the ball.</param> /// <param name="initialOrientation">The initial orientation of the ball.</param> /// <param name="mass">The mass of the ball.</param> /// <param name="ballRadius">The radius of the ball.</param> /// <param name="ballHull">The ball's hull.</param> /// <param name="collisionHandler">The ball's collision handler.</param> /// <param name="physics">The physics engine environment to which the ball belongs.</param> /// <param name="airResistance">The air resistance of the ball.</param> /// <param name="number">The ball's number.</param> /// <param name="ballModel">The ball's model.</param> public Ball(Vector3 initialPosition, Vector3 initialOrientation, float mass, float ballRadius, Hull ballHull, CollisionHandler collisionHandler, PhysicsEngine.Environment physics, float airResistance, int number, Model ballModel) { physicsReference = new BallEntity(initialPosition, initialOrientation, mass, ballRadius, ballHull, collisionHandler, physics, airResistance); physics.Add(physicsReference); this.number = number; this.ballModel = ballModel; }
public override void OnInspectorGUI() { //DrawDefaultInspector(); HullTable hullTable = target as HullTable; if (!hullTable) { return; } float PosY = 50f; EditorGUI.LabelField(new Rect(0f, PosY, Screen.width * .25f, EditorGUIUtility.singleLineHeight), "ID"); EditorGUI.LabelField(new Rect(Screen.width * .26f, PosY, Screen.width * .7f, EditorGUIUtility.singleLineHeight), "Hull"); if(hullTable.Hull_id_List==null) { Debug.Log("hull table null"); } for (int i = 0; i < hullTable.Hull_id_List.Count; i++) { HullTableEntry entry = hullTable.Hull_id_List[i]; PosY += EditorGUIUtility.singleLineHeight ; if (GUI.Button(new Rect(0.0f, PosY, Screen.width * rectXPos.x, EditorGUIUtility.singleLineHeight), "X")) { hullTable.RemoveEntry(entry.ID); EditorUtility.SetDirty(hullTable); } EditorGUI.IntField(new Rect(Screen.width * (rectXPos.x + spacing), PosY, Screen.width * rectXPos.y, EditorGUIUtility.singleLineHeight), entry.ID); EditorGUI.ObjectField(new Rect(Screen.width * (rectXPos.y + spacing), PosY, Screen.width * rectXPos.z, EditorGUIUtility.singleLineHeight), entry.hull, typeof(Hull), true); } for (int i = 0; i < 5 + hullTable.Hull_id_List.Count * EditorGUIUtility.singleLineHeight / 6; i++) { EditorGUILayout.Space(); } EditorGUILayout.LabelField("Add new entry to Hull Table"); id = EditorGUILayout.IntField("ID", id); if (hullTable.IDExists(id)) { EditorGUILayout.HelpBox("ID already exists in table", MessageType.Error, true); } EditorGUILayout.LabelField("Hull Prefab"); hull = EditorGUILayout.ObjectField(hull, typeof(Hull), false) as Hull; if(!hull) { EditorGUILayout.HelpBox("Please assign a hull", MessageType.Info, true); } else if(hullTable.HullExists(hull)) { EditorGUILayout.HelpBox("Hull already exists in table", MessageType.Warning, true); } if (GUILayout.Button("Auto Generate ID and Add")) { if (hull) { hullTable.AutoGenIDAndAdd(hull); id = hullTable.GenNextID(); EditorUtility.SetDirty(hullTable); Clear(); } else { EditorGUILayout.HelpBox("No hull assigned", MessageType.Error, true); Debug.LogError("No hull assigned", this); } } if(GUILayout.Button("Add Entry")) { if (hull) { hullTable.AddEntry(id, hull); id = hullTable.GenNextID(); EditorUtility.SetDirty(hullTable); Clear(); } else { EditorGUILayout.HelpBox("No hull assigned", MessageType.Error, true); Debug.LogError("No hull assigned", this); } } if(GUILayout.Button("Wipe Table")) { if(EditorUtility.DisplayDialog("Confirm Wipe", "Are you sure you want to wipe the hull table?", "Wipe", "Cancel")) { hullTable.WipeTable(); EditorUtility.SetDirty(hullTable); Clear(); } } }
private void DrawHUDBack(SpriteBatch spriteBatch, GUICustomComponent container) { Hull mouseOnHull = null; hullInfoFrame.Visible = false; foreach (Hull hull in Hull.hullList) { var hullFrame = submarineContainer.Children.First().FindChild(hull); if (hullFrame == null) { continue; } if (GUI.MouseOn == hullFrame || hullFrame.IsParentOf(GUI.MouseOn)) { mouseOnHull = hull; } if (item.Submarine == null || !hasPower) { hullFrame.Color = Color.DarkCyan * 0.3f; hullFrame.Children.First().Color = Color.DarkCyan * 0.3f; } } if (voltage < minVoltage) { return; } float scale = 1.0f; HashSet <Submarine> subs = new HashSet <Submarine>(); foreach (Hull hull in Hull.hullList) { if (hull.Submarine == null) { continue; } var hullFrame = submarineContainer.Children.First().FindChild(hull); if (hullFrame == null) { continue; } hullDatas.TryGetValue(hull, out HullData hullData); if (hullData == null) { hullData = new HullData(); GetLinkedHulls(hull, hullData.LinkedHulls); hullDatas.Add(hull, hullData); } Color neutralColor = Color.DarkCyan; if (hull.RoomName != null) { if (hull.RoomName.Contains("ballast") || hull.RoomName.Contains("Ballast") || hull.RoomName.Contains("airlock") || hull.RoomName.Contains("Airlock")) { neutralColor = new Color(9, 80, 159); } } if (hullData.Distort) { hullFrame.Children.First().Color = Color.Lerp(Color.Black, Color.DarkGray * 0.5f, Rand.Range(0.0f, 1.0f)); hullFrame.Color = neutralColor * 0.5f; continue; } subs.Add(hull.Submarine); scale = Math.Min( hullFrame.Parent.Rect.Width / (float)hull.Submarine.Borders.Width, hullFrame.Parent.Rect.Height / (float)hull.Submarine.Borders.Height); Color borderColor = neutralColor; float?gapOpenSum = 0.0f; if (ShowHullIntegrity) { gapOpenSum = hull.ConnectedGaps.Where(g => !g.IsRoomToRoom).Sum(g => g.Open); borderColor = Color.Lerp(neutralColor, Color.Red, Math.Min((float)gapOpenSum, 1.0f)); } float?oxygenAmount = null; if (!RequireOxygenDetectors || hullData?.Oxygen != null) { oxygenAmount = RequireOxygenDetectors ? hullData.Oxygen : hull.OxygenPercentage; GUI.DrawRectangle( spriteBatch, hullFrame.Rect, Color.Lerp(Color.Red * 0.5f, Color.Green * 0.3f, (float)oxygenAmount / 100.0f), true); } float?waterAmount = null; if (!RequireWaterDetectors || hullData.Water != null) { waterAmount = RequireWaterDetectors ? hullData.Water : Math.Min(hull.WaterVolume / hull.Volume, 1.0f); if (hullFrame.Rect.Height * waterAmount > 3.0f) { Rectangle waterRect = new Rectangle( hullFrame.Rect.X, (int)(hullFrame.Rect.Y + hullFrame.Rect.Height * (1.0f - waterAmount)), hullFrame.Rect.Width, (int)(hullFrame.Rect.Height * waterAmount)); waterRect.Inflate(-3, -3); GUI.DrawRectangle(spriteBatch, waterRect, new Color(85, 136, 147), true); GUI.DrawLine(spriteBatch, new Vector2(waterRect.X, waterRect.Y), new Vector2(waterRect.Right, waterRect.Y), Color.LightBlue); } } if (mouseOnHull == hull || hullData.LinkedHulls.Contains(mouseOnHull)) { borderColor = Color.Lerp(borderColor, Color.White, 0.5f); hullFrame.Children.First().Color = Color.White; hullFrame.Color = borderColor; } else { hullFrame.Children.First().Color = neutralColor * 0.8f; } if (mouseOnHull == hull) { hullInfoFrame.RectTransform.ScreenSpaceOffset = hullFrame.Rect.Center; hullInfoFrame.Visible = true; hullNameText.Text = hull.DisplayName; foreach (Hull linkedHull in hullData.LinkedHulls) { gapOpenSum += linkedHull.ConnectedGaps.Where(g => !g.IsRoomToRoom).Sum(g => g.Open); oxygenAmount += linkedHull.OxygenPercentage; waterAmount += Math.Min(linkedHull.WaterVolume / linkedHull.Volume, 1.0f); } oxygenAmount /= (hullData.LinkedHulls.Count + 1); waterAmount /= (hullData.LinkedHulls.Count + 1); hullBreachText.Text = gapOpenSum > 0.1f ? TextManager.Get("MiniMapHullBreach") : ""; hullBreachText.TextColor = Color.Red; hullAirQualityText.Text = oxygenAmount == null?TextManager.Get("MiniMapAirQualityUnavailable") : TextManager.AddPunctuation(':', TextManager.Get("MiniMapAirQuality"), +(int)oxygenAmount + " %"); hullAirQualityText.TextColor = oxygenAmount == null ? Color.Red : Color.Lerp(Color.Red, Color.LightGreen, (float)oxygenAmount / 100.0f); hullWaterText.Text = waterAmount == null?TextManager.Get("MiniMapWaterLevelUnavailable") : TextManager.AddPunctuation(':', TextManager.Get("MiniMapWaterLevel"), (int)(waterAmount * 100.0f) + " %"); hullWaterText.TextColor = waterAmount == null ? Color.Red : Color.Lerp(Color.LightGreen, Color.Red, (float)waterAmount); } hullFrame.Color = borderColor; } foreach (Submarine sub in subs) { if (sub.HullVertices == null) { continue; } Rectangle worldBorders = sub.GetDockedBorders(); worldBorders.Location += sub.WorldPosition.ToPoint(); scale = Math.Min( submarineContainer.Rect.Width / (float)worldBorders.Width, submarineContainer.Rect.Height / (float)worldBorders.Height) * 0.9f; float displayScale = ConvertUnits.ToDisplayUnits(scale); Vector2 offset = ConvertUnits.ToSimUnits(sub.WorldPosition - new Vector2(worldBorders.Center.X, worldBorders.Y - worldBorders.Height / 2)); Vector2 center = container.Rect.Center.ToVector2(); for (int i = 0; i < sub.HullVertices.Count; i++) { Vector2 start = (sub.HullVertices[i] + offset) * displayScale; start.Y = -start.Y; Vector2 end = (sub.HullVertices[(i + 1) % sub.HullVertices.Count] + offset) * displayScale; end.Y = -end.Y; GUI.DrawLine(spriteBatch, center + start, center + end, Color.DarkCyan * Rand.Range(0.3f, 0.35f), width: (int)(10 * GUI.Scale)); } } }
private void InitShip() { shipsHull = new Hull(); shipsWeapons = new Weapons(rand); shipShields = new Shield(); }
public void AddEntry(int _ID, Hull _hull) { if (Hull_id_List == null) { hull_id_List = new List<HullTableEntry>(); } Hull_id_List.Add(new HullTableEntry(_ID, _hull)); }
public bool HullExists(Hull _hull) { if (Hull_id_List == null) { return false; } return Hull_id_List.Any(entry => entry.hull == _hull); }
public override void Start() { base.Start(); radioSpeakerName = TextManager.Get("Tutorial.Radio.Speaker"); mechanic = Character.Controlled; var toolbelt = FindOrGiveItem(mechanic, "toolbelt"); toolbelt.Unequip(mechanic); mechanic.Inventory.RemoveItem(toolbelt); var crowbar = FindOrGiveItem(mechanic, "crowbar"); crowbar.Unequip(mechanic); mechanic.Inventory.RemoveItem(crowbar); var repairOrder = Order.GetPrefab("repairsystems"); mechanic_repairIcon = repairOrder.SymbolSprite; mechanic_repairIconColor = repairOrder.Color; mechanic_weldIcon = new Sprite("Content/UI/MainIconsAtlas.png", new Rectangle(1, 256, 127, 127), new Vector2(0.5f, 0.5f)); // Other tutorial items tutorial_securityFinalDoorLight = Item.ItemList.Find(i => i.HasTag("tutorial_securityfinaldoorlight")).GetComponent <LightComponent>(); tutorial_upperFinalDoor = Item.ItemList.Find(i => i.HasTag("tutorial_upperfinaldoor")).GetComponent <Door>(); tutorial_submarineSteering = Item.ItemList.Find(i => i.HasTag("command")).GetComponent <Steering>(); tutorial_submarineSteering.CanBeSelected = false; foreach (ItemComponent ic in tutorial_submarineSteering.Item.Components) { ic.CanBeSelected = false; } SetDoorAccess(null, tutorial_securityFinalDoorLight, false); SetDoorAccess(tutorial_upperFinalDoor, null, false); // Room 1 mechanic_firstDoor = Item.ItemList.Find(i => i.HasTag("mechanic_firstdoor")).GetComponent <Door>(); mechanic_firstDoorLight = Item.ItemList.Find(i => i.HasTag("mechanic_firstdoorlight")).GetComponent <LightComponent>(); SetDoorAccess(mechanic_firstDoor, mechanic_firstDoorLight, false); // Room 2 mechanic_equipmentObjectiveSensor = Item.ItemList.Find(i => i.HasTag("mechanic_equipmentobjectivesensor")).GetComponent <MotionSensor>(); mechanic_equipmentCabinet = Item.ItemList.Find(i => i.HasTag("mechanic_equipmentcabinet")).GetComponent <ItemContainer>(); mechanic_secondDoor = Item.ItemList.Find(i => i.HasTag("mechanic_seconddoor")).GetComponent <Door>(); mechanic_secondDoorLight = Item.ItemList.Find(i => i.HasTag("mechanic_seconddoorlight")).GetComponent <LightComponent>(); SetDoorAccess(mechanic_secondDoor, mechanic_secondDoorLight, false); // Room 3 mechanic_weldingObjectiveSensor = Item.ItemList.Find(i => i.HasTag("mechanic_weldingobjectivesensor")).GetComponent <MotionSensor>(); mechanic_workingPump = Item.ItemList.Find(i => i.HasTag("mechanic_workingpump")).GetComponent <Pump>(); mechanic_thirdDoor = Item.ItemList.Find(i => i.HasTag("mechanic_thirddoor")).GetComponent <Door>(); mechanic_thirdDoorLight = Item.ItemList.Find(i => i.HasTag("mechanic_thirddoorlight")).GetComponent <LightComponent>(); mechanic_brokenWall_1 = Structure.WallList.Find(i => i.SpecialTag == "mechanic_brokenwall_1"); //mechanic_ladderSensor = Item.ItemList.Find(i => i.HasTag("mechanic_laddersensor")).GetComponent<MotionSensor>(); SetDoorAccess(mechanic_thirdDoor, mechanic_thirdDoorLight, false); mechanic_brokenWall_1.Indestructible = false; mechanic_brokenWall_1.SpriteColor = Color.White; for (int i = 0; i < mechanic_brokenWall_1.SectionCount; i++) { mechanic_brokenWall_1.AddDamage(i, 85); } mechanic_brokenhull_1 = mechanic_brokenWall_1.Sections[0].gap.FlowTargetHull; // Room 4 mechanic_craftingObjectiveSensor = Item.ItemList.Find(i => i.HasTag("mechanic_craftingobjectivesensor")).GetComponent <MotionSensor>(); mechanic_deconstructor = Item.ItemList.Find(i => i.HasTag("mechanic_deconstructor")).GetComponent <Deconstructor>(); mechanic_fabricator = Item.ItemList.Find(i => i.HasTag("mechanic_fabricator")).GetComponent <Fabricator>(); mechanic_craftingCabinet = Item.ItemList.Find(i => i.HasTag("mechanic_craftingcabinet")).GetComponent <ItemContainer>(); mechanic_fourthDoor = Item.ItemList.Find(i => i.HasTag("mechanic_fourthdoor")).GetComponent <Door>(); mechanic_fourthDoorLight = Item.ItemList.Find(i => i.HasTag("mechanic_fourthdoorlight")).GetComponent <LightComponent>(); SetDoorAccess(mechanic_fourthDoor, mechanic_fourthDoorLight, false); // Room 5 mechanic_fifthDoor = Item.ItemList.Find(i => i.HasTag("mechanic_fifthdoor")).GetComponent <Door>(); mechanic_fifthDoorLight = Item.ItemList.Find(i => i.HasTag("mechanic_fifthdoorlight")).GetComponent <LightComponent>(); mechanic_fireSensor = Item.ItemList.Find(i => i.HasTag("mechanic_firesensor")).GetComponent <MotionSensor>(); SetDoorAccess(mechanic_fifthDoor, mechanic_fifthDoorLight, false); // Room 6 mechanic_divingSuitObjectiveSensor = Item.ItemList.Find(i => i.HasTag("mechanic_divingsuitobjectivesensor")).GetComponent <MotionSensor>(); mechanic_divingSuitContainer = Item.ItemList.Find(i => i.HasTag("mechanic_divingsuitcontainer")).GetComponent <ItemContainer>(); for (int i = 0; i < mechanic_divingSuitContainer.Inventory.Items.Length; i++) { foreach (ItemComponent ic in mechanic_divingSuitContainer.Inventory.Items[i].Components) { ic.CanBePicked = true; } } mechanic_oxygenContainer = Item.ItemList.Find(i => i.HasTag("mechanic_oxygencontainer")).GetComponent <ItemContainer>(); for (int i = 0; i < mechanic_oxygenContainer.Inventory.Items.Length; i++) { foreach (ItemComponent ic in mechanic_oxygenContainer.Inventory.Items[i].Components) { ic.CanBePicked = true; } } tutorial_mechanicFinalDoor = Item.ItemList.Find(i => i.HasTag("tutorial_mechanicfinaldoor")).GetComponent <Door>(); tutorial_mechanicFinalDoorLight = Item.ItemList.Find(i => i.HasTag("tutorial_mechanicfinaldoorlight")).GetComponent <LightComponent>(); SetDoorAccess(tutorial_mechanicFinalDoor, tutorial_mechanicFinalDoorLight, false); // Room 7 mechanic_brokenPump = Item.ItemList.Find(i => i.HasTag("mechanic_brokenpump")).GetComponent <Pump>(); mechanic_brokenPump.Item.Indestructible = false; mechanic_brokenPump.Item.Condition = 0; mechanic_brokenPump.CanBeSelected = false; mechanic_brokenPump.Item.GetComponent <Repairable>().CanBeSelected = false; mechanic_brokenWall_2 = Structure.WallList.Find(i => i.SpecialTag == "mechanic_brokenwall_2"); tutorial_submarineDoor = Item.ItemList.Find(i => i.HasTag("tutorial_submarinedoor")).GetComponent <Door>(); tutorial_submarineDoorLight = Item.ItemList.Find(i => i.HasTag("tutorial_submarinedoorlight")).GetComponent <LightComponent>(); mechanic_brokenWall_2.Indestructible = false; mechanic_brokenWall_2.SpriteColor = Color.White; for (int i = 0; i < mechanic_brokenWall_2.SectionCount; i++) { mechanic_brokenWall_2.AddDamage(i, 85); } mechanic_brokenhull_2 = mechanic_brokenWall_2.Sections[0].gap.FlowTargetHull; SetDoorAccess(tutorial_submarineDoor, tutorial_submarineDoorLight, false); // Submarine tutorial_enteredSubmarineSensor = Item.ItemList.Find(i => i.HasTag("tutorial_enteredsubmarinesensor")).GetComponent <MotionSensor>(); mechanic_submarineEngine = Item.ItemList.Find(i => i.HasTag("mechanic_submarineengine")).GetComponent <Engine>(); mechanic_submarineEngine.Item.Indestructible = false; mechanic_submarineEngine.Item.Condition = 0f; mechanic_ballastPump_1 = Item.ItemList.Find(i => i.HasTag("mechanic_ballastpump_1")).GetComponent <Pump>(); mechanic_ballastPump_1.Item.Indestructible = false; mechanic_ballastPump_1.Item.Condition = 0f; mechanic_ballastPump_2 = Item.ItemList.Find(i => i.HasTag("mechanic_ballastpump_2")).GetComponent <Pump>(); mechanic_ballastPump_2.Item.Indestructible = false; mechanic_ballastPump_2.Item.Condition = 0f; }
private void VerifyHullContains(Hull hull, int idA, int idB) { if ( ((hull[0].pointsIndex == idA) && (hull[hull.Count - 1].pointsIndex == idB)) || ((hull[0].pointsIndex == idB) && (hull[hull.Count - 1].pointsIndex == idA))) return; for (int h = 0; h < hull.Count - 1; h++) { if (hull[h].pointsIndex == idA) { Debug.Assert(hull[h + 1].pointsIndex == idB); return; } else if (hull[h].pointsIndex == idB) { Debug.Assert(hull[h + 1].pointsIndex == idA); return; } } }
private TurnBasedUnit InstantiateShip(bool hullSpawnedAlready, ShipType shipType, Vector3 position, Quaternion rotation) { if (!hullSpawnedAlready) { hullBeingBuilt = GameObject.Instantiate(blueprintBeingBuilt.Hull, position, rotation) as Hull; #if FULL_DEBUG ||LOW_DEBUG if (!hullBeingBuilt) { Debug.LogError("ship null"); } #endif hullBeingBuilt.Init(); } for (int i = 0; i < blueprintBeingBuilt.Slot_component_table.Count; i++) { var slot_component = blueprintBeingBuilt.Slot_component_table.ElementAt(i); int slotIndex = slot_component.Key.index; #if !NO_DEBUG if (hullBeingBuilt.index_slot_table.ContainsKey(slotIndex)) { Transform slotTrans = hullBeingBuilt.index_slot_table[slotIndex].transform; ShipComponent builtComponent = GameObject.Instantiate(slot_component.Value, slotTrans.position, slotTrans.rotation) as ShipComponent; blueprintBeingBuilt.Slot_component_table[slot_component.Key] = builtComponent; builtComponent.transform.SetParent(slotTrans, true); builtComponent.Placement = slot_component.Key.Placement; builtComponent.CompSpecificType = slot_component.Value.CompSpecificType; slot_component.Key.InstalledComponent = slot_component.Value; } else { Debug.LogError("Slot " + slotIndex + " not found in Hull " + hullBeingBuilt.hullName); } #else Transform slotTrans = hullBeingBuilt.index_slot_table[slotIndex].transform; GameObject component = GameObject.Instantiate(slot_component.Value, slotTrans.position, slotTrans.rotation) as GameObject; component.transform.SetParent(slotTrans, true); #endif } return SetupScriptsOnShip(shipType); }
private void Repair(Vector2 rayStart, Vector2 rayEnd, float deltaTime, Character user, float degreeOfSuccess, List <Body> ignoredBodies) { var collisionCategories = Physics.CollisionWall | Physics.CollisionCharacter | Physics.CollisionItem | Physics.CollisionLevel | Physics.CollisionRepair; if (RepairMultiple) { var bodies = Submarine.PickBodies(rayStart, rayEnd, ignoredBodies, collisionCategories, ignoreSensors: false, allowInsideFixture: true); Type lastHitType = null; foreach (Body body in bodies) { Type bodyType = body.UserData?.GetType(); if (!RepairThroughWalls && bodyType != null && bodyType != lastHitType) { //stop the ray if it already hit a door/wall and is now about to hit some other type of entity if (lastHitType == typeof(Item) || lastHitType == typeof(Structure)) { break; } } if (FixBody(user, deltaTime, degreeOfSuccess, body)) { if (bodyType != null) { lastHitType = bodyType; } } } } else { FixBody(user, deltaTime, degreeOfSuccess, Submarine.PickBody(rayStart, rayEnd, ignoredBodies, collisionCategories, ignoreSensors: false, customPredicate: (Fixture f) => { return(f?.Body?.UserData != null); }, allowInsideFixture: true)); } if (ExtinguishAmount > 0.0f && item.CurrentHull != null) { fireSourcesInRange.Clear(); //step along the ray in 10% intervals, collecting all fire sources in the range for (float x = 0.0f; x <= Submarine.LastPickedFraction; x += 0.1f) { Vector2 displayPos = ConvertUnits.ToDisplayUnits(rayStart + (rayEnd - rayStart) * x); if (item.CurrentHull.Submarine != null) { displayPos += item.CurrentHull.Submarine.Position; } Hull hull = Hull.FindHull(displayPos, item.CurrentHull); if (hull == null) { continue; } foreach (FireSource fs in hull.FireSources) { if (fs.IsInDamageRange(displayPos, 100.0f) && !fireSourcesInRange.Contains(fs)) { fireSourcesInRange.Add(fs); } } } foreach (FireSource fs in fireSourcesInRange) { fs.Extinguish(deltaTime, ExtinguishAmount); } } }
public void ClientRead(ServerNetObject type, IReadMessage msg, float sendingTime) { bool launch = msg.ReadBoolean(); if (launch) { ushort userId = msg.ReadUInt16(); User = Entity.FindEntityByID(userId) as Character; Vector2 simPosition = new Vector2(msg.ReadSingle(), msg.ReadSingle()); float rotation = msg.ReadSingle(); if (User != null) { Shoot(User, simPosition, simPosition, rotation, ignoredBodies: User.AnimController.Limbs.Where(l => !l.IsSevered).Select(l => l.body.FarseerBody).ToList(), createNetworkEvent: false); } else { Launch(User, simPosition, rotation); } } bool isStuck = msg.ReadBoolean(); if (isStuck) { ushort submarineID = msg.ReadUInt16(); ushort hullID = msg.ReadUInt16(); Vector2 simPosition = new Vector2( msg.ReadSingle(), msg.ReadSingle()); Vector2 axis = new Vector2( msg.ReadSingle(), msg.ReadSingle()); UInt16 entityID = msg.ReadUInt16(); Entity entity = Entity.FindEntityByID(entityID); Submarine submarine = Entity.FindEntityByID(submarineID) as Submarine; Hull hull = Entity.FindEntityByID(hullID) as Hull; item.Submarine = submarine; item.CurrentHull = hull; item.body.SetTransform(simPosition, item.body.Rotation); if (entity is Character character) { byte limbIndex = msg.ReadByte(); if (limbIndex >= character.AnimController.Limbs.Length) { DebugConsole.ThrowError($"Failed to read a projectile update from the server. Limb index out of bounds ({limbIndex}, character: {character.ToString()})"); return; } if (character.Removed) { return; } var limb = character.AnimController.Limbs[limbIndex]; StickToTarget(limb.body.FarseerBody, axis); } else if (entity is Structure structure) { byte bodyIndex = msg.ReadByte(); if (bodyIndex == 255) { bodyIndex = 0; } if (bodyIndex >= structure.Bodies.Count) { DebugConsole.ThrowError($"Failed to read a projectile update from the server. Structure body index out of bounds ({bodyIndex}, structure: {structure.ToString()})"); return; } var body = structure.Bodies[bodyIndex]; StickToTarget(body, axis); } else if (entity is Item item) { if (item.Removed) { return; } var door = item.GetComponent <Door>(); if (door != null) { StickToTarget(door.Body.FarseerBody, axis); } else if (item.body != null) { StickToTarget(item.body.FarseerBody, axis); } } else if (entity is Submarine sub) { StickToTarget(sub.PhysicsBody.FarseerBody, axis); } else { DebugConsole.ThrowError($"Failed to read a projectile update from the server. Invalid stick target ({entity?.ToString() ?? "null"}, {entityID})"); } } else { Unstick(); } }
public void InstallModule(StarshipModule module, HullLocation location) { Hull.InstallModule(module, location); module.OnInstall(this); }
public void sendUserEquipmentOnEnterLobby(NodeAddedEvent e, UserInMatchMakingLobby user, [Context, JoinByUser] Weapon weapon, [Context, JoinByUser] Hull hull, [JoinByUser] UserInMatchMakingLobby user2Lobby, [JoinByBattleLobby] SingleNode <BattleLobbyComponent> lobby) { SetEquipmentEvent eventInstance = new SetEquipmentEvent { WeaponId = weapon.marketItemGroup.Key, HullId = hull.marketItemGroup.Key }; base.ScheduleEvent(eventInstance, lobby); user.Entity.RemoveComponentIfPresent <InitUserEquipmentComponent>(); user.Entity.AddComponent <InitUserEquipmentComponent>(); }
public int GetDir(DockingPort dockingTarget = null) { int forcedDockingDir = GetForcedDockingDir(); if (forcedDockingDir != 0) { return(forcedDockingDir); } if (dockingTarget != null) { forcedDockingDir = -dockingTarget.GetForcedDockingDir(); if (forcedDockingDir != 0) { return(forcedDockingDir); } } if (DockingDir != 0) { return(DockingDir); } if (Door != null && Door.LinkedGap.linkedTo.Count > 0) { Hull refHull = null; float largestHullSize = 0.0f; foreach (MapEntity linked in Door.LinkedGap.linkedTo) { if (!(linked is Hull hull)) { continue; } if (hull.Volume > largestHullSize) { refHull = hull; largestHullSize = hull.Volume; } } if (refHull != null) { return(IsHorizontal ? Math.Sign(Door.Item.WorldPosition.X - refHull.WorldPosition.X) : Math.Sign(Door.Item.WorldPosition.Y - refHull.WorldPosition.Y)); } } if (dockingTarget?.Door?.LinkedGap != null && dockingTarget.Door.LinkedGap.linkedTo.Count > 0) { Hull refHull = null; float largestHullSize = 0.0f; foreach (MapEntity linked in dockingTarget.Door.LinkedGap.linkedTo) { if (!(linked is Hull hull)) { continue; } if (hull.Volume > largestHullSize) { refHull = hull; largestHullSize = hull.Volume; } } if (refHull != null) { return(IsHorizontal ? Math.Sign(refHull.WorldPosition.X - dockingTarget.Door.Item.WorldPosition.X) : Math.Sign(refHull.WorldPosition.Y - dockingTarget.Door.Item.WorldPosition.Y)); } } if (dockingTarget != null) { int dir = IsHorizontal ? Math.Sign(dockingTarget.item.WorldPosition.X - item.WorldPosition.X) : Math.Sign(dockingTarget.item.WorldPosition.Y - item.WorldPosition.Y); if (dir != 0) { return(dir); } } if (item.Submarine != null) { return(IsHorizontal ? Math.Sign(item.WorldPosition.X - item.Submarine.WorldPosition.X) : Math.Sign(item.WorldPosition.Y - item.Submarine.WorldPosition.Y)); } return(0); }
private void CreateHull() { var hullRects = new Rectangle[] { item.WorldRect, dockingTarget.item.WorldRect }; var subs = new Submarine[] { item.Submarine, dockingTarget.item.Submarine }; hulls = new Hull[2]; bodies = new Body[4]; if (dockingTarget.door != null) { CreateDoorBody(); } if (door != null) { dockingTarget.CreateDoorBody(); } if (IsHorizontal) { if (hullRects[0].Center.X > hullRects[1].Center.X) { hullRects = new Rectangle[] { dockingTarget.item.WorldRect, item.WorldRect }; subs = new Submarine[] { dockingTarget.item.Submarine, item.Submarine }; } hullRects[0] = new Rectangle(hullRects[0].Center.X, hullRects[0].Y, ((int)DockedDistance / 2), hullRects[0].Height); hullRects[1] = new Rectangle(hullRects[1].Center.X - ((int)DockedDistance / 2), hullRects[1].Y, ((int)DockedDistance / 2), hullRects[1].Height); for (int i = 0; i < 2; i++) { hullRects[i].Location -= MathUtils.ToPoint((subs[i].WorldPosition - subs[i].HiddenSubPosition)); hulls[i] = new Hull(MapEntityPrefab.list.Find(m => m.Name == "Hull"), hullRects[i], subs[i]); hulls[i].AddToGrid(subs[i]); for (int j = 0; j < 2; j++) { bodies[i + j * 2] = BodyFactory.CreateEdge(GameMain.World, ConvertUnits.ToSimUnits(new Vector2(hullRects[i].X, hullRects[i].Y - hullRects[i].Height * j)), ConvertUnits.ToSimUnits(new Vector2(hullRects[i].Right, hullRects[i].Y - hullRects[i].Height * j))); } } gap = new Gap(new Rectangle(hullRects[0].Right - 2, hullRects[0].Y, 4, hullRects[0].Height), true, subs[0]); if (gapId != null) { gap.ID = (ushort)gapId; } LinkHullsToGap(); } else { if (hullRects[0].Center.Y > hullRects[1].Center.Y) { hullRects = new Rectangle[] { dockingTarget.item.WorldRect, item.WorldRect }; subs = new Submarine[] { dockingTarget.item.Submarine, item.Submarine }; } hullRects[0] = new Rectangle(hullRects[0].X, hullRects[0].Y + (int)(-hullRects[0].Height + DockedDistance) / 2, hullRects[0].Width, ((int)DockedDistance / 2)); hullRects[1] = new Rectangle(hullRects[1].X, hullRects[1].Y - hullRects[1].Height / 2, hullRects[1].Width, ((int)DockedDistance / 2)); for (int i = 0; i < 2; i++) { hullRects[i].Location -= MathUtils.ToPoint((subs[i].WorldPosition - subs[i].HiddenSubPosition)); hulls[i] = new Hull(MapEntityPrefab.list.Find(m => m.Name == "Hull"), hullRects[i], subs[i]); hulls[i].AddToGrid(subs[i]); if (hullIds[i] != null) { hulls[i].ID = (ushort)hullIds[i]; } } gap = new Gap(new Rectangle(hullRects[0].X, hullRects[0].Y + 2, hullRects[0].Width, 4), false, subs[0]); if (gapId != null) { gap.ID = (ushort)gapId; } LinkHullsToGap(); } item.linkedTo.Add(hulls[0]); item.linkedTo.Add(hulls[1]); hullIds[0] = hulls[0].ID; hullIds[1] = hulls[1].ID; gap.DisableHullRechecks = true; gapId = gap.ID; item.linkedTo.Add(gap); foreach (Body body in bodies) { if (body == null) { continue; } body.BodyType = BodyType.Static; body.Friction = 0.5f; body.CollisionCategories = Physics.CollisionWall; } }
private void Repair(Vector2 rayStart, Vector2 rayEnd, float deltaTime, Character user, float degreeOfSuccess, List <Body> ignoredBodies) { if (ExtinquishAmount > 0.0f && item.CurrentHull != null) { Vector2 displayPos = ConvertUnits.ToDisplayUnits(rayStart + (rayEnd - rayStart) * Submarine.LastPickedFraction * 0.9f); displayPos += item.CurrentHull.Submarine.Position; Hull hull = Hull.FindHull(displayPos, item.CurrentHull); if (hull != null) { hull.Extinguish(deltaTime, ExtinquishAmount, displayPos); if (hull != item.CurrentHull) { item.CurrentHull.Extinguish(deltaTime, ExtinquishAmount, displayPos); } } } Body targetBody = Submarine.PickBody(rayStart, rayEnd, ignoredBodies, Physics.CollisionWall | Physics.CollisionCharacter | Physics.CollisionItem | Physics.CollisionLevel | Physics.CollisionRepair, false); if (targetBody == null || targetBody.UserData == null) { return; } pickedPosition = Submarine.LastPickedPosition; Structure targetStructure; Limb targetLimb; Item targetItem; if ((targetStructure = (targetBody.UserData as Structure)) != null) { if (!fixableEntities.Contains("structure") && !fixableEntities.Contains(targetStructure.Name)) { return; } if (targetStructure.IsPlatform) { return; } int sectionIndex = targetStructure.FindSectionIndex(ConvertUnits.ToDisplayUnits(pickedPosition)); if (sectionIndex < 0) { return; } #if CLIENT Vector2 progressBarPos = targetStructure.SectionPosition(sectionIndex); if (targetStructure.Submarine != null) { progressBarPos += targetStructure.Submarine.DrawPosition; } var progressBar = user.UpdateHUDProgressBar( targetStructure, progressBarPos, 1.0f - targetStructure.SectionDamage(sectionIndex) / targetStructure.Health, Color.Red, Color.Green); if (progressBar != null) { progressBar.Size = new Vector2(60.0f, 20.0f); } Vector2 particlePos = ConvertUnits.ToDisplayUnits(pickedPosition); if (targetStructure.Submarine != null) { particlePos += targetStructure.Submarine.DrawPosition; } foreach (var emitter in ParticleEmitterHitStructure) { float particleAngle = item.body.Rotation + ((item.body.Dir > 0.0f) ? 0.0f : MathHelper.Pi); emitter.Emit(deltaTime, particlePos, item.CurrentHull, particleAngle + MathHelper.Pi, -particleAngle + MathHelper.Pi); } #endif targetStructure.AddDamage(sectionIndex, -StructureFixAmount * degreeOfSuccess, user); //if the next section is small enough, apply the effect to it as well //(to make it easier to fix a small "left-over" section) for (int i = -1; i < 2; i += 2) { int nextSectionLength = targetStructure.SectionLength(sectionIndex + i); if ((sectionIndex == 1 && i == -1) || (sectionIndex == targetStructure.SectionCount - 2 && i == 1) || (nextSectionLength > 0 && nextSectionLength < Structure.WallSectionSize * 0.3f)) { //targetStructure.HighLightSection(sectionIndex + i); targetStructure.AddDamage(sectionIndex + i, -StructureFixAmount * degreeOfSuccess); } } } else if ((targetLimb = (targetBody.UserData as Limb)) != null) { targetLimb.character.AddDamage(CauseOfDeath.Damage, -LimbFixAmount * degreeOfSuccess, user); #if CLIENT Vector2 particlePos = ConvertUnits.ToDisplayUnits(pickedPosition); if (targetLimb.character.Submarine != null) { particlePos += targetLimb.character.Submarine.DrawPosition; } foreach (var emitter in ParticleEmitterHitCharacter) { float particleAngle = item.body.Rotation + ((item.body.Dir > 0.0f) ? 0.0f : MathHelper.Pi); emitter.Emit(deltaTime, particlePos, item.CurrentHull, particleAngle + MathHelper.Pi, -particleAngle + MathHelper.Pi); } #endif } else if ((targetItem = (targetBody.UserData as Item)) != null) { targetItem.IsHighlighted = true; float prevCondition = targetItem.Condition; ApplyStatusEffectsOnTarget(deltaTime, ActionType.OnUse, targetItem.AllPropertyObjects); #if CLIENT if (item.Condition != prevCondition) { Vector2 progressBarPos = targetItem.DrawPosition; var progressBar = user.UpdateHUDProgressBar( targetItem, progressBarPos, targetItem.Condition / 100.0f, Color.Red, Color.Green); if (progressBar != null) { progressBar.Size = new Vector2(60.0f, 20.0f); } Vector2 particlePos = ConvertUnits.ToDisplayUnits(pickedPosition); if (targetItem.Submarine != null) { particlePos += targetItem.Submarine.DrawPosition; } foreach (var emitter in ParticleEmitterHitItem) { float particleAngle = item.body.Rotation + ((item.body.Dir > 0.0f) ? 0.0f : MathHelper.Pi); emitter.Emit(deltaTime, particlePos, item.CurrentHull, particleAngle + MathHelper.Pi, -particleAngle + MathHelper.Pi); } } #endif } }
/// <summary> /// Constructs a new BallEntity. /// </summary> /// <param name="position">The position of the ball.</param> /// <param name="orientation">The orientation of the ball.</param> /// <param name="mass">The mass of the ball.</param> /// <param name="boundingRadius">The bounding radius of the ball.</param> /// <param name="hull">The ball's hull.</param> /// <param name="collisionHandler">The ball's collision handler.</param> /// <param name="environment">The environment to which the ball belongs.</param> /// <param name="coefficientOfAirResistance">The air resistance coefficient of the ball.</param> public BallEntity(Vector3 position, Vector3 orientation, float mass, float boundingRadius, Hull hull, CollisionHandler collisionHandler, PhysicsEngine.Environment environment, float coefficientOfAirResistance) : base(position, orientation, mass, boundingRadius, hull, collisionHandler, environment, coefficientOfAirResistance) { }
public bool Update(float deltaTime) { prevPosition = position; prevRotation = rotation; //over 3 times faster than position += velocity * deltatime position.X += velocity.X * deltaTime; position.Y += velocity.Y * deltaTime; if (prefab.RotateToDirection) { if (velocityChange != Vector2.Zero || angularVelocity != 0.0f) { rotation = MathUtils.VectorToAngle(new Vector2(velocity.X, -velocity.Y)); } } else { rotation += angularVelocity * deltaTime; } if (prefab.WaterDrag > 0.0f && (currentHull == null || (currentHull.Submarine != null && position.Y - currentHull.Submarine.DrawPosition.Y < currentHull.Surface))) { ApplyDrag(prefab.WaterDrag, deltaTime); } else if (prefab.Drag > 0.0f) { ApplyDrag(prefab.Drag, deltaTime); } velocity.X += velocityChange.X * deltaTime; velocity.Y += velocityChange.Y * deltaTime; size.X += sizeChange.X * deltaTime; size.Y += sizeChange.Y * deltaTime; alpha += prefab.ColorChange.W * deltaTime; color = new Color( color.R / 255.0f + prefab.ColorChange.X * deltaTime, color.G / 255.0f + prefab.ColorChange.Y * deltaTime, color.B / 255.0f + prefab.ColorChange.Z * deltaTime); if (prefab.Sprites[spriteIndex] is SpriteSheet) { animState += deltaTime; int frameCount = ((SpriteSheet)prefab.Sprites[spriteIndex]).FrameCount; animFrame = (int)Math.Min(Math.Floor(animState / prefab.AnimDuration * frameCount), frameCount - 1); } lifeTime -= deltaTime; if (lifeTime <= 0.0f || alpha <= 0.0f || size.X <= 0.0f || size.Y <= 0.0f) { return(false); } if (!prefab.DeleteOnCollision && !prefab.CollidesWithWalls) { return(true); } if (currentHull == null) { Hull collidedHull = Hull.FindHull(position); if (collidedHull != null) { if (prefab.DeleteOnCollision) { return(false); } OnWallCollisionOutside(collidedHull); } } else { Vector2 collisionNormal = Vector2.Zero; if (velocity.Y < 0.0f && position.Y - prefab.CollisionRadius * size.Y < currentHull.WorldRect.Y - currentHull.WorldRect.Height) { if (prefab.DeleteOnCollision) { return(false); } collisionNormal = new Vector2(0.0f, 1.0f); } else if (velocity.Y > 0.0f && position.Y + prefab.CollisionRadius * size.Y > currentHull.WorldRect.Y) { if (prefab.DeleteOnCollision) { return(false); } collisionNormal = new Vector2(0.0f, -1.0f); } else if (velocity.X < 0.0f && position.X - prefab.CollisionRadius * size.X < currentHull.WorldRect.X) { if (prefab.DeleteOnCollision) { return(false); } collisionNormal = new Vector2(1.0f, 0.0f); } else if (velocity.X > 0.0f && position.X + prefab.CollisionRadius * size.X > currentHull.WorldRect.Right) { if (prefab.DeleteOnCollision) { return(false); } collisionNormal = new Vector2(-1.0f, 0.0f); } if (collisionNormal != Vector2.Zero) { bool gapFound = false; foreach (Gap gap in hullGaps) { if (gap.IsHorizontal != (collisionNormal.X != 0.0f)) { continue; } if (gap.IsHorizontal) { if (gap.WorldRect.Y < position.Y || gap.WorldRect.Y - gap.WorldRect.Height > position.Y) { continue; } int gapDir = Math.Sign(gap.WorldRect.Center.X - currentHull.WorldRect.Center.X); if (Math.Sign(velocity.X) != gapDir || Math.Sign(position.X - currentHull.WorldRect.Center.X) != gapDir) { continue; } } else { if (gap.WorldRect.X > position.X || gap.WorldRect.Right < position.X) { continue; } float hullCenterY = currentHull.WorldRect.Y - currentHull.WorldRect.Height / 2; int gapDir = Math.Sign(gap.WorldRect.Y - hullCenterY); if (Math.Sign(velocity.Y) != gapDir || Math.Sign(position.Y - hullCenterY) != gapDir) { continue; } } gapFound = true; break; } if (!gapFound) { OnWallCollisionInside(currentHull, collisionNormal); } else { Hull newHull = Hull.FindHull(position); if (newHull != currentHull) { currentHull = newHull; hullGaps = currentHull == null ? new List <Gap>() : currentHull.ConnectedGaps; OnChangeHull?.Invoke(position, currentHull); } } } } return(true); }
/// <summary> /// Constructs a new ball with default orientation, mass, radius, elasticity, and air resistance. /// </summary> /// <param name="initialPosition">The initial position of the ball.</param> /// <param name="physics">The physics engine environment to which the ball belongs.</param> /// <param name="ballHull">The ball's hull.</param> /// <param name="number">The ball's number.</param> /// <param name="ballModel">The ball's model.</param> public Ball(Vector3 initialPosition, PhysicsEngine.Environment physics, Hull ballHull, int number, Model ballModel) : this(initialPosition, GameVariables.initialBallOrientation, GameVariables.ballMass, GameVariables.ballRadius, ballHull, new ElasticCollision(GameVariables.ballElasticity), physics, GameVariables.ballAirResistance, number, ballModel) { }
public void Init(ParticlePrefab prefab, Vector2 position, Vector2 speed, float rotation, Hull hullGuess = null) { this.prefab = prefab; spriteIndex = Rand.Int(prefab.Sprites.Count); animState = 0; animFrame = 0; currentHull = Hull.FindHull(position, hullGuess); this.position = position; prevPosition = position; drawPosition = position; velocity = MathUtils.IsValid(speed) ? speed : Vector2.Zero; if (currentHull != null && currentHull.Submarine != null) { velocity += ConvertUnits.ToDisplayUnits(currentHull.Submarine.Velocity); } this.rotation = rotation + Rand.Range(prefab.StartRotationMinRad, prefab.StartRotationMaxRad); prevRotation = rotation; angularVelocity = Rand.Range(prefab.AngularVelocityMinRad, prefab.AngularVelocityMaxRad); totalLifeTime = prefab.LifeTime; lifeTime = prefab.LifeTime; size = prefab.StartSizeMin + (prefab.StartSizeMax - prefab.StartSizeMin) * Rand.Range(0.0f, 1.0f); sizeChange = prefab.SizeChangeMin + (prefab.SizeChangeMax - prefab.SizeChangeMin) * Rand.Range(0.0f, 1.0f); color = new Color(prefab.StartColor, 1.0f); alpha = prefab.StartAlpha; velocityChange = prefab.VelocityChangeDisplay; OnChangeHull = null; if (prefab.DeleteOnCollision || prefab.CollidesWithWalls) { hullGaps = currentHull == null ? new List <Gap>() : currentHull.ConnectedGaps; } if (prefab.RotateToDirection) { this.rotation = MathUtils.VectorToAngle(new Vector2(velocity.X, -velocity.Y)); prevRotation = rotation; } }
private Tuple <DynamicVao, DynamicVao> TryBuildVaoForLight(Light light) { _hullVertices.Clear(); _shadowVertices.Clear(); _shadowIndices.Clear(); _hullIndices.Clear(); int numSegments = 0; int shadowIndexOffset = 0; int hullIndexOffset = 0; int hullCount = _engine.Hulls.Count; for (int i = 0; i < hullCount; i++) { Hull hull = _engine.Hulls[i]; if (!hull.Enabled || !hull.Valid || light.IgnoredHulls.Contains(hull) || !light.Intersects(hull)) { continue; } Polygon points = hull.WorldPoints; Vector2 prevPoint = points[points.Count - 1]; int pointCount = points.Count; numSegments += pointCount; for (int j = 0; j < pointCount; j++) { Vector2 currentPoint = points[j]; _shadowVertices.Add(new VertexShadow(prevPoint, currentPoint, new Vector2(0.0f, 0.0f))); _shadowVertices.Add(new VertexShadow(prevPoint, currentPoint, new Vector2(1.0f, 0.0f))); _shadowVertices.Add(new VertexShadow(prevPoint, currentPoint, new Vector2(0.0f, 1.0f))); _shadowVertices.Add(new VertexShadow(prevPoint, currentPoint, new Vector2(1.0f, 1.0f))); _shadowIndices.Add(shadowIndexOffset * 4 + 0); _shadowIndices.Add(shadowIndexOffset * 4 + 1); _shadowIndices.Add(shadowIndexOffset * 4 + 2); _shadowIndices.Add(shadowIndexOffset * 4 + 1); _shadowIndices.Add(shadowIndexOffset * 4 + 3); _shadowIndices.Add(shadowIndexOffset * 4 + 2); prevPoint = currentPoint; shadowIndexOffset++; } _hullVertices.AddRange(hull.WorldPoints); int indexCount = hull.Indices.Count; for (int j = 0; j < indexCount; j++) { _hullIndices.Add(hull.Indices[j] + hullIndexOffset); } hullIndexOffset += pointCount; } if (numSegments == 0) { return(null); } Tuple <DynamicVao, DynamicVao> lightVaos; if (!_lightsVaos.TryGetValue(light, out lightVaos)) { lightVaos = Tuple.Create( DynamicVao.New(_engine.Device, VertexShadow.Layout, PrimitiveType.TriangleList, _shadowVertices.Count, _shadowIndices.Count, useIndices: true), DynamicVao.New(_engine.Device, VertexPosition2.Layout, PrimitiveType.TriangleList, _hullVertices.Count, _hullIndices.Count, useIndices: true)); _lightsVaos.Add(light, lightVaos); } lightVaos.Item1.SetVertices(_shadowVertices); lightVaos.Item1.SetIndices(_shadowIndices); lightVaos.Item2.SetVertices(_hullVertices); lightVaos.Item2.SetIndices(_hullIndices); return(lightVaos); }
private void GetHull() { hull1 = Hull.FindHull(item.WorldPosition, item.CurrentHull); }