// This method is called every update (but only if application has focus) public override void HandleUnhandledInput(bool receivedFocusInThisUpdate) { if (MyInput.Static.ENABLE_DEVELOPER_KEYS || (MySession.Static != null && MySession.Static.Settings.EnableSpectator) || (MyMultiplayer.Static != null && MyMultiplayer.Static.IsAdmin(MySession.LocalHumanPlayer.Id.SteamId))) { //Set camera to player if (MyInput.Static.IsNewGameControlPressed(MyControlsSpace.SPECTATOR_NONE)) { if (MySession.ControlledEntity != null) { //we already are controlling this object if (MyFinalBuildConstants.IS_OFFICIAL) { SetCameraController(); } else { var cameraController = MySession.GetCameraControllerEnum(); if (cameraController != MyCameraControllerEnum.Entity && cameraController != MyCameraControllerEnum.ThirdPersonSpectator) { SetCameraController(); } else { var entities = MyEntities.GetEntities().ToList(); int lastKnownIndex = entities.IndexOf(MySession.ControlledEntity.Entity); var entitiesList = new List <MyEntity>(); if (lastKnownIndex + 1 < entities.Count) { entitiesList.AddRange(entities.GetRange(lastKnownIndex + 1, entities.Count - lastKnownIndex - 1)); } if (lastKnownIndex != -1) { entitiesList.AddRange(entities.GetRange(0, lastKnownIndex + 1)); } MyCharacter newControlledObject = null; for (int i = 0; i < entitiesList.Count; i++) { var character = entitiesList[i] as MyCharacter; if (character != null && !character.IsDead) { newControlledObject = character; break; } } if (MySession.LocalHumanPlayer != null && newControlledObject != null) { MySession.LocalHumanPlayer.Controller.TakeControl(newControlledObject); } } // We could have activated the cube builder in spectator, so deactivate it now if (MyCubeBuilder.Static.IsActivated && !(MySession.ControlledEntity is MyCharacter)) { MyCubeBuilder.Static.Deactivate(); } } } } //Set camera to following third person if (MyInput.Static.IsNewGameControlPressed(MyControlsSpace.SPECTATOR_DELTA)) { if (MySession.ControlledEntity != null) { MySession.SetCameraController(MyCameraControllerEnum.SpectatorDelta); } } //Set camera to spectator if (MyInput.Static.IsNewGameControlPressed(MyControlsSpace.SPECTATOR_FREE)) { if (MySession.GetCameraControllerEnum() != MyCameraControllerEnum.Spectator) { MySession.SetCameraController(MyCameraControllerEnum.Spectator); } else if (MyInput.Static.IsAnyShiftKeyPressed()) { MyFakes.ENABLE_DEVELOPER_SPECTATOR_CONTROLS = !MyFakes.ENABLE_DEVELOPER_SPECTATOR_CONTROLS; } if (MyInput.Static.IsAnyCtrlKeyPressed() && MySession.ControlledEntity != null) { MySpectator.Static.Position = (Vector3D)MySession.ControlledEntity.Entity.PositionComp.GetPosition() + MySpectator.Static.ThirdPersonCameraDelta; MySpectator.Static.Target = (Vector3D)MySession.ControlledEntity.Entity.PositionComp.GetPosition(); } } //Set camera to static spectator, non movable if (MyInput.Static.IsNewGameControlPressed(MyControlsSpace.SPECTATOR_STATIC)) { if (MySession.ControlledEntity != null) { MySession.SetCameraController(MyCameraControllerEnum.SpectatorFixed); if (MyInput.Static.IsAnyCtrlKeyPressed()) { MySpectator.Static.Position = (Vector3D)MySession.ControlledEntity.Entity.PositionComp.GetPosition() + MySpectator.Static.ThirdPersonCameraDelta; MySpectator.Static.Target = (Vector3D)MySession.ControlledEntity.Entity.PositionComp.GetPosition(); } } } //Open console if (MyInput.Static.IsNewGameControlPressed(MyControlsSpace.CONSOLE) && MyInput.Static.IsAnyAltKeyPressed()) { MyGuiScreenConsole.Show(); } } if (MyDefinitionErrors.ShouldShowModErrors) { MyDefinitionErrors.ShouldShowModErrors = false; MyGuiSandbox.ShowModErrors(); } // Switch view - cockpit on/off, third person if (MyInput.Static.IsNewGameControlPressed(MyControlsSpace.CAMERA_MODE) && CanSwitchCamera) { MyGuiAudio.PlaySound(MyGuiSounds.HudClick); SwitchCamera(); //if (MySession.IsCameraControlledObject()) //{ // //MySession.SetCameraController(MyCameraControllerEnum.ThirdPersonSpectator); // MySession.Static.CameraController.IsInFirstPersonView = true; //} //else //{ // MySession.Static.CameraController.IsInFirstPersonView = false; //} ////else if (MySession.GetCameraControllerEnum() == MyCameraControllerEnum.ThirdPersonSpectator) ////{ //// if (MySession.ControlledObject is IMyCameraController) //// MySession.SetCameraController(MyCameraControllerEnum.Entity, MySession.ControlledObject.Entity); ////} } if (MyInput.Static.IsNewGameControlPressed(MyControlsSpace.HELP_SCREEN)) { if (MyInput.Static.IsAnyCtrlKeyPressed()) { switch (MySandboxGame.Config.DebugComponentsInfo) { case MyDebugComponent.MyDebugComponentInfoState.NoInfo: MySandboxGame.Config.DebugComponentsInfo = MyDebugComponent.MyDebugComponentInfoState.EnabledInfo; break; case MyDebugComponent.MyDebugComponentInfoState.EnabledInfo: MySandboxGame.Config.DebugComponentsInfo = MyDebugComponent.MyDebugComponentInfoState.FullInfo; break; case MyDebugComponent.MyDebugComponentInfoState.FullInfo: MySandboxGame.Config.DebugComponentsInfo = MyDebugComponent.MyDebugComponentInfoState.NoInfo; break; } MySandboxGame.Config.Save(); } else if (MyGuiScreenGamePlay.ActiveGameplayScreen == null) { MyGuiAudio.PlaySound(MyGuiSounds.HudMouseClick); MyGuiSandbox.AddScreen(MyGuiScreenGamePlay.ActiveGameplayScreen = MyGuiSandbox.CreateScreen(MyPerGameSettings.GUI.HelpScreen)); } } if (MyInput.Static.IsNewGameControlPressed(MyControlsSpace.TOGGLE_HUD)) { MyGuiAudio.PlaySound(MyGuiSounds.HudClick); MyHud.MinimalHud = !MyHud.MinimalHud; } if (MyPerGameSettings.SimplePlayerNames && MyInput.Static.IsNewGameControlPressed(MyControlsSpace.BROADCASTING)) { MyHud.LocationMarkers.Visible = !MyHud.LocationMarkers.Visible; } var controlledObject = MySession.ControlledEntity; var currentCameraController = MySession.Static.CameraController; if (MyInput.Static.IsNewGameControlPressed(MyControlsSpace.MISSION_SETTINGS) && MyGuiScreenGamePlay.ActiveGameplayScreen == null && MyPerGameSettings.Game == Sandbox.Game.GameEnum.SE_GAME && MyFakes.ENABLE_MISSION_TRIGGERS) { MyGuiSandbox.AddScreen(new Sandbox.Game.Screens.MyGuiScreenMissionTriggers()); } // HACK! Do NOT add anything that relies on use objects here! // Letting certain use objects which are targeted handle any kind of events, circumventing all normal use object mechanisms. // Only used by ropes (and it should stay that way). var controlledCharacter = controlledObject as MyCharacter; bool handledByUseObject = false; if (controlledCharacter != null && controlledCharacter.UseObject != null) { handledByUseObject = controlledCharacter.UseObject.HandleInput(); } MyStringId context = controlledObject != null ? controlledObject.ControlContext : MySpaceBindingCreator.CX_BASE; if (controlledObject != null && !handledByUseObject) { if (!MySandboxGame.IsPaused) { if (context == MySpaceBindingCreator.CX_BUILD_MODE || context == MySpaceBindingCreator.CX_CHARACTER || context == MySpaceBindingCreator.CX_SPACESHIP) { if (MyControllerHelper.IsControl(context, MyControlsSpace.PRIMARY_TOOL_ACTION, MyControlStateType.NEW_PRESSED)) { if (MyToolbarComponent.CurrentToolbar.ShouldActivateSlot) { MyToolbarComponent.CurrentToolbar.ActivateStagedSelectedItem(); } else { controlledObject.BeginShoot(MyShootActionEnum.PrimaryAction); } } if (MyControllerHelper.IsControl(context, MyControlsSpace.PRIMARY_TOOL_ACTION, MyControlStateType.NEW_RELEASED)) { controlledObject.EndShoot(MyShootActionEnum.PrimaryAction); } if (MyControllerHelper.IsControl(context, MyControlsSpace.SECONDARY_TOOL_ACTION, MyControlStateType.NEW_PRESSED)) { controlledObject.BeginShoot(MyShootActionEnum.SecondaryAction); } if (MyControllerHelper.IsControl(context, MyControlsSpace.SECONDARY_TOOL_ACTION, MyControlStateType.NEW_RELEASED)) { controlledObject.EndShoot(MyShootActionEnum.SecondaryAction); } } if (context == MySpaceBindingCreator.CX_CHARACTER || context == MySpaceBindingCreator.CX_SPACESHIP) { if (MyControllerHelper.IsControl(context, MyControlsSpace.USE, MyControlStateType.NEW_PRESSED)) { // Key press if (currentCameraController != null) { if (!currentCameraController.HandleUse()) { controlledObject.Use(); } } else { controlledObject.Use(); } } else if (MyControllerHelper.IsControl(context, MyControlsSpace.USE, MyControlStateType.PRESSED)) { // Key not pressed this frame, holding from previous controlledObject.UseContinues(); } else if (MyControllerHelper.IsControl(context, MyControlsSpace.USE, MyControlStateType.NEW_RELEASED)) { controlledObject.UseFinished(); } //Temp fix until spectators are implemented as entities //Prevents controlled object from getting input while spectator mode is enabled if (!(MySession.Static.CameraController is MySpectatorCameraController && MySpectatorCameraController.Static.SpectatorCameraMovement == MySpectatorCameraMovementEnum.UserControlled)) { if (MyControllerHelper.IsControl(context, MyControlsSpace.CROUCH, MyControlStateType.NEW_PRESSED)) { controlledObject.Crouch(); } if (MyControllerHelper.IsControl(context, MyControlsSpace.CROUCH, MyControlStateType.PRESSED)) { controlledObject.Down(); } if (MyControllerHelper.IsControl(context, MyControlsSpace.SPRINT, MyControlStateType.PRESSED)) { controlledObject.Sprint(); } if (MyControllerHelper.IsControl(context, MyControlsSpace.JUMP, MyControlStateType.NEW_PRESSED)) { controlledObject.Jump(); } if (MyControllerHelper.IsControl(context, MyControlsSpace.JUMP, MyControlStateType.PRESSED)) { controlledObject.Up(); } if (MyControllerHelper.IsControl(context, MyControlsSpace.SWITCH_WALK, MyControlStateType.NEW_PRESSED)) { controlledObject.SwitchWalk(); } if (MyControllerHelper.IsControl(context, MyControlsSpace.BROADCASTING, MyControlStateType.NEW_PRESSED)) { controlledObject.SwitchBroadcasting(); } if (MyControllerHelper.IsControl(context, MyControlsSpace.HELMET, MyControlStateType.NEW_PRESSED)) { controlledObject.SwitchHelmet(); } } if (MyControllerHelper.IsControl(context, MyControlsSpace.DAMPING, MyControlStateType.NEW_PRESSED)) { MyGuiAudio.PlaySound(MyGuiSounds.HudClick); controlledObject.SwitchDamping(); } if (MyControllerHelper.IsControl(context, MyControlsSpace.THRUSTS, MyControlStateType.NEW_PRESSED)) { MyGuiAudio.PlaySound(MyGuiSounds.HudClick); controlledObject.SwitchThrusts(); } if (MyControllerHelper.IsControl(context, MyControlsSpace.HEADLIGHTS, MyControlStateType.NEW_PRESSED)) { MyGuiAudio.PlaySound(MyGuiSounds.HudClick); controlledObject.SwitchLights(); } if (MyControllerHelper.IsControl(context, MyControlsSpace.TOGGLE_REACTORS, MyControlStateType.NEW_PRESSED)) { MyGuiAudio.PlaySound(MyGuiSounds.HudClick); controlledObject.SwitchReactors(); } if (MyControllerHelper.IsControl(context, MyControlsSpace.LANDING_GEAR, MyControlStateType.NEW_PRESSED)) { MyGuiAudio.PlaySound(MyGuiSounds.HudClick); controlledObject.SwitchLeadingGears(); } if (MyControllerHelper.IsControl(context, MyControlsSpace.SUICIDE, MyControlStateType.NEW_PRESSED)) { controlledObject.Die(); } if ((controlledObject as MyCockpit) != null && MyControllerHelper.IsControl(context, MyControlsSpace.CUBE_COLOR_CHANGE, MyControlStateType.NEW_PRESSED)) { (controlledObject as MyCockpit).SwitchWeaponMode(); } } } if (MyControllerHelper.IsControl(context, MyControlsSpace.TERMINAL, MyControlStateType.NEW_PRESSED) && MyGuiScreenGamePlay.ActiveGameplayScreen == null) { MyGuiAudio.PlaySound(MyGuiSounds.HudClick); controlledObject.ShowTerminal(); } if (MyControllerHelper.IsControl(context, MyControlsSpace.INVENTORY, MyControlStateType.NEW_PRESSED) && MyGuiScreenGamePlay.ActiveGameplayScreen == null) { MyGuiAudio.PlaySound(MyGuiSounds.HudClick); controlledObject.ShowInventory(); } if (MyControllerHelper.IsControl(context, MyControlsSpace.CONTROL_MENU, MyControlStateType.NEW_PRESSED) && MyGuiScreenGamePlay.ActiveGameplayScreen == null) { MyGuiAudio.PlaySound(MyGuiSounds.HudClick); m_controlMenu.OpenControlMenu(controlledObject); } if (!MyCompilationSymbols.RenderProfiling && MyControllerHelper.IsControl(context, MyControlsSpace.CHAT_SCREEN, MyControlStateType.NEW_PRESSED)) { if (MyGuiScreenChat.Static == null) { Vector2 chatPos = new Vector2(0.01f, 0.84f); chatPos = MyGuiScreenHudBase.ConvertHudToNormalizedGuiPosition(ref chatPos); MyGuiScreenChat chatScreen = new MyGuiScreenChat(chatPos); MyGuiSandbox.AddScreen(chatScreen); } } } MoveAndRotatePlayerOrCamera(); // Quick save or quick load. if (MyInput.Static.IsNewKeyPressed(MyKeys.F5)) { MyGuiAudio.PlaySound(MyGuiSounds.HudMouseClick); var currentSession = MySession.Static.CurrentPath; if (MyInput.Static.IsAnyShiftKeyPressed()) { if (MySession.Static.ClientCanSave || Sync.IsServer) { if (!MyAsyncSaving.InProgress) { var messageBox = MyGuiSandbox.CreateMessageBox( buttonType : MyMessageBoxButtonsType.YES_NO, messageText : MyTexts.Get(MySpaceTexts.MessageBoxTextAreYouSureYouWantToQuickSave), messageCaption : MyTexts.Get(MySpaceTexts.MessageBoxCaptionPleaseConfirm), callback : delegate(MyGuiScreenMessageBox.ResultEnum callbackReturn) { if (callbackReturn == MyGuiScreenMessageBox.ResultEnum.YES) { MyAsyncSaving.Start(() => MySector.ResetEyeAdaptation = true); //black screen after save } }); messageBox.SkipTransition = true; messageBox.CloseBeforeCallback = true; MyGuiSandbox.AddScreen(messageBox); } } else { MyHud.Notifications.Add(MyNotificationSingletons.ClientCannotSave); } } else if (Sync.IsServer) { ShowLoadMessageBox(currentSession); } else { // Is multiplayer client, reconnect ShowReconnectMessageBox(); } } // Launch main menu if (MyInput.Static.IsNewKeyPressed(MyKeys.Escape) || MyControllerHelper.IsControl(context, MyControlsGUI.MAIN_MENU, MyControlStateType.NEW_PRESSED)) { MyGuiAudio.PlaySound(MyGuiSounds.HudMouseClick); //Allow changing video options from game in DX version MyGuiScreenMainMenu.AddMainMenu(); } if (MyInput.Static.IsNewKeyPressed(MyKeys.F3)) { if (Sync.MultiplayerActive) { MyGuiAudio.PlaySound(MyGuiSounds.HudMouseClick); MyGuiSandbox.AddScreen(new MyGuiScreenPlayers()); } else { MyHud.Notifications.Add(MyNotificationSingletons.MultiplayerDisabled); } } if (MyInput.Static.IsNewGameControlPressed(MyControlsSpace.BUILD_SCREEN) && MyGuiScreenGamePlay.ActiveGameplayScreen == null) { if (MyGuiScreenCubeBuilder.Static == null && (MySession.ControlledEntity is MyShipController || MySession.ControlledEntity is MyCharacter)) { int offset = 0; if (MyInput.Static.IsAnyShiftKeyPressed()) { offset += 6; } if (MyInput.Static.IsAnyCtrlKeyPressed()) { offset += 12; } MyGuiAudio.PlaySound(MyGuiSounds.HudMouseClick); MyGuiSandbox.AddScreen( MyGuiScreenGamePlay.ActiveGameplayScreen = MyGuiSandbox.CreateScreen(MyPerGameSettings.GUI.ToolbarConfigScreen, offset, MySession.ControlledEntity as MyShipController) ); } } if (MyInput.Static.IsNewGameControlPressed(MyControlsSpace.PAUSE_GAME)) { MySandboxGame.UserPauseToggle(); } if (MySession.Static != null) { if (MyInput.Static.IsNewKeyPressed(MyKeys.F10)) { if (MyPerGameSettings.GUI.VoxelMapEditingScreen != null && MySession.Static.CreativeMode && MyInput.Static.IsAnyShiftKeyPressed()) { // Shift+F10 MyGuiSandbox.AddScreen(MyGuiSandbox.CreateScreen(MyPerGameSettings.GUI.VoxelMapEditingScreen)); } else { // F10 if (MyFakes.ENABLE_BATTLE_SYSTEM && MySession.Static.Battle) { if (MyPerGameSettings.GUI.BattleBlueprintScreen != null) { MyGuiSandbox.AddScreen(MyGuiSandbox.CreateScreen(MyPerGameSettings.GUI.BattleBlueprintScreen)); } else { Debug.Fail("No battle blueprint screen"); } } else { MyGuiSandbox.AddScreen(new MyGuiBlueprintScreen(MyCubeBuilder.Static.Clipboard)); } } } } // F11, mod debug if (MyInput.Static.IsNewKeyPressed(MyKeys.F11) && !MyInput.Static.IsAnyShiftKeyPressed() && !MyInput.Static.IsAnyCtrlKeyPressed()) { MyDX9Gui.SwitchModDebugScreen(); } }
// CH: TODO: This is here just temporarily. We should move it to a better place later public virtual void AfterCharacterCreate(MyCharacter character) { }
// Update position, check collisions, etc. // Return false if projectile dies/timeouts in this tick. public bool Update() { // Projectile was killed , but still not last time drawn, so we don't need to do update (we are waiting for last draw) if (m_state == MyProjectileStateEnum.KILLED) { return(true); } // Projectile was killed and last time drawn, so we can finally remove it from buffer if (m_state == MyProjectileStateEnum.KILLED_AND_DRAWN) { StopEffect(); return(false); } Vector3D position = m_position; m_position += m_velocity * MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS; // Distance timeout Vector3 positionDelta = m_position - m_origin; if (Vector3.Dot(positionDelta, positionDelta) >= m_maxTrajectory * m_maxTrajectory) { StopEffect(); m_state = MyProjectileStateEnum.KILLED; return(true); } m_checkIntersectionIndex = ++m_checkIntersectionIndex % CHECK_INTERSECTION_INTERVAL; if (m_checkIntersectionIndex != 0 && m_positionChecked) //check only each n-th intersection { return(true); } // Calculate hit point, create decal and throw debris particles Vector3D lineEndPosition = position + CHECK_INTERSECTION_INTERVAL * (m_velocity * MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS); LineD line = new LineD(m_positionChecked ? position : m_origin, lineEndPosition); m_positionChecked = true; IMyEntity entity; Vector3D hitPosition; Vector3 hitNormal; bool headShot; GetHitEntityAndPosition(line, out entity, out hitPosition, out hitNormal, out headShot); if (entity == null || entity == m_ignoreEntity || entity.Physics == null) { return(true); } ProfilerShort.Begin("Projectile.Update"); { MyCharacter hitCharacter = entity as MyCharacter; if (hitCharacter != null) { IStoppableAttackingTool stoppableTool = hitCharacter.CurrentWeapon as IStoppableAttackingTool; if (stoppableTool != null) { stoppableTool.StopShooting(OwnerEntity); } } } m_position = hitPosition; bool isProjectileGroupKilled = false; if (!isProjectileGroupKilled) { MySurfaceImpactEnum surfaceImpact; MyStringHash materialType; GetSurfaceAndMaterial(entity, ref hitPosition, out surfaceImpact, out materialType); PlayHitSound(materialType, entity, hitPosition); DoDamage(headShot ? m_projectileAmmoDefinition.ProjectileHeadShotDamage : m_projectileAmmoDefinition.ProjectileMassDamage, hitPosition, entity); // Create smoke and debris particle at the place of voxel/model hit if (surfaceImpact != MySurfaceImpactEnum.CHARACTER) { m_projectileAmmoDefinition.ProjectileOnHitParticles(ref hitPosition, ref hitNormal, ref line.Direction, entity, m_weapon, 1, OwnerEntity); } m_projectileAmmoDefinition.ProjectileOnHitMaterialParticles(ref hitPosition, ref hitNormal, ref line.Direction, entity, surfaceImpact, m_weapon, 1); CreateDecal(materialType); if (m_weapon == null || (entity.GetTopMostParent() != m_weapon.GetTopMostParent())) { ApplyProjectileForce(entity, hitPosition, m_directionNormalized, false, m_projectileAmmoDefinition.ProjectileHitImpulse * m_impulseMultiplier); } StopEffect(); m_state = MyProjectileStateEnum.KILLED; } ProfilerShort.End(); return(true); }
public override void RecreateControls(bool constructor) { base.RecreateControls(constructor); m_scale = 0.7f; AddCaption("Render Character", Color.Yellow.ToVector4()); AddShareFocusHint(); m_currentPosition = -m_size.Value / 2.0f + new Vector2(0.02f, 0.10f); m_currentPosition.Y += 0.01f; if (MySession.Static.ControlledEntity == null || !(MySession.Static.ControlledEntity is MyCharacter)) { AddLabel("None active character", Color.Yellow.ToVector4(), 1.2f); return; } MyCharacter playerCharacter = MySession.Static.LocalCharacter; if (!constructor) { playerCharacter.DebugMode = true; } AddSlider("Max slope", playerCharacter.Definition.MaxSlope, 0f, 89f, (slider) => { playerCharacter.Definition.MaxSlope = slider.Value; }); AddLabel(playerCharacter.Model.AssetName, Color.Yellow.ToVector4(), 1.2f); AddLabel("Animation A:", Color.Yellow.ToVector4(), 1.2f); m_animationComboA = AddCombo(); int i = 0; foreach (var animation in playerCharacter.Definition.AnimationNameToSubtypeName) { m_animationComboA.AddItem(i++, new StringBuilder(animation.Key)); } m_animationComboA.SelectItemByIndex(0); AddLabel("Animation B:", Color.Yellow.ToVector4(), 1.2f); m_animationComboB = AddCombo(); i = 0; foreach (var animation in playerCharacter.Definition.AnimationNameToSubtypeName) { m_animationComboB.AddItem(i++, new StringBuilder(animation.Key)); } m_animationComboB.SelectItemByIndex(0); m_blendSlider = AddSlider("Blend time", 0.5f, 0, 3, null); AddButton(new StringBuilder("Play A->B"), OnPlayBlendButtonClick); m_currentPosition.Y += 0.01f; m_animationCombo = AddCombo(); i = 0; foreach (var animation in playerCharacter.Definition.AnimationNameToSubtypeName) { m_animationCombo.AddItem(i++, new StringBuilder(animation.Key)); } m_animationCombo.SortItemsByValueText(); m_animationCombo.SelectItemByIndex(0); m_loopCheckbox = AddCheckBox("Loop", false, null); m_currentPosition.Y += 0.02f; foreach (var name in playerCharacter.Definition.BoneSets.Keys) { var checkBox = AddCheckBox(name, false, null); checkBox.UserData = name; if (name == "Body") { checkBox.IsChecked = true; } } AddButton(new StringBuilder("Play animation"), OnPlayButtonClick); AddCheckBox("Draw damage and hit hapsules", () => MyDebugDrawSettings.DEBUG_DRAW_SHOW_DAMAGE, (s) => MyDebugDrawSettings.DEBUG_DRAW_SHOW_DAMAGE = s); m_currentPosition.Y += 0.01f; }
private void ActivateCommon() { BoundingSphereD globalSphere = new BoundingSphereD(Vector3D.Transform(m_detectorSphere.Center, CubeGrid.WorldMatrix), m_detectorSphere.Radius); if (MyDebugDrawSettings.ENABLE_DEBUG_DRAW) { MyRenderProxy.DebugDrawSphere(globalSphere.Center, (float)globalSphere.Radius, Color.Red.ToVector3(), 1.0f, false); } m_isActivatedOnSomething = false; ProfilerShort.Begin("Query"); var res = MyEntities.GetTopMostEntitiesInSphere(ref globalSphere); m_entitiesInContact.Clear(); foreach (MyEntity entity in res) { var rootEntity = entity.GetTopMostParent(); if (CanInteractWith(rootEntity)) { m_entitiesInContact.Add(rootEntity); } } res.Clear(); ProfilerShort.End(); //TODO:cache blocks on this grid foreach (var entry in m_entitiesInContact) { MyCubeGrid grid = entry as MyCubeGrid; MyCharacter character = entry as MyCharacter; if (grid != null) { m_tempBlocksBuffer.Clear(); grid.GetBlocksInsideSphere(ref globalSphere, m_tempBlocksBuffer); m_blocksToActivateOn.UnionWith(m_tempBlocksBuffer); } if (character != null && Sync.IsServer) { MyStringHash damageType = MyDamageType.Drill; if (this is IMyShipGrinder) { damageType = MyDamageType.Grind; } else if (this is IMyShipWelder) { damageType = MyDamageType.Weld; } if (globalSphere.Intersects(character.PositionComp.WorldAABB)) { character.DoDamage(20, damageType, true, attackerId: EntityId); } } } m_isActivatedOnSomething |= Activate(m_blocksToActivateOn); m_activateCounter++; m_lastTimeActivate = MySandboxGame.TotalGamePlayTimeInMilliseconds; PlayLoopSound(m_isActivatedOnSomething); m_blocksToActivateOn.Clear(); }
private void DrawJetpackThrusts(bool updateCalled) { MyCharacter character = m_skinnedEntity as MyCharacter; if (character == null || character.GetCurrentMovementState() == MyCharacterMovementEnum.Died) { return; } var jetpack = character.JetpackComp; if (jetpack == null || !jetpack.CanDrawThrusts) { return; } var thrustComponent = Container.Get <MyEntityThrustComponent>(); if (thrustComponent == null) { return; } //VRageRender.MyRenderProxy.DebugDrawLine3D(WorldMatrix.Translation, WorldMatrix.Translation + Physics.LinearAcceleration, Color.White, Color.Green, false); var worldToLocal = MatrixD.Invert(Container.Entity.PositionComp.WorldMatrix); foreach (MyJetpackThrust thrust in m_jetpackThrusts) { Vector3D position = Vector3D.Zero; if ((jetpack.TurnedOn && jetpack.IsPowered) && (!character.IsInFirstPersonView || character != MySession.Static.LocalCharacter)) { var thrustMatrix = (MatrixD)thrust.ThrustMatrix * Container.Entity.PositionComp.WorldMatrix; Vector3D forward = Vector3D.TransformNormal(thrust.Forward, thrustMatrix); position = thrustMatrix.Translation; position += forward * thrust.Offset; float flameScale = 0.05f; if (updateCalled) { thrust.ThrustRadius = MyUtils.GetRandomFloat(0.9f, 1.1f) * flameScale; } float strength = Vector3.Dot(forward, -Vector3.Transform(thrustComponent.FinalThrust, Entity.WorldMatrix.GetOrientation()) / Entity.Physics.Mass); strength = MathHelper.Clamp(strength * 0.09f, 0.1f, 1f); if (strength > 0 && thrust.ThrustRadius > 0) { float angle = 1 - Math.Abs(Vector3.Dot(MyUtils.Normalize(MySector.MainCamera.Position - position), forward)); float alphaCone = (1 - (float)Math.Pow(1 - angle, 30)) * 0.5f; if (updateCalled) { thrust.ThrustLength = strength * 10 * MyUtils.GetRandomFloat(0.6f, 1.0f) * flameScale; thrust.ThrustThickness = MyUtils.GetRandomFloat(thrust.ThrustRadius * 0.90f, thrust.ThrustRadius); } // We move polyline particle backward, because we are stretching ball texture and it doesn't look good if stretched. This will hide it. MyTransparentGeometry.AddLineBillboard(thrust.ThrustMaterial, thrust.Light.Color * alphaCone * strength, position, GetRenderObjectID(), ref worldToLocal, forward, thrust.ThrustLength, thrust.ThrustThickness, MyBillboard.BlenType.AdditiveBottom); } if (thrust.ThrustRadius > 0) { MyTransparentGeometry.AddPointBillboard(thrust.ThrustMaterial, thrust.Light.Color, position, GetRenderObjectID(), ref worldToLocal, thrust.ThrustRadius, 0, -1, MyBillboard.BlenType.AdditiveBottom); } } else { if (updateCalled || (character.IsUsing != null)) { thrust.ThrustRadius = 0; } } if (thrust.Light != null) { if (thrust.ThrustRadius > 0) { thrust.Light.LightOn = true; thrust.Light.Intensity = JETPACK_LIGHT_INTENSITY_BASE + thrust.ThrustLength * JETPACK_LIGHT_INTENSITY_LENGTH; thrust.Light.Range = thrust.ThrustRadius * JETPACK_LIGHT_RANGE_RADIUS + thrust.ThrustLength * JETPACK_LIGHT_RANGE_LENGTH; thrust.Light.Position = Vector3D.Transform(position, MatrixD.Invert(Container.Entity.PositionComp.WorldMatrix)); thrust.Light.ParentID = GetRenderObjectID(); thrust.Light.GlareOn = true; thrust.Light.GlareIntensity = JETPACK_GLARE_INTENSITY_BASE + thrust.ThrustLength * JETPACK_GLARE_INTENSITY_LENGTH; thrust.Light.GlareMaterial = "GlareJetpack"; thrust.Light.GlareType = VRageRender.Lights.MyGlareTypeEnum.Normal; thrust.Light.GlareSize = (thrust.ThrustRadius * JETPACK_GLARE_SIZE_RADIUS + thrust.ThrustLength * JETPACK_GLARE_SIZE_LENGTH) * thrust.ThrustGlareSize; thrust.Light.GlareQuerySize = 0.1f; thrust.Light.UpdateLight(); } else { thrust.Light.GlareOn = false; thrust.Light.LightOn = false; thrust.Light.UpdateLight(); } } } }
public void OnControlAcquired(MyCharacter owner) { }
public override void Unequip() { MyCharacter.SetupEquipmentLogic(this, false); }
public MyAsteroidsDebugInputComponent() { AddShortcut(MyKeys.NumPad1, true, false, false, false, () => "Debug draw procedural asteroid seeds: " + m_drawSeeds, delegate { m_drawSeeds = !m_drawSeeds; return(true); }); AddShortcut(MyKeys.NumPad3, true, false, false, false, () => "Debug draw procedural tracked entities: " + m_drawTrackedEntities, delegate { m_drawTrackedEntities = !m_drawTrackedEntities; return(true); }); AddShortcut(MyKeys.NumPad4, true, false, false, false, () => "Toggle farplane distance: " + (MySector.MainCamera == null ? -1f : MySector.MainCamera.FarPlaneDistance), delegate { m_fakeFarPlaneDistance = !m_fakeFarPlaneDistance; if (m_originalFarPlaneDisatance == -1) { m_originalFarPlaneDisatance = MySector.MainCamera.FarPlaneDistance; } if (m_fakeFarPlaneDistance) { MySector.MainCamera.FarPlaneDistance = m_debugFarPlaneDistance; } else { MySector.MainCamera.FarPlaneDistance = m_originalFarPlaneDisatance; } return(true); }); AddShortcut(MyKeys.NumPad5, true, false, false, false, () => "Debug draw procedural seed radius: " + m_drawRadius, delegate { m_drawRadius = !m_drawRadius; return(true); }); AddShortcut(MyKeys.NumPad6, true, false, false, false, () => "Debug draw procedural seed distance: " + m_drawDistance, delegate { m_drawDistance = !m_drawDistance; return(true); }); AddShortcut(MyKeys.NumPad7, true, false, false, false, () => "Toggle fog: " + MySector.FogProperties.EnableFog, delegate { MySector.FogProperties.EnableFog = !MySector.FogProperties.EnableFog; return(true); }); AddShortcut(MyKeys.NumPad8, true, false, false, false, () => "Debug draw procedural cells: " + m_drawCells, delegate { m_drawCells = !m_drawCells; return(true); }); AddShortcut(MyKeys.NumPad9, true, false, false, false, () => "Spawn new moving player somewhere: " + m_plys.Count, delegate { var pos = new Vector3D(MyRandom.Instance.NextFloat() * 2 - 1f, MyRandom.Instance.NextFloat() * 2 - 1f, MyRandom.Instance.NextFloat() * 2 - 1f) * 150000; var vel = new Vector3(MyRandom.Instance.NextFloat() * 2 - 1f, MyRandom.Instance.NextFloat() * 2 - 1f, MyRandom.Instance.NextFloat() * 2 - 1f); vel.Normalize(); var ply = MyCharacter.CreateCharacter(MatrixD.CreateTranslation(pos), vel * 100 * (MyRandom.Instance.NextFloat() * 0.5f + 0.5f), "ALIEN SPACE NINJA", MyCharacter.DefaultModel, null, false); m_plys.Add(ply); return(true); }); AddShortcut(MyKeys.NumPad0, true, false, false, false, () => "Remove one spawned player: " + m_plys.Count, delegate { if (m_plys.Count == 0) { return(false); } var ply = m_plys[0]; m_plys.Remove(ply); ply.Close(); return(true); }); }
private bool TryFindValidHumanInArea(int standingRadius, int crouchingRadius, out MyCharacter foundCharacter) { var position = m_bot.AgentEntity.PositionComp.GetPosition(); var forward = m_bot.AgentEntity.PositionComp.WorldMatrix.Forward; var players = Sync.Players.GetOnlinePlayers(); foreach (var player in players) { if (player.Id.SerialId != 0 && MyAIComponent.Static.Bots.GetBotType(player.Id.SerialId) != BotType.HUMANOID) { continue; } if (player.Character != null && !player.Character.MarkedForClose && !player.Character.IsDead) { var characterPosition = player.Character.PositionComp.GetPosition(); var vectorToTarget = characterPosition - position; vectorToTarget.Y = 0; var distance = vectorToTarget.Normalize(); bool matchCriterion = false; if (distance < standingRadius) { if (Vector3D.Dot(vectorToTarget, forward) > COS15) { matchCriterion = true; } else if (player.Character.IsCrouching && !player.Character.IsSprinting) { matchCriterion = distance < crouchingRadius; } else { matchCriterion = true; } } if (matchCriterion) { foundCharacter = player.Character; return(true); } } } foundCharacter = null; return(false); }
public override void Equip() { MyCharacter.SetupEquipmentLogic(this, true); }
public override void OnAddedToContainer(MyComponentContainer container) { base.OnAddedToContainer(container); m_character = Entity as MyCharacter; }
private void DoDetection(bool useHead, bool doModelIntersection) { bool flag; if (ReferenceEquals(base.Character, MySession.Static.ControlledEntity)) { MyHud.SelectedObjectHighlight.RemoveHighlight(); } MatrixD xd = base.Character.GetHeadMatrix(false, true, false, false, false); Vector3D translation = xd.Translation; Vector3D forward = xd.Forward; if (!useHead) { Vector3D planePoint = xd.Translation - (xd.Forward * 0.3); if (!ReferenceEquals(base.Character, MySession.Static.LocalCharacter)) { translation = planePoint; forward = xd.Forward; } else { translation = MySector.MainCamera.WorldMatrix.Translation; forward = MySector.MainCamera.WorldMatrix.Forward; translation = MyUtils.LinePlaneIntersection(planePoint, (Vector3)forward, translation, (Vector3)forward); } } Vector3D to = translation + (forward * 2.5); base.StartPosition = translation; MatrixD transform = MatrixD.CreateTranslation(translation); HkShape shape = (HkShape) new HkSphereShape(this.ShapeRadius); IMyEntity objA = null; base.ShapeKey = uint.MaxValue; base.HitPosition = Vector3D.Zero; base.HitNormal = Vector3.Zero; base.HitMaterial = MyStringHash.NullOrEmpty; base.HitTag = null; this.m_hits.Clear(); Vector3 zero = (Vector3)Vector3D.Zero; try { bool flag2; bool flag3; int num; base.EnableDetectorsInArea(translation); MyPhysics.CastShapeReturnContactBodyDatas(to, shape, ref transform, 0, 0f, this.m_hits, true); this.m_rayOrigin = translation; this.m_rayDirection = forward; this.m_hits.Sort(new Comparison <MyPhysics.HitInfo>(this.CompareHits)); if (this.m_hits.Count <= 0) { goto TR_0012; } else { flag2 = false; flag3 = false; num = 0; } goto TR_002F; TR_0017: num++; TR_002F: while (true) { if (num >= this.m_hits.Count) { break; } HkRigidBody hkEntity = this.m_hits[num].HkHitInfo.Body; IMyEntity hitEntity = this.m_hits[num].HkHitInfo.GetHitEntity(); if (!ReferenceEquals(hitEntity, base.Character)) { int num1; if (hitEntity is MyEntitySubpart) { hitEntity = hitEntity.Parent; } if (((hkEntity == null) || (hitEntity == null)) || ReferenceEquals(hitEntity, base.Character)) { num1 = 0; } else { num1 = (int)!hkEntity.HasProperty(HkCharacterRigidBody.MANIPULATED_OBJECT); } flag2 = (bool)num1; flag3 = (hitEntity != null) && (hitEntity.Physics != null); if (ReferenceEquals(objA, null) & flag2) { objA = hitEntity; base.ShapeKey = this.m_hits[num].HkHitInfo.GetShapeKey(0); } if (hitEntity is MyCubeGrid) { List <MyCube> list = (hitEntity as MyCubeGrid).RayCastBlocksAllOrdered(translation, to); if ((list != null) && (list.Count > 0)) { MySlimBlock cubeBlock = list[0].CubeBlock; if (cubeBlock.FatBlock != null) { flag3 = true; objA = cubeBlock.FatBlock; base.ShapeKey = 0; } } } if (!((base.HitMaterial.Equals(MyStringHash.NullOrEmpty) & flag2) & flag3)) { if (hkEntity == null) { num++; goto TR_0017; } else { zero = this.m_hits[num].GetFixedPosition(); } } else { base.HitBody = hkEntity; base.HitNormal = this.m_hits[num].HkHitInfo.Normal; base.HitPosition = this.m_hits[num].GetFixedPosition(); base.HitMaterial = hkEntity.GetBody().GetMaterialAt(base.HitPosition); zero = (Vector3)base.HitPosition; } break; } goto TR_0017; } } finally { shape.RemoveReference(); } TR_0012: flag = false; IMyUseObject interactive = objA as IMyUseObject; base.DetectedEntity = objA; if (objA != null) { MyUseObjectsComponentBase component = null; objA.Components.TryGet <MyUseObjectsComponentBase>(out component); if (component != null) { interactive = component.GetInteractiveObject(base.ShapeKey); } if (doModelIntersection) { LineD line = new LineD(translation, to); MyCharacter character = objA as MyCharacter; if (character == null) { MyIntersectionResultLineTriangleEx?nullable; if (objA.GetIntersectionWithLine(ref line, out nullable, IntersectionFlags.ALL_TRIANGLES)) { base.HitPosition = nullable.Value.IntersectionPointInWorldSpace; base.HitNormal = nullable.Value.NormalInWorldSpace; } } else if (character.GetIntersectionWithLine(ref line, ref base.CharHitInfo, IntersectionFlags.ALL_TRIANGLES)) { base.HitPosition = base.CharHitInfo.Triangle.IntersectionPointInWorldSpace; base.HitNormal = base.CharHitInfo.Triangle.NormalInWorldSpace; base.HitTag = base.CharHitInfo; } } } if (((interactive != null) && ((interactive.SupportedActions != UseActionEnum.None) && (Vector3D.Distance(translation, zero) < interactive.InteractiveDistance))) && ReferenceEquals(base.Character, MySession.Static.ControlledEntity)) { HandleInteractiveObject(interactive); base.UseObject = interactive; flag = true; } if (!flag) { base.UseObject = null; } base.DisableDetectors(); }
public virtual bool IsMemoryTargetValid(MyBBMemoryTarget targetMemory) { if (targetMemory == null) { return(false); } switch (targetMemory.TargetType) { case MyAiTargetEnum.CHARACTER: { MyCharacter target = null; if (MyEntities.TryGetEntityById(targetMemory.EntityId.Value, out target)) { return(IsEntityReachable(target)); } else { return(false); } } case MyAiTargetEnum.CUBE: case MyAiTargetEnum.COMPOUND_BLOCK: { MyCubeGrid target = null; if (MyEntities.TryGetEntityById(targetMemory.EntityId.Value, out target)) { MySlimBlock block = target.GetCubeBlock(targetMemory.BlockPosition); if (block == null) { return(false); } if (block.FatBlock != null) { return(IsEntityReachable(block.FatBlock)); } else { return(IsEntityReachable(target)); } } else { return(false); } } case MyAiTargetEnum.VOXEL: case MyAiTargetEnum.ENVIRONMENT_ITEM: return(true); case MyAiTargetEnum.ENTITY: case MyAiTargetEnum.GRID: MyEntity entity = null; if (MyEntities.TryGetEntityById(targetMemory.EntityId.Value, out entity)) { return(IsEntityReachable(entity)); } else { return(false); } default: return(false); } }
public override void Update() { base.Update(); if (IsAttacking) { int attackTime = MySandboxGame.TotalGamePlayTimeInMilliseconds - m_attackStart; if (attackTime > ATTACK_LENGTH) { IsAttacking = false; MyCharacter botEntity = m_bot.AgentEntity; if (botEntity != null) { botEntity.EnableAnimationCommands(); } } else if (attackTime > 500 && m_bot.AgentEntity.UseNewAnimationSystem) { m_bot.AgentEntity.AnimationController.TriggerAction(m_stringIdAttackAction); if (Sync.IsServer) { MyMultiplayer.RaiseStaticEvent(x => PlayAttackAnimation, m_bot.AgentEntity.EntityId); } } if (attackTime > 500 && !m_attackPerformed) { MyCharacter botEntity = m_bot.AgentEntity; if (botEntity != null) { Vector3D attackPosition = botEntity.WorldMatrix.Translation + botEntity.PositionComp.WorldMatrix.Forward * 2.5 + botEntity.PositionComp.WorldMatrix.Up * 1.0; m_attackBoundingSphere = new BoundingSphereD(attackPosition, 1.1); m_attackPerformed = true; List <MyEntity> hitEntities = MyEntities.GetTopMostEntitiesInSphere(ref m_attackBoundingSphere); foreach (var hitEntity in hitEntities) { //AttackEntity(hitEntity); if (hitEntity is MyCharacter && hitEntity != botEntity) { var character = hitEntity as MyCharacter; if (character.IsSitting) { continue; } var characterVolume = character.PositionComp.WorldVolume; double touchDistSq = m_attackBoundingSphere.Radius + characterVolume.Radius; touchDistSq = touchDistSq * touchDistSq; if (Vector3D.DistanceSquared(m_attackBoundingSphere.Center, characterVolume.Center) > touchDistSq) { continue; } if (character.IsDead) { var inventory = character.GetInventory(); if (inventory == null) { continue; } if (m_bot.AgentEntity == null) { continue; } var cyberhoundInventory = m_bot.AgentEntity.GetInventory(); if (cyberhoundInventory == null) { continue; } MyInventory.TransferAll(inventory, cyberhoundInventory); } else { character.DoDamage(ATTACK_DAMAGE_TO_CHARACTER, MyDamageType.Bolt, updateSync: true, attackerId: botEntity.EntityId); } } else if (hitEntity is MyCubeGrid && hitEntity.Physics != null) { var grid = hitEntity as MyCubeGrid; m_tmpBlocks.Clear(); grid.GetBlocksInsideSphere(ref m_attackBoundingSphere, m_tmpBlocks); foreach (var block in m_tmpBlocks) { block.DoDamage(ATTACK_DAMAGE_TO_GRID, MyDamageType.Bolt); } m_tmpBlocks.Clear(); } } hitEntities.Clear(); } } if (attackTime > 500) { //MyRenderProxy.DebugDrawSphere(m_attackBoundingSphere.Center, (float)m_attackBoundingSphere.Radius, Color.Red, 1.0f, false); } } }
public virtual bool Update(MyCharacter me) { return(IsTrue); }
public override void Draw() { base.Draw(); MyCharacter character = m_skinnedEntity as MyCharacter; Matrix headMatrix = character.GetHeadMatrix(false); Vector3 position = m_light.Position; Vector3 forwardVector = m_light.ReflectorDirection; Vector3 leftVector = headMatrix.Left; Vector3 upVector = headMatrix.Up; float reflectorLength = MyCharacter.REFLECTOR_BILLBOARD_LENGTH * 0.4f * 0.16f; float reflectorThickness = MyCharacter.REFLECTOR_BILLBOARD_THICKNESS * 0.08f; //float reflectorRadiusForAdditive = 0.25f;//0.65f; Vector3 color = new Vector3(m_light.ReflectorColor); Vector3 glarePosition = position + forwardVector * 0.28f; var dot = Vector3.Dot(Vector3.Normalize(MySector.MainCamera.Position - glarePosition), forwardVector); float angle = 1 - Math.Abs(dot); float alphaGlareAlphaBlended = (float)Math.Pow(1 - angle, 2); float alphaCone = (1 - (float)Math.Pow(1 - angle, 30)) * 0.5f; float reflectorRadiusForAlphaBlended = MathHelper.Lerp(0.1f, 0.5f, alphaGlareAlphaBlended); //3.5f; // Multiply alpha by reflector level (and not the color), because if we multiply the color and let alpha unchanged, reflector cune will be drawn as very dark cone, but still visible var reflectorLevel = character.CurrentLightPower; alphaCone *= reflectorLevel * 0.2f; alphaGlareAlphaBlended *= reflectorLevel * 0.1f; float distance = Vector3.Distance(character.PositionComp.GetPosition(), MySector.MainCamera.Position); if ((character != MySession.Static.LocalCharacter || !character.IsInFirstPersonView) && distance < MyCharacter.LIGHT_GLARE_MAX_DISTANCE && reflectorLevel > 0) { float alpha = MathHelper.Clamp((MyCharacter.LIGHT_GLARE_MAX_DISTANCE - 10.0f) / distance, 0, 1); if (reflectorLength > 0 && reflectorThickness > 0) { if (m_leftGlare != null) { MyTransparentGeometry.AddLineBillboard("ReflectorConeCharacter", new Vector4(color, 1.0f) * alphaCone * alpha, m_leftGlare.Position, m_leftGlare.ReflectorDirection, reflectorLength, reflectorThickness, MyBillboard.BlenType.AdditiveBottom); } if (m_rightGlare != null) { MyTransparentGeometry.AddLineBillboard("ReflectorConeCharacter", new Vector4(color, 1.0f) * alphaCone * alpha, m_rightGlare.Position, m_rightGlare.ReflectorDirection, reflectorLength, reflectorThickness, MyBillboard.BlenType.AdditiveBottom); } } if (m_leftGlare != null) { MyTransparentGeometry.AddPointBillboard("ReflectorGlareAlphaBlended", new Vector4(color, 1.0f) * alphaGlareAlphaBlended * alpha, m_leftGlare.Position, reflectorRadiusForAlphaBlended * 0.3f, 0, -1, MyBillboard.BlenType.AdditiveTop); } if (m_rightGlare != null) { MyTransparentGeometry.AddPointBillboard("ReflectorGlareAlphaBlended", new Vector4(color, 1.0f) * alphaGlareAlphaBlended * alpha, m_rightGlare.Position, reflectorRadiusForAlphaBlended * 0.3f, 0, -1, MyBillboard.BlenType.AdditiveTop); } } DrawJetpackThrusts(character.UpdateCalled()); if (character.Hierarchy.Parent != null) { if (m_leftGlare != null && m_leftGlare.LightOn == true) { m_leftGlare.LightOn = false; m_leftGlare.GlareOn = false; m_leftGlare.UpdateLight(); } if (m_rightGlare != null && m_rightGlare.LightOn == true) { m_rightGlare.LightOn = false; m_rightGlare.GlareOn = false; m_rightGlare.UpdateLight(); } } else { if (m_leftGlare != null && m_leftGlare.LightOn == false) { m_leftGlare.LightOn = true; m_leftGlare.GlareOn = true; m_leftGlare.UpdateLight(); } if (m_rightGlare != null && m_rightGlare.LightOn == true) { m_rightGlare.LightOn = true; m_rightGlare.GlareOn = true; m_rightGlare.UpdateLight(); } } //Maybe this check is not needed at all? In every case we want the DrawBlood effect when damaged if (MySession.Static.ControlledEntity == character || MySession.Static.ControlledEntity is MyCockpit && ((MyCockpit)MySession.Static.ControlledEntity).Pilot == character || MySession.Static.ControlledEntity is MyLargeTurretBase && ((MyLargeTurretBase)MySession.Static.ControlledEntity).Pilot == character ) { if (character.IsDead && character.CurrentRespawnCounter > 0) { DrawBlood(1); } if (!character.IsDead && m_currentHitIndicatorCounter > 0) { m_currentHitIndicatorCounter -= VRage.Game.MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS; if (m_currentHitIndicatorCounter < 0) { m_currentHitIndicatorCounter = 0; } float alpha = m_currentHitIndicatorCounter / HIT_INDICATOR_LENGTH; DrawBlood(alpha); } if (character.StatComp != null) { var healthRatio = character.StatComp.HealthRatio; if (healthRatio <= MyCharacterStatComponent.LOW_HEALTH_RATIO && !character.IsDead) { float alpha = MathHelper.Clamp(MyCharacterStatComponent.LOW_HEALTH_RATIO - healthRatio, 0, 1) / MyCharacterStatComponent.LOW_HEALTH_RATIO + 0.3f; DrawBlood(alpha); } } } //DebugDraw(); }
public virtual void OnCharacterControlAcquired(MyCharacter character) { }
public void SpawnAtShip(MyPlayer player, string respawnShipId) { Debug.Assert(Sync.IsServer, "Spawning can only be called on the server!"); if (!Sync.IsServer) { return; } ResetRespawnCooldown(player.Id); if (Sync.MultiplayerActive) { SyncCooldownToPlayer(player.Id.SteamId); } MyCharacter character = null; MyCockpit cockpit = null; List <MyCubeGrid> respawnGrids = new List <MyCubeGrid>(); var respawnShipDef = MyDefinitionManager.Static.GetRespawnShipDefinition(respawnShipId); MyPrefabDefinition prefabDef = respawnShipDef.Prefab; // Deploy ship Vector3 direction, position; GetSpawnPosition(prefabDef.BoundingSphere.Radius, out direction, out position); MyPrefabManager.Static.SpawnPrefab( respawnGrids, prefabDef.Id.SubtypeName, position, -direction, Vector3.CalculatePerpendicularVector(-direction), spawningOptions: Sandbox.ModAPI.SpawningOptions.RotateFirstCockpitTowardsDirection, updateSync: true); // Find cockpit foreach (var grid in respawnGrids) { foreach (var block in grid.GetBlocks()) { if (block.FatBlock is MyCockpit) { cockpit = (MyCockpit)block.FatBlock; break; } } if (cockpit != null) { break; } } System.Diagnostics.Debug.Assert(cockpit != null, "character is spawning in ship without cockpit !"); // Create character Matrix matrix = Matrix.Identity; if (cockpit != null) { matrix = cockpit.WorldMatrix; matrix.Translation = cockpit.WorldMatrix.Translation - Vector3.Up - Vector3.Forward; } else if (respawnGrids.Count > 0) { matrix.Translation = respawnGrids[0].PositionComp.WorldAABB.Center + respawnGrids[0].PositionComp.WorldAABB.HalfExtents; } character = MyCharacter.CreateCharacter(matrix, Vector3.Zero, player.Identity.DisplayName, player.Identity.Model, null, cockpit: cockpit); if (cockpit != null) { cockpit.AttachPilot(character, false); } CloseRespawnShip(player); foreach (var respawnGrid in respawnGrids) { respawnGrid.ChangeGridOwnership(player.Identity.IdentityId, MyOwnershipShareModeEnum.None); player.RespawnShip.Add(respawnGrid.EntityId); } Sync.Players.SetPlayerCharacter(player, character, cockpit); Sync.Players.RevivePlayer(player); }
public NormalState(MyCharacter newCharacter) { character = newCharacter; }
protected bool CanHit(IMyHandToolComponent toolComponent, MyCharacterDetectorComponent detectorComponent, ref bool isBlock, out float hitEfficiency) { bool canHit = true; hitEfficiency = 1.0f; MyTuple <ushort, MyStringHash> message; // TODO(GoodAI/HonzaS): Take care when merging this line. // The null check was not encountered with hand tools different from the reward/punishment tool. if (detectorComponent.HitBody != null && detectorComponent.HitBody.UserObject is MyBlockingBody) { var blocking = detectorComponent.HitBody.UserObject as MyBlockingBody; if (blocking.HandTool.IsBlocking && blocking.HandTool.m_owner.StatComp != null && blocking.HandTool.m_owner.StatComp.CanDoAction(blocking.HandTool.m_shotHitCondition.StatsActionIfHit, out message)) { blocking.HandTool.m_owner.StatComp.DoAction(blocking.HandTool.m_shotHitCondition.StatsActionIfHit); if (!string.IsNullOrEmpty(blocking.HandTool.m_shotHitCondition.StatsModifierIfHit)) { blocking.HandTool.m_owner.StatComp.ApplyModifier(blocking.HandTool.m_shotHitCondition.StatsModifierIfHit); } isBlock = true; if (!string.IsNullOrEmpty(blocking.HandTool.m_shotToolAction.Value.StatsEfficiency)) { hitEfficiency = 1.0f - blocking.HandTool.m_owner.StatComp.GetEfficiencyModifier(blocking.HandTool.m_shotToolAction.Value.StatsEfficiency); } canHit = hitEfficiency > 0.0f; MyEntityContainerEventExtensions.RaiseEntityEventOn(blocking.HandTool, MyStringHash.GetOrCompute("Hit"), new MyEntityContainerEventExtensions.HitParams(MyStringHash.GetOrCompute("Block"), this.PhysicalItemDefinition.Id.SubtypeId)); } } if (!canHit) { hitEfficiency = 0.0f; return(canHit); } if (!string.IsNullOrEmpty(m_shotHitCondition.StatsActionIfHit)) { canHit = m_owner.StatComp != null && m_owner.StatComp.CanDoAction(m_shotHitCondition.StatsActionIfHit, out message); if (!canHit) { hitEfficiency = 0.0f; return(canHit); } } float hitDistance = Vector3.Distance(detectorComponent.HitPosition, PositionComp.GetPosition()); canHit = hitDistance <= m_toolItemDef.HitDistance; if (!canHit) { hitEfficiency = 0.0f; return(canHit); } // checking of player factions MyEntity attacker = m_owner.Entity; long attackerPlayerId = m_owner.GetPlayerIdentityId(); var localPlayerFaction = MySession.Static.Factions.TryGetPlayerFaction(attackerPlayerId) as MyFaction; if (localPlayerFaction != null && !localPlayerFaction.EnableFriendlyFire) { // friendy fire isn't enabled in attacker faction IMyEntity otherPlayerEntity = detectorComponent.DetectedEntity; MyCharacter otherPlayer = otherPlayerEntity as MyCharacter; if (otherPlayer != null) { bool sameFaction = localPlayerFaction.IsMember(otherPlayer.GetPlayerIdentityId()); canHit = !sameFaction; hitEfficiency = canHit ? hitEfficiency : 0.0f; } } return(canHit); }
public virtual void OnControlReleased() { RemoveHudInfo(); Owner = null; CharacterInventory = null; }
public MyDebugRenderComponentCharacter(MyCharacter character) : base(character) { m_character = character; }
public override void OnAddedToContainer() { base.OnAddedToContainer(); m_character = Container.Entity as MyCharacter; }
public void OnControlAcquired(MyCharacter owner) { m_owner = owner; m_isControlled = true; }
public override void UpdateGpsForPlayer(MyEntityTracker entity) { if (!(entity.Entity is MyCharacter)) { return; } var settings = MySettingsSession.Static.Settings.GeneratorSettings.GPSSettings; if (settings.AsteroidGPSMode != MyGPSGenerationMode.DISCOVERY) { return; } var objects = MyStarSystemGenerator.Static.StarSystem.GetAllObjects(); MyCharacter player = entity.Entity as MyCharacter; foreach (var obj in objects) { if (obj.Type != MySystemObjectType.ASTEROIDS) { continue; } MySystemAsteroids asteroid = obj as MySystemAsteroids; Vector3D entityPosition = player.PositionComp.GetPosition(); var provider = MyAsteroidObjectsManager.Static.AsteroidObjectProviders[asteroid.AsteroidTypeName]; IMyAsteroidObjectShape shape = provider.GetAsteroidObjectShape(asteroid); if (shape == null) { continue; } if (shape.Contains(entityPosition) != ContainmentType.Disjoint) { MyGPSManager.Static.RemoveDynamicGps(player.GetPlayerIdentityId(), asteroid.Id); } Vector3D closestPos = shape.GetClosestPoint(entityPosition); double distance = Vector3D.Subtract(entityPosition, closestPos).Length(); if (distance > 5000000) { MyGPSManager.Static.RemoveDynamicGps(player.GetPlayerIdentityId(), asteroid.Id); } else if (distance > 5) { if (MyGPSManager.Static.DynamicGpsExists(asteroid.Id, player.GetPlayerIdentityId())) { MyGPSManager.Static.ModifyDynamicGps(asteroid.DisplayName, Color.Yellow, closestPos, player.GetPlayerIdentityId(), asteroid.Id); continue; } MyGPSManager.Static.AddDynamicGps(asteroid.DisplayName, Color.Yellow, closestPos, player.GetPlayerIdentityId(), asteroid.Id); } else { MyGPSManager.Static.RemoveDynamicGps(player.GetPlayerIdentityId(), asteroid.Id); } } }
public static List <MyCubeGrid> FindGridList(string gridNameOrEntityId, MyCharacter character, bool includeConnectedGrids) { List <MyCubeGrid> grids = new List <MyCubeGrid>(); if (gridNameOrEntityId == null && character == null) { return(new List <MyCubeGrid>()); } if (includeConnectedGrids) { ConcurrentBag <MyGroups <MyCubeGrid, MyGridPhysicalGroupData> .Group> groups; if (gridNameOrEntityId == null) { groups = FindLookAtGridGroup(character); } else { groups = FindGridGroup(gridNameOrEntityId); } if (groups.Count > 1) { return(null); } foreach (var group in groups) { foreach (var node in group.Nodes) { MyCubeGrid grid = node.NodeData; if (grid.Physics == null) { continue; } grids.Add(grid); } } } else { ConcurrentBag <MyGroups <MyCubeGrid, MyGridMechanicalGroupData> .Group> groups; if (gridNameOrEntityId == null) { groups = FindLookAtGridGroupMechanical(character); } else { groups = FindGridGroupMechanical(gridNameOrEntityId); } if (groups.Count > 1) { return(null); } foreach (var group in groups) { foreach (var node in group.Nodes) { MyCubeGrid grid = node.NodeData; if (grid.Physics == null) { continue; } grids.Add(grid); } } } return(grids); }
public MyDebugRenderComponentCharacter(MyCharacter character) : base(character) { this.m_simulatedBonesDebugDraw = new List <Matrix>(); this.m_simulatedBonesAbsoluteDebugDraw = new List <Matrix>(); this.m_character = character; }
private static BootsState GetBootState(MyCharacter character) { return(character .GetInstanceFieldOrThrow <object>("m_bootsState") .GetInstanceFieldOrThrow <BootsState>("m_value")); }
public override void Simulate() { base.Simulate(); if (m_botPlayer != null) { if (m_botPlayer.Identity.IsDead) { if (!m_respawnRequestSent) { MyPlayerCollection.RespawnRequest(false, false, 0, null, m_botPlayer.Id.SerialId); m_respawnRequestSent = true; } } else { m_respawnRequestSent = false; // TODO: Add your bot logic here if (m_botPlayer.Character != null) { MyCharacter character = m_botPlayer.Character; // Moving and/or the character (run the game an you'll see what this code does...) character.MoveAndRotate(Vector3.Zero, new Vector2(0.0f, 10.0f), 0.0f); /* * // Enabling/disabling the jetpack * character.TurnOnJetpack(true); * character.TurnOnJetpack(false); * * // Querying position and orientation of the character: * Vector3D positionInWorld = character.PositionComp.GetPosition(); * Vector3D forwardUnitVector = character.PositionComp.WorldMatrix.Forward; * * // These can be found in KeenSWH\Sandbox\Sources\SpaceEngineers\Content\Data\PhysicalItems.sbc ... * MyDefinitionId welderDefId = new MyDefinitionId(typeof(MyObjectBuilder_PhysicalGunObject), "WelderItem"); * MyDefinitionId grinderDefId = new MyDefinitionId(typeof(MyObjectBuilder_PhysicalGunObject), "AngleGrinderItem"); * MyDefinitionId rifleDefId = new MyDefinitionId(typeof(MyObjectBuilder_PhysicalGunObject), "AutomaticRifleItem"); * * // Switching to rifle: * if (character.CanSwitchToWeapon(rifleDefId)) * { * character.SwitchToWeapon(rifleDefId); * } * else * { * // Switching failed, probably because the object was not in the inventory * } * * // Shooting with whatever you have in the hand * // (Note that after switching to a gun, you'll have to wait until it really is in your hand, which might take a while * // if you're the client and you're connected to a server.) * character.BeginShoot(MyShootActionEnum.PrimaryAction); * // Several frames later: * character.EndShoot(MyShootActionEnum.PrimaryAction); * * // Getting entities in an area of 10m around the character: * BoundingSphereD sphere = new BoundingSphereD(positionInWorld, 10.0f); * List<MyEntity> result = MyEntities.GetEntitiesInSphere(ref sphere); * foreach (MyEntity entity in result) * { * // We only want to check CubeGrids, for example (i.e. stations and ships) * MyCubeGrid grid = entity as MyCubeGrid; * if (grid != null) * { * HashSet<MySlimBlock> blocks = new HashSet<MySlimBlock>(); // Consider preallocating this * grid.GetBlocksInsideSphere(ref sphere, blocks); * * foreach (MySlimBlock block in blocks) * { * // You can query the block here: * * // Type of the block (as found in KeenSWH\Sandbox\Sources\SpaceEngineers\Content\Data\CubeBlocks.sbc) * var blockDefinitionId = block.BlockDefinition.Id; * // Position in world (probably center, but I don't remember precisely now) * Vector3D worldPosition = grid.GridIntegerToWorld(block.Position); * * // Min and max positions in world. * // This is important if the block is larger than 1x1x1 (again, probably centers of those min and max cubes) * Vector3D minWorldPosition = grid.GridIntegerToWorld(block.Min); * Vector3D maxWorldPosition = grid.GridIntegerToWorld(block.Max); * * // This will contain dimensions of the block. Beware: it does not have to be the same as block.Min - block.Max (because of rotations) * Vector3I dims = block.BlockDefinition.Size; * * // Etc... VisualStudio IntelliSense is your friend ;-) * } * } * * // How large is one cube in the grid * float blockSizeInMeters = grid.GridSize; * }*/ } } } }