public override void fire(Agent p, PhysicsEngine ph) { base.fire(p, ph); if (curCooldown == cooldown) { Random rand = new Random(); Vector3 [] dirs = new Vector3[5]; dirs[0] = Vector3.Normalize(p.getDirectionVector()); Vector3 right = Vector3.Cross(dirs[0], Vector3.Up); Vector3 up = Vector3.Cross(dirs[0], right); up *= 0.15f; right *= 0.15f; dirs[1] = dirs[0] + (float)rand.NextDouble() * right + (float)rand.NextDouble() * up; dirs[2] = dirs[0] + (float)rand.NextDouble() * right - (float)rand.NextDouble() * up; dirs[3] = dirs[0] - (float)rand.NextDouble() * right - (float)rand.NextDouble() * up; dirs[4] = dirs[0] - (float)rand.NextDouble() * right + (float)rand.NextDouble() * up; foreach(Vector3 dir in dirs) { List<Agent> l = new List<Agent>(); l.Add(p); PhysicsEngine.HitScan hs = ph.hitscan(p.getPosition() + new Vector3(0, 75, 0) + p.getDirectionVector() * 10, dir, null); PhysicsEngine.AgentHitScan ahs = ph.agentHitscan(p.getPosition() + new Vector3(0, 75, 0) + p.getDirectionVector() * 10, dir, l); if (hs != null && (ahs == null || hs.Distance() < ahs.Distance())) makeLaser(p, hs.ray, Vector3.Distance(hs.ray.Position, hs.collisionPoint), 5, 5, "Shotgun"); else if (ahs != null) { ahs.agent.dealDamage(damage, p); makeLaser(p, ahs.ray, Vector3.Distance(ahs.ray.Position, ahs.collisionPoint), 5, 5, "Shotgun"); } } } }
public override void fire(Agent p, PhysicsEngine ph) { base.fire(p, ph); if (curCooldown == cooldown) { Random rand = new Random(); Vector3 dir = Vector3.Normalize(p.getDirectionVector()); Vector3 right = Vector3.Cross(dir, Vector3.Up); Vector3 up = Vector3.Cross(dir, right); up *= inaccuracy; right *= inaccuracy; dir = dir + (float)(rand.NextDouble() * 2 - 1) * up + (float)(rand.NextDouble() * 2 - 1) * right; inaccuracy = Math.Min(maxInaccuracy, inaccruacyJump + inaccuracy); inaccuracyCurCooldown = 0; List<Agent> l = new List<Agent>(); l.Add(p); PhysicsEngine.HitScan hs = ph.hitscan(p.getPosition() + new Vector3(0, 75, 0) + p.getDirectionVector() * 10, p.getDirectionVector(), null); PhysicsEngine.AgentHitScan ahs = ph.agentHitscan(p.getPosition() + new Vector3(0, 60, 0) + p.getDirectionVector() * 10, dir, l); if (hs != null && (ahs == null || hs.Distance() < ahs.Distance())) makeLaser(p, hs.ray, Vector3.Distance(hs.ray.Position, hs.collisionPoint), 5, 5, "Rifle"); else if (ahs != null) { ahs.agent.dealDamage(damage, p); makeLaser(p, ahs.ray, Vector3.Distance(ahs.ray.Position, ahs.collisionPoint), 5, 5, "Rifle"); } } }
/// <summary> /// Initialization /// </summary> /// <param name="device"></param> /// <param name="physicsEngine"></param> public override void Initialize(xnagrfx.GraphicsDevice device, PhysicsEngine physicsEngine) { try { // GPS sensor dimensions and relative position _shape = new BoxShape(new BoxShapeProperties( "GPS Sensor", 0.01f, new Pose(new Vector3(0,0.8f,0)), new Vector3(0.01f, 0.01f, 0.01f))); State.PhysicsPrimitives.Add(_shape); base.Initialize(device, physicsEngine); if (Parent == null) { throw new Exception("GPS Sensor entity must be a child of another entity."); } CreateAndInsertPhysicsEntity(physicsEngine); Flags |= VisualEntityProperties.DisableRendering; AddShapeToPhysicsEntity(_shape, new VisualEntityMesh(device, 0.01f, 0.01f)); } catch (Exception ex) { HasBeenInitialized = false; InitError = ex.ToString(); } }
internal void OnAddedInternal(PhysicsEngine engine) { if (this.engine != null) { throw new InvalidOperationException(); } this.engine = engine; OnAdded(); this.AddBodyRange(engine.bodies); }
public override void fire(Agent p, PhysicsEngine ph) { base.fire(p, ph); if (curCooldown == cooldown) { PhysicsEngine.HitScan hs = ph.hitscan(p.getPosition() + new Vector3(0, 75, 0) + p.getDirectionVector() * 10, p.getDirectionVector(), null); if (hs != null) { makeRocket(p, hs.ray, Vector3.Distance(hs.ray.Position, hs.collisionPoint), 1200, 40); } } }
internal void OnAddedInternal(PhysicsEngine engine) { if (this.engine != null) { throw new InvalidOperationException("A broadphsed Detector cannot be added to more then one engine."); } this.engine = engine; OnAdded(); this.AddBodyRange(engine.bodies); }
public ARGame() : base() { componentFactory = new ARComponentFactory(); componentFactory.GraphicsInputFactory = ((AxiomEngine)engine).ComponentFactory; PhysicsEngine physicsEngine = new PhysicsEngine(); engine.AddSubsystem(physicsEngine); componentFactory.PhysicalFactory = physicsEngine.ComponentFactory; new LogManager(); LogManager.Instance.CreateLog("AR.log", true); }
public EntityManager(IMultiplayerServer server, IWorld world) { Server = server; World = world; PhysicsEngine = new PhysicsEngine(world, (BlockRepository)server.BlockRepository); PendingDespawns = new ConcurrentBag<IEntity>(); Entities = new List<IEntity>(); // TODO: Handle loading worlds that already have entities // Note: probably not the concern of EntityManager. The server could manually set this? NextEntityID = 1; LastUpdate = DateTime.UtcNow; TimeSinceLastUpdate = TimeSpan.Zero; }
protected override void Update(float deltaTime) { Ray r = ConstructRayFromMousePosition(); bool ret = PhysicsEngine.RayCastFirst(r, 1000, cast, out KeyValuePair <Collider, RayHit> arr); if (ret) { Vector3 pos = arr.Value.Location; pos.Y = looker.LocalPosition.Y; sphereTargetMarker.SetLocalPosition(pos); looker.LookAt(sphereTargetMarker); } }
public EntityManager(IMultiPlayerServer server, IWorld world) { Server = server; World = world; PhysicsEngine = new PhysicsEngine(world, (BlockRepository)server.BlockRepository); PendingDespawns = new ConcurrentBag <IEntity>(); Entities = new List <IEntity>(); // TODO: Handle loading worlds that already have entities // Note: probably not the concern of EntityManager. The server could manually set this? NextEntityID = 1; LastUpdate = DateTime.UtcNow; TimeSinceLastUpdate = TimeSpan.Zero; }
// \param dt the time diference of one simulation step, can be changed at runtime // \param targetDirection should be normalized // \param controller controller of the controlled entity public VehicleAlignToCommand(PhysicsEngine physicsEngine, double dt, SpatialVectorDouble targetDirection, EntityController controller, ulong controlledObjectId, double targetDerivationDistance, Pid.Configuration yawPidConfiguration, Pid.Configuration pitchPidConfiguration) { this.physicsEngine = physicsEngine; this.dt = dt; this.controller = controller; this.targetDirection = targetDirection; this.controlledObjectId = controlledObjectId; this.targetDerivationDistance = targetDerivationDistance; Trace.Assert(physicsEngine.existObjectById(controlledObjectId)); // object must exist hold by the physics engine yawPid = Pid.makeByTargetAndConfiguration(0, yawPidConfiguration); pitchPid = Pid.makeByTargetAndConfiguration(0, pitchPidConfiguration); }
private void OnMouseUp() { CancelInvoke(); // cancel InvokeRepeating audioSource.Stop(); audioSource.clip = launchSound; audioSource.Play(); // Launch the ball PhysicsEngine launchedObjectInstance = Instantiate(launchedObjectPrefab, transform.position, Quaternion.identity) as PhysicsEngine; launchedObjectInstance.transform.parent = GameObject.Find("LaunchedObjects").transform; Vector3 launchVelocity = new Vector3(1, 1, 0).normalized *launchSpeed; launchedObjectInstance.velocityVector = launchVelocity; }
internal void OnRemovedInternal() { Clear(); bool wasPending = this.IsPending; PhysicsEngine engine = this.engine; this.isAdded = false; this.engine = null; OnRemoved(engine, wasPending); if (Removed != null) { Removed(this, new RemovedEventArgs(engine, wasPending)); } }
private void OnMouseUp() { CancelInvoke(); PhysicsEngine newBall = Instantiate(ballToLaunch) as PhysicsEngine; newBall.transform.parent = GameObject.Find("Launched Balls").transform; Vector3 launchVelocity = new Vector3(1, 1, 0).normalized *launchSpeed; newBall.velocityVector = launchVelocity; audioSource.Stop(); audioSource.clip = launchSound; audioSource.Play(); }
/// <summary> /// Gets called from OpenTK whenever it is time for an update /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected virtual void Update(object sender, FrameEventArgs e) { FrameCounter++; MemoryTracer.NextStage("Update Frame: " + FrameCounter); MemoryTracer.AddSubStage("Scene Update"); CurrentScene?.Update((float)e.Time); MemoryTracer.NextStage("World Update"); CurrentScene?.Update((float)e.Time); MemoryTracer.NextStage("Physics Update"); PhysicsEngine.Update((float)e.Time); if (_changeScene) { MemoryTracer.NextStage("Scene Intialization"); _changeScene = false; MemoryTracer.AddSubStage("Removing Old Scene"); CurrentScene?._Destroy(); CurrentScene?.DestroyScene(); //Call on destroy on the scene itself. MemoryTracer.NextStage("Removing World"); CurrentScene?.RemoveDestroyedObjects(); MemoryTracer.NextStage("Create New Scene"); CurrentScene = (AbstractScene)Activator.CreateInstance(_nextScene); MemoryTracer.NextStage("Initialize New Scene"); CurrentScene._initializeScene(); MemoryTracer.ReturnFromSubStage(); } //Cleanup MemoryTracer.NextStage("Clean up Destroyed Objects"); CurrentScene?.RemoveDestroyedObjects(); MemoryTracer.ReturnFromSubStage(); //Returning to root. //ResourceManager.ProcessDeleteQueue(); }
void OnMouseUp() { Debug.Log("Cannon clicked!!!"); CancelInvoke("IncreaseLaunchSpeed"); audioSource.Stop(); audioSource.clip = launchSound; audioSource.Play(); PhysicsEngine newBall = Instantiate(ball) as PhysicsEngine; newBall.transform.parent = GameObject.Find("BallSpawn").transform; Vector3 launchVelocity = new Vector3(1, 1, 0).normalized *launchSpeed; newBall.velocity = launchVelocity; }
public void DespawnEntity(long entityId) { Ticker.ScheduleTick( () => { if (EntityManager.TryGet(entityId, out Entity entity)) { PhysicsEngine.Remove(entity); EntityManager.Remove(entityId); //entity.Dispose(); } }, 0); // Log.Info($"Despawned entity {entityId}"); }
internal void OnAddedInternal(PhysicsEngine engine) { this.isAdded = true; this.engine = engine; foreach (Body b in Bodies) { b.Removed += OnBodyRemoved; b.jointCount++; } OnAdded(); if (Added != null) { Added(this, EventArgs.Empty); } }
protected override void OnKeyDown(object sender, KeyboardKeyEventArgs e) { if (e.Key == Key.B) { Ray r = ConstructRayFromMousePosition(); bool ret = PhysicsEngine.RayCastFirst(r, 1000, cast, out KeyValuePair <Collider, RayHit> arr); if (ret) { Vector3 pos = arr.Value.Location; pos.Y += looker.LocalPosition.Y; sphereTargetMarker.SetLocalPosition(pos); looker.LookAt(sphereTargetMarker); } } }
public void TestExtremeTerrainCollision() { var repository = GetBlockRepository(); var world = new TrueCraft.Core.World.World("default", new FlatlandGenerator()); var physics = new PhysicsEngine(world, repository); var entity = new TestEntity(); entity.Position = new Vector3(0, 4, 0); entity.AccelerationDueToGravity = 10; physics.AddEntity(entity); // Test physics.Update(TimeSpan.FromSeconds(1)); Assert.AreEqual(4, entity.Position.Y); }
public bool UnregisterActor(Actor actor) { Console.WriteLine("Trying to remove Actor: " + actor); actor.OnActorDestroy(); var removal = _actors.Remove(actor); foreach (var comp in actor.Components) { var physComp = comp as PhysicsComponent; if (physComp != null) { PhysicsEngine.UnregisterPhysicsComponent(physComp); } } return(removal); }
public void PlayersWontKeepMovingPastDestination() { var destinationX = 5; var expectedPositionX = 5; _playerOne.Speed = 4; _playerOne.Destination = new Point(destinationX, 0); PhysicsEngine.MainLoop(); PhysicsEngine.MainLoop(); _playerOne.Position.X.Should().Be(expectedPositionX); }
void OnMouseUp() { CancelInvoke("IncreaseLaunchSpeed"); audioSource.Stop(); audioSource.clip = launchSound; audioSource.Play(); // launch the ball PhysicsEngine newBall = Instantiate(ballToLaunch) as PhysicsEngine; newBall.transform.parent = GameObject.Find("Launched Balls").transform; Vector3 launchVelocity = new Vector3(1, 1, 0).normalized *launchSpeed; newBall.velocityVector = launchVelocity; universalGravitation.AddPhysicsEngine(newBall); }
/// <summary> /// Initializes a new instance of the <see cref="TouchablePanel"/> class. /// </summary> public TouchablePanel() { elementToBody = new Dictionary <FrameworkElement, Body>(); shouldCreateBody = new List <FrameworkElement>(); shouldRemoveBody = new List <FrameworkElement>(); contactJoints = new Dictionary <int, FixedHingeJoint>(); elementToScale = new Dictionary <FrameworkElement, ScaleState>(); ignorer = new ObjectIgnorer(); engine = new PhysicsEngine(); engine.BroadPhase = new SweepAndPruneDetector(); engine.Solver = new SequentialImpulsesSolver(); timer = new PhysicsTimer(PhysicsTimerCallback, 0.01); Loaded += TouchablePanel_Loaded; }
private void Launch() { CancelInvoke("IncreaseLaunchSpeed"); audioSource.Stop(); audioSource.clip = launchFX; audioSource.Play(); Vector3 launchVelocity = new Vector3(1f, 1f, 0f).normalized *launchSpeed; PhysicsEngine newBall = Instantiate(ballToLaunch) as PhysicsEngine; newBall.transform.parent = launchedBalls.transform; newBall.velocityVector = launchVelocity; }
public void TestAdvancedCogEngine() { XNAGame game = new XNAGame(); game.SpectaterCamera.CameraPosition = new Vector3(0, 0, -40); game.SpectaterCamera.FarClip = 10000; PhysicsEngine engine = new PhysicsEngine(); CogEngine cogEngine = new CogEngine(game, engine); game.AddXNAObject(cogEngine); game.Run(); engine.Dispose(); }
private Will() { _engine = new PhysicsEngine { BroadPhase = new Physics2DDotNet.Detectors.SelectiveSweepDetector(), Solver = new Physics2DDotNet.Solvers.SequentialImpulsesSolver { AllowedPenetration = 0.0001f } }; _engine.AddLogic(new GravityField(new Vector2D(0, -300), new Lifespan())); _engine.Updated += OnEngineUpdated; _timer = new PhysicsTimer(_engine.Update, .005f); }
public Physics2dEngine() { phsEngine = new PhysicsEngine(); phsEngine.BroadPhase = new Physics2DDotNet.Detectors.SelectiveSweepDetector(); //phsEngine.BroadPhase = new Physics2DDotNet.Detectors.SpatialHashDetector(); SequentialImpulsesSolver phsSolver = new SequentialImpulsesSolver(); phsSolver.Iterations = 12; phsSolver.SplitImpulse = true; //phsSolver.BiasFactor = 0.7; phsSolver.BiasFactor = 0.0; //phsSolver.AllowedPenetration = 0.1; phsSolver.AllowedPenetration = 0.01; phsEngine.Solver = (CollisionSolver)phsSolver; }
public Game1() { graphics = new GraphicsDeviceManager(this); GraphicsHelper.graphics = graphics; Content.RootDirectory = "Content"; ContentHelper.Content = Content; Window.AllowUserResizing = false; // Borderless Window functionality Window.IsBorderless = true; Window.Position = Point.Zero; Window.Title = "I am Poor and Hungry"; // Scaleable resolution functionality graphics.PreferredBackBufferWidth = 1920; graphics.PreferredBackBufferHeight = 1080; GraphicsHelper.screen = new Rectangle(0, 0, graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight); // Depth and Buffer format functionality graphics.PreferredDepthStencilFormat = DepthFormat.Depth16; graphics.PreferredBackBufferFormat = SurfaceFormat.Color; // V-Sync graphics.SynchronizeWithVerticalRetrace = true; // Anti-Aliasing functionality graphics.PreferMultiSampling = true; // Fullscreen functionality //graphics.ToggleFullScreen(); this.Components.Add(Time.Instance(this)); this.Components.Add(Random.Instance(this)); this.Components.Add(GameObjectManager.Instance(this)); this.Components.Add(SceneManager.Instance(this)); this.Components.Add(SoundManager.Instance(this)); this.Components.Add(SongManager.Instance(this)); this.Components.Add(PhysicsEngine.Instance(this, PhysicsEngine.EngineTypes.Physics2D)); SceneManager.activeScene = new SceneTitle(); //SceneManager.activeScene = new SceneGame(); //PhysicsEngine.PhysicsSettings.WORLD_FORCE = new Vector3(0, -9.8f, 0); }
void ChkCollisions() { foreach (var enemy in _listOfEnemies) { if (enemy.IsAlive) { foreach (var bullet in _listOfBullets) { if (PhysicsEngine.CheckCollision(enemy, bullet)) { enemy.ReceiveHit(bullet); if (!enemy.IsAlive) { EnemyKilled(); } } if (PhysicsEngine.CheckBorderCollision(enemy) == PhysicsEngine.borderCollision.Down) { enemy.Reset(); } } } } foreach (var player in _listOfPlayers) { if (player.IsAlive) { foreach (var enemy in _listOfEnemies) { if (enemy.IsAlive && PhysicsEngine.CheckCollision(player, enemy)) { player.ReceiveHit(enemy); } if (enemy.IsAlive) { PhysicsEngine.borderCollision borderCol = PhysicsEngine.CheckBorderCollision(player); if (borderCol != PhysicsEngine.borderCollision.None) { player.MoveTo(PhysicsEngine.CalcColSolvePlayer(player, borderCol)); } } } } } }
// Use this for initialization void Start() { physics = GetComponent <PhysicsEngine>(); physics.mass += fuelMass; increaseThrust = 1f / fuelMass; //Let the UI know the fuel if (onFuelUpdate != null) { onFuelUpdate(rocketName, fuelMass); } if (engineParticle) { psEmit = engineParticle.emission; } m_source = gameObject.GetComponent <SoundManager>(); }
/// <summary> /// Frame update /// </summary> /// <param name="update"></param> public override void Update(FrameUpdate update) { if (_raycastProperties == null) { base.Update(update); return; } _appTime = (float)update.ApplicationTime; // assume pose of parent if (Parent != null) { State.Pose = Parent.State.Pose; } _elapsedSinceLastScan += (float)update.ElapsedTime; // only retrieve raycast results every SCAN_INTERVAL. // For entities that are compute intenisve, you should consider giving them // their own task queue so they dont flood a shared queue if (_elapsedSinceLastScan > SCAN_INTERVAL) { _elapsedSinceLastScan = 0; // the LRF looks towards the negative Z axis (towards the user), not the positive Z axis // which is the default orientation. So we have to rotate its orientation by 180 degrees _raycastProperties.OriginPose.Orientation = TypeConversion.FromXNA( TypeConversion.ToXNA(State.Pose.Orientation) * xna.Quaternion.CreateFromAxisAngle(new xna.Vector3(0, 1, 0), (float)Math.PI)); // to calculate the position of the origin of the raycast, we must first rotate the LocalPose position // of the raycast (an offset from the origin of the parent entity) by the orientation of the parent entity. // The origin of the raycast is then this rotated offset added to the parent position. xna.Matrix parentOrientation = xna.Matrix.CreateFromQuaternion(TypeConversion.ToXNA(State.Pose.Orientation)); xna.Vector3 localOffset = xna.Vector3.Transform(TypeConversion.ToXNA(_sonarBox.State.LocalPose.Position), parentOrientation); _raycastProperties.OriginPose.Position = State.Pose.Position + TypeConversion.FromXNA(localOffset); _raycastResultsPort = PhysicsEngine.Raycast2D(_raycastProperties); _raycastResultsPort.Test(out _lastResults); if (_serviceNotification != null && _lastResults != null) { _serviceNotification.Post(_lastResults); } } base.Update(update); }
public void TestContactNotify() { XNAGame game = new XNAGame(); game.SpectaterCamera.CameraPosition = new Vector3(0, 0, -40); PhysicsEngine engine = new PhysicsEngine(); engine.AddContactNotification(delegate(ContactPair contactInformation, ContactPairFlag events) { var pos = contactInformation.ActorA.GlobalPosition; game.LineManager3D.AddLine(pos, pos + Vector3.Up * 5, Color.Yellow); pos = contactInformation.ActorB.GlobalPosition; game.LineManager3D.AddLine(pos, pos + Vector3.Up * 5, Color.Orange); }); game.InitializeEvent += delegate { engine.Initialize(); PhysicsDebugRendererXNA debugRenderer = new PhysicsDebugRendererXNA(game, engine.Scene); game.AddXNAObject(debugRenderer); }; game.UpdateEvent += delegate { if (game.Keyboard.IsKeyPressed(Microsoft.Xna.Framework.Input.Keys.F)) { Actor actor = PhysicsHelper.CreateDynamicSphereActor(engine.Scene, 1, 1); actor.GlobalPosition = game.SpectaterCamera.CameraPosition + game.SpectaterCamera.CameraDirection * 5; actor.LinearVelocity = game.SpectaterCamera.CameraDirection * 5; actor.ContactReportFlags = ContactPairFlag.All; //actor.ContactReportThreshold = 10000; } engine.Update(game.Elapsed); }; game.Run(); engine.Dispose(); }
private void SingleRaycastAsync(xna.Vector3 from, xna.Vector3 to, int index, Port <OcclusionRay> resultPort) { var rayResult = PhysicsEngine.Raycast2D( RaycastProperties.FromSingleRay( TypeConversion.FromXNA(from), TypeConversion.FromXNA(to) ) ); Activate( Arbiter.Receive(false, rayResult, delegate(RaycastResult result) { xna.Vector3 hitPoint; if (result.ImpactPoints.Count == 1) { var impact = result.ImpactPoints[0].Position; hitPoint = new xna.Vector3( impact.X, impact.Y, impact.Z ); } else { hitPoint = to; } float distance = (hitPoint - to).Length(); resultPort.Post( new OcclusionRay { Index = index, Point = from, Impact = hitPoint, Distance = distance, Occluded = distance > OcclusionThreshold, Run = 0 } ); } ) ); }
/// <summary> /// Initializes a new instance of the <see cref="ScrollViewer"/> class. /// </summary> public ScrollViewer() { borderSoftness = BorderSoftness; AddHandler(MultitouchScreen.NewContactEvent, (NewContactEventHandler)OnNewContact); AddHandler(MultitouchScreen.ContactMovedEvent, (ContactEventHandler)OnContactMoved); AddHandler(MultitouchScreen.ContactRemovedEvent, (ContactEventHandler)OnContactRemoved); AddHandler(MultitouchScreen.ContactLeaveEvent, (ContactEventHandler)OnContactLeave); engine = new PhysicsEngine(); engine.BroadPhase = new SweepAndPruneDetector(); engine.Solver = new SequentialImpulsesSolver(); engine.AddLogic(new BoundsConstrainLogic(this)); timer = new PhysicsTimer(PhysicsTimerCallback, 0.01); Loaded += ScrollViewer_Loaded; }
private void UpdateInternalFOV(Point source, Point dest, bool canOperate, PhysicsEngine engine, bool usePlayerLOS, bool monstersBlockPath) { // First get the 'default' values bool[,] moveableGrid = m_map.CalculateMoveablePointGrid(monstersBlockPath, source); // Now foor doors, if we can operate, make it movable // Doors are special. If they ever are not special, make this a virtual method if (canOperate) { foreach (MapObject m in m_map.MapObjects.OfType<MapDoor>()) moveableGrid[m.Position.X, m.Position.Y] = true; } // Now for a targetted monster if any, they are movable Monster monster = (Monster)m_map.Monsters.SingleOrDefault(x => x.Position == dest); if (monster != null) moveableGrid[monster.Position.X, monster.Position.Y] = true; // Same for player if (m_player.Position == dest) moveableGrid[m_player.Position.X, m_player.Position.Y] = true; // We can't travel to places we haven't explored if (usePlayerLOS) { for (int i = 0; i < m_map.Width; ++i) { for (int j = 0; j < m_map.Height; ++j) { if (!m_map.IsVisitedAt(new Point(i, j))) { moveableGrid[i, j] = false; } } } } // Now use moveableGrid to setup FOV for (int i = 0; i < m_map.Width; ++i) { for (int j = 0; j < m_map.Height; ++j) { m_physicsMap.Cells[i, j].Walkable = moveableGrid[i, j]; } } }
public bool SpawnEntity(long entityId, Entity entity) { if (EntityManager.AddEntity(entityId, entity)) { //entity.RenderLocation = entity.KnownPosition; if (entity.HasPhysics) { PhysicsEngine.AddTickable(entity); } entity.OnSpawn(); return(true); } return(false); //Log.Info($"Spawned entity {entityId} : {entity} at {entity.KnownPosition} with renderer {entity.GetModelRenderer()}"); }
public void Destroy() { if (_destroyed) { return; } _destroyed = true; EventDispatcher.UnregisterEvents(this); PhysicsEngine.Stop(); EntityManager.Dispose(); ChunkManager.Dispose(); PhysicsEngine.Dispose(); Player.Dispose(); }
public void Update(UpdateArgs args) { var camera = Camera; args.Camera = camera; /*if (Math.Abs(Player.FOVModifier - _fovModifier) > 0f) * { * _fovModifier = Player.FOVModifier; * * camera.FOV += _fovModifier; * camera.UpdateProjectionMatrix(); * camera.FOV -= _fovModifier; * }*/ camera.Update(args); //_brightnessMod = SkyRenderer.BrightnessModifier; SkyRenderer.Update(args); ChunkManager.Update(args); EntityManager.Update(args); PhysicsEngine.Update(args.GameTime); if (Math.Abs(_brightnessMod - SkyRenderer.BrightnessModifier) > 0f) { _brightnessMod = SkyRenderer.BrightnessModifier; var diffuseColor = Color.White.ToVector3() * SkyRenderer.BrightnessModifier; ChunkManager.AmbientLightColor = diffuseColor; if (Math.Abs(ChunkManager.Shaders.BrightnessModifier - SkyRenderer.BrightnessModifier) > 0f) { ChunkManager.Shaders.BrightnessModifier = SkyRenderer.BrightnessModifier; } var modelRenderer = Player?.ModelRenderer; if (modelRenderer != null) { modelRenderer.DiffuseColor = diffuseColor; } } Player.Update(args); }
public override void Initialize(Microsoft.Xna.Framework.Graphics.GraphicsDevice device, PhysicsEngine physicsEngine) { base.Initialize(device, physicsEngine); if (CustomJoint != null) { if (ParentJoint != null) PhysicsEngine.DeleteJoint((PhysicsJoint)ParentJoint); if (CustomJoint.State.Connectors[0].Entity == null) CustomJoint.State.Connectors[0].Entity = FindConnectedEntity(CustomJoint.State.Connectors[0].EntityName); if (CustomJoint.State.Connectors[1].Entity == null) CustomJoint.State.Connectors[1].Entity = FindConnectedEntity(CustomJoint.State.Connectors[1].EntityName); ParentJoint = CustomJoint; PhysicsEngine.InsertJoint((PhysicsJoint)ParentJoint); } }
public MultiplayerClient(TrueCraftUser user) { User = user; Client = new TcpClient(); PacketReader = new PacketReader(); PacketReader.RegisterCorePackets(); PacketHandlers = new PacketHandler[0x100]; Handlers.PacketHandlers.RegisterHandlers(this); World = new ReadOnlyWorld(); var repo = new BlockRepository(); repo.DiscoverBlockProviders(); World.World.BlockRepository = repo; World.World.ChunkProvider = new EmptyGenerator(); Physics = new PhysicsEngine(World.World, repo); SocketPool = new SocketAsyncEventArgsPool(100, 200, 65536); connected = 0; cancel = new CancellationTokenSource(); }
public override void fire(Agent p, PhysicsEngine ph) { base.fire(p, ph); if (curCooldown == cooldown) { List<Agent> l = new List<Agent>(); l.Add(p); PhysicsEngine.HitScan hs = ph.hitscan(p.getPosition() + new Vector3(0, 75, 0) + p.getDirectionVector() * 10, p.getDirectionVector(), null); PhysicsEngine.AgentHitScan ahs = ph.agentHitscan(p.getPosition() + new Vector3(0, 60, 0) + p.getDirectionVector() * 10, p.getDirectionVector(), l); if (hs != null && (ahs == null || hs.Distance() < ahs.Distance())) makeLaser(p, hs.ray, Vector3.Distance(hs.ray.Position, hs.collisionPoint), 10, 10, "Railgun"); else { if (ahs != null) { ahs.agent.dealDamage((int)damage, p); makeLaser(p, ahs.ray, Vector3.Distance(ahs.ray.Position, ahs.collisionPoint), 10, 10, "Railgun"); } } } }
// Alright, the behavior we're looking for is a bit unique. // We want to know if you can walk to a given position. // If there is a character there, ignore it so we can walk 'towards' it // If there are doors in the way, if we can operate, ignore them. public List<Point> Travel(Character actor, Point dest, bool canOperate, PhysicsEngine engine, bool usePlayerLOS, bool monstersBlockPath) { UpdateInternalFOV(actor.Position, dest, canOperate, engine, usePlayerLOS, monstersBlockPath); bool pathExists = m_pathFinding.Compute(actor.Position.X, actor.Position.Y, dest.X, dest.Y); if (!pathExists) return null; List<Point> path = new List<Point>(); int pathLength = m_pathFinding.Size(); for (int i = 0; i < pathLength; ++i) { int currentX; int currentY; m_pathFinding.GetPathElement(i, out currentX, out currentY); path.Add(new Point(currentX, currentY)); } return path; }
private float currentThrust; // N <- Note Newtons NOT kN // Use this for initialization void Start () { physicsEngine = GetComponent<PhysicsEngine>(); physicsEngine.mass += fuelMass; }
internal void OnRemovedInternal() { engine = null; Clear(); OnRemoved(); }
protected override void Start() { _physicsEngine = PhysicsEngine.GlobalInstance; _notificationTarget = new SimulationEnginePort(); // PartnerType.Service is the entity instance name. SimulationEngine.GlobalInstancePort.Subscribe(ServiceInfo.PartnerList, _notificationTarget); LogInfo("Starting Simulated Sonar"); // Raul - If state cannot be read from file create a default one if (_state == null) { _state = CreateDefaultState(); } else // Use the state saved in the file, but don't forget to allocate memory for arrays. { _state.DistanceMeasurements = new double[SonarArrayLength]; formerDistanceMeasurements = new double[SonarArrayLength]; } // dont start listening to DSSP operations, other than drop, until notification of entity Activate(new Interleave( new TeardownReceiverGroup ( Arbiter.Receive<InsertSimulationEntity>(false, _notificationTarget, InsertEntityNotificationHandlerFirstTime), Arbiter.Receive<dssp.DsspDefaultDrop>(false, _mainPort, DefaultDropHandler) ), new ExclusiveReceiverGroup(), new ConcurrentReceiverGroup() )); // Publish the service to the local Node Directory // DirectoryInsert(); }
public virtual void fire(Agent p, PhysicsEngine ph) { if (curCooldown > 0 || p.ammo < ammoUsed) return; p.ammo -= ammoUsed; curCooldown = cooldown; }
internal void OnPendingInternal(PhysicsEngine engine) { this.isChecked = true; this.engine = engine; OnPending(EventArgs.Empty); }
internal void OnRemovedInternal() { bool isPending = IsPending; foreach (Body b in Bodies) { b.IsFrozen = false; b.idleCount = 0; if (!isPending) { b.RemoveJoint(this); } b.Removed -= OnBodyRemoved; } PhysicsEngine engine = this.engine; bool wasPending = isPending; this.isAdded = false; this.engine = null; OnRemoved(new RemovedEventArgs(engine, wasPending)); }
// New maps might have new height/width public void UpdateNewMap(PhysicsEngine physicsEngine, Map map) { m_physicsMap = new PhysicsMap(map.Width, map.Height); }
public JsonPhysics(PhysicsEngine Engine) { this.Engine = Engine; }
public void InitializePhysics() { engine = new PhysicsEngine("MetaliPhysics"); scene = engine.Factory.PhysicsSceneManager.Create("Scene"); scene.TimeOfSimulation = 0.016f; }
internal MagicEffectsEngine(PhysicsEngine physicsEngine, CombatEngine combatEngine) { m_combatEngine = combatEngine; m_physicsEngine = physicsEngine; m_effectEngine = new EffectEngine(CoreGameEngineInterface.Instance); }
protected internal override void BeforeAddCheck(PhysicsEngine engine) { if (body.Engine != engine) { throw new InvalidOperationException("Body must be in the engine"); } base.BeforeAddCheck(engine); }
protected internal void BeforeAddCheckInternal(PhysicsEngine engine) { foreach (Body item in Bodies) { if (item.Engine != engine) { throw new InvalidOperationException("All Bodies the Joint Effects Must Be added to the Same Engine Before the Joint is added."); } } BeforeAddCheck(engine); }
//-- TT #endregion /// <summary> /// Service Start /// </summary> protected override void Start() { int i; // The state might already have been created using // the Initial State Partner above. If so, then we // don't want to create a new one! if (_state == null) { _state = new MazeSimulatorState(); // Do any other initialization here for the default // settings that you might want ... // Raul - Aug 2007 - Indicate what sensors are being used // Using LRF instead of Sonar doesn't work with control panel // until I fix the limit of 19 ports in Control Panel Operations portset _state.UseLRF = false; _state.UseSonar = true; // Raul - Aug 2007 - Initial position of the robot // This is valid for the maze I am using now // Note that position could be inside a wall in // your maze! _state.RobotStartCellCol = 30; _state.RobotStartCellRow = 30; } // TT Feb-2007 - Shock! Horror! Setting the maze in the config // file did not work because it was initialized in the constructor // for the State! // The maze here is one with lots of different objects including some balls // Note the path - It is relative to where dsshost is started from // Other samples are: // ModelSmall.gif -- A smaller model than the one above // office.bmp -- A black and white image of an "office" maze // Jul-2007: // Changed the location of the files if (_state.Maze == null || _state.Maze == "") _state.Maze = "Apps/UC3M/MazeSimulatorRA/OfficeRaul1.bmp"; // Make sure that there is a floor texture // Plenty of others to try, e.g. concrete.jpg. if (_state.GroundTexture == null || _state.GroundTexture == "") _state.GroundTexture = "cellfloor.jpg"; // _state.GroundTexture = "granito.bmp"; // TT Dec-2006 - This is a fudge to support upgrading from // prior versions where the RobotType did not exist. When // MSRS loades the config file, it does not populate any // of the fields that are missing. Therefore the RobotType // is null and this causes the code to crash later on. if (_state.RobotType == null) _state.RobotType = "Pioneer3DX"; // Now initialize our internal copies of state info // This is a little bit of insurance against a bad // config file ... // Copy as many textures as available up to the max for (i = 0; (i < 16) && (i < _state.WallTextures.Length); i++) { _WallTextures[i] = _state.WallTextures[i]; } // Fill any remaining textures with empty string for ( ; i < 16; i++) _WallTextures[i] = ""; // Copy as many colors as specified // NOTE: The constructor for the State sets all of the // colors to the standard ones, so any that are not // specified will default to them. for (i = 0; (i < 16) && (i < _state.WallColors.Length); i++) { _WallColors[i] = _state.WallColors[i]; } // Fill any remaining colors with the defaults for (; i < 16; i++) _WallColors[i] = MazeSimulatorState.DefaultColors[i]; // Copy as many heights as specified for (i = 0; (i < 16) && (i < _state.HeightMap.Length); i++) { _WallHeights[i] = _state.HeightMap[i]; } // Fill any remaining heights with the defaults for (; i < 16; i++) _WallHeights[i] = 5.0f; // Copy as many weights as specified for (i = 0; (i < 16) && (i < _state.MassMap.Length); i++) { _WallMasses[i] = _state.MassMap[i]; } // Fill any remaining weights with the defaults for (; i < 16; i++) _WallMasses[i] = 0.0f; // Copy as many sphere flags as specified for (i = 0; (i < 16) && (i < _state.UseSphere.Length); i++) { _UseSphere[i] = _state.UseSphere[i]; } // Fill any remaining flags with false for (; i < 16; i++) _UseSphere[i] = false; if (_state.SphereScale <= 0.0f) _state.SphereScale = 1.0f; if (_state.HeightScale <= 0.0f) _state.HeightScale = 1.0f; // Copy back our private versions which might have the // effect of extending the state _state.WallColors = _WallColors; _state.WallTextures = _WallTextures; _state.HeightMap = _WallHeights; _state.MassMap = _WallMasses; _state.UseSphere = _UseSphere; // Now save the State // This creates a new file the first time it is run // Later, it re-reads the existing file, but by then // the file has been populated with the defaults SaveState(_state); // Listen on the main port for requests and call the appropriate handler. ActivateDsspOperationHandlers(); // Publish the service to the local Node Directory DirectoryInsert(); // display HTTP service Uri LogInfo(LogGroups.Console, "Service uri: "); // Cache references to simulation/rendering and physics _physicsEngine = PhysicsEngine.GlobalInstance; _simEnginePort = SimulationEngine.GlobalInstancePort; // TT Dec-2006 - Set up the initial camera view SetupCamera(); // Add objects (entities) in our simulated world PopulateWorld(); }
/// <summary> /// Before the item is allowed to be added to pending this method is called to /// throw any exceptions without corrupting the state of the Physics engine. /// </summary> /// <param name="engine">The engine the item is about to be added too.</param> protected internal virtual void BeforeAddCheck(PhysicsEngine engine) { }
/// <summary> /// Initialization /// </summary> /// <param name="device"></param> /// <param name="physicsEngine"></param> public override void Initialize(xnagrfx.GraphicsDevice device, PhysicsEngine physicsEngine) { try { InitError = string.Empty; // set flag so rendering engine renders us last Flags |= VisualEntityProperties.UsesAlphaBlending; // creates effect, loads meshes, etc base.Initialize(device, physicsEngine); HeightFieldShapeProperties hf = new HeightFieldShapeProperties("height field", 2, 0.02f, 2, 0.02f, 0, 0, 1, 1); hf.HeightSamples = new HeightFieldSample[hf.RowCount * hf.ColumnCount]; for (int i = 0; i < hf.HeightSamples.Length; i++) hf.HeightSamples[i] = new HeightFieldSample(); _particlePlane = new Shape(hf); _particlePlane.State.Name = "sonar impact plane"; VisualEntityMesh sonarMesh = null; // we render on our own only the laser impact points. The laser Box is rendered as part of the parent. int index = Meshes.Count; Meshes.Add(SimulationEngine.ResourceCache.CreateMesh(device, _particlePlane.State)); Meshes[0].Textures[0] = SimulationEngine.ResourceCache.CreateTextureFromFile(device, "particle.bmp"); // we have a custom effect, with an additional global parameter. Get handle to it here if (Effect != null) _timeAttenuationHandle = Effect.GetParameter("timeAttenuation"); World = xna.Matrix.Identity; if (Meshes.Count > 1) sonarMesh = Meshes[0]; if (Parent == null) throw new Exception("This entity must be a child of another entity."); Parent.AddShapeToPhysicsEntity(_sonarBox, sonarMesh); } catch (Exception ex) { HasBeenInitialized = false; InitError = ex.ToString(); } }
internal void OnRemovedInternal() { Clear(); bool wasPending = this.IsPending; PhysicsEngine engine = this.engine; this.isAdded = false; this.engine = null; OnRemoved(new RemovedEventArgs(engine, wasPending)); }
// Use this for initialization void Start () { physicsEngine = GetComponent<PhysicsEngine>(); }