public override void ReportError(PhysX.ErrorCode errorCode, string message, string file, int lineNumber) { string errorMessage = String.Format("[InWorldz.PhysxPhysics] PhysX ERROR: Code: {0} Message: {1} ({2}:{3})", new object[] { errorCode, message, file, lineNumber }); if (errorMessage == lastMessage && lastMessageRepeat < MAX_MESSAGES_BEFORE_NOTIFICATION) { lastMessageRepeat++; return; } else { if (lastMessageRepeat != 0) { m_log.ErrorFormat("[InWorldz.PhysxPhysics] PhysX ERROR: (Last physics message repeats {0} times)", lastMessageRepeat); lastMessageRepeat = 0; } lastMessage = errorMessage; } m_log.ErrorFormat(errorMessage); if (Settings.Instance.ThrowOnSdkError) { throw new PhysxSdkException(errorMessage); } }
public override void OnStateEnter() { //Adjust Cooldowns And Timers //Because you can transition from JumpState to JumpState this //is set in OnStateEnter and is slightly longer sm.SetTimer(this.GetType()); //Handler Setup eventManager.AddHandler <CollisionEvent>(OnCollision); eventManager.AddHandler <HitEvent>(OnHit); //Set Animation sm._character._xAnimator.SetAnimation(Services.AnimationLibray.GetXAnimation(sm.c, AnimationLibrary.AnimationTags.Jump) as XAnimation); //Play Audio sm._character.sfxPlayer.Play(Services.SFXLibrary.GetSFX(SFXLibrary.SFXTags.Jump)); //Pre-Calculations if (sm.jumpCount <= 1) { sm._character.gravity = PhysX.CalculateGravity(sm._character.jump_height_max, sm._character.initial_distance_to_peak, sm._character.horizontal_air_speed); sm._character._velocity.y = PhysX.CalculateJumpVelocity(sm._character.jump_height_max, sm._character.initial_distance_to_peak, sm._character.horizontal_air_speed); } else { sm._character.gravity = PhysX.CalculateGravity(sm._character.airJumpHeight, sm._character.airDistanceToPeak, sm._character.horizontal_air_speed); sm._character._velocity.y = PhysX.CalculateJumpVelocity(sm._character.airJumpHeight, sm._character.airDistanceToPeak, sm._character.horizontal_air_speed); } }
/// <summary> /// Initializes the control. /// </summary> protected override void Initialize() { physX = PhysX.Instance; // Start the animation timer. timer = Stopwatch.StartNew(); float aspectRatio = GraphicsDevice.Viewport.AspectRatio; godCamera = new GodCamera("godCamera", aspectRatio, Form.ActiveForm); fixedCamera = new DefferedCamera("fixedCamera", aspectRatio, Form.ActiveForm); orthoCamera = new OrthographicCamera("orthoCamera", 1, 1000, new Vector3(0, 50, 500), new Vector3(0, 0, 0), aspectRatio, Form.ActiveForm); CamerasManager.Instance.Activate(godCamera); physX.Initialize(GraphicsDevice); PhysicsHelper.CreateGroundPlane(); GraphicsDevice.RenderState.CullMode = CullMode.None; //PhysicsHelper.CreateBox(new Vector3(0, 50, 0), new Vector3(2), 100); // Hook the idle event to constantly redraw our animation. Application.Idle += delegate { Invalidate(); }; }
public override void OnSleep(PhysX.Actor[] actors) { if (OnSleepCallback != null) { OnSleepCallback(actors); } }
public override void OnContact(PhysX.ContactPairHeader contactPairHeader, PhysX.ContactPair[] pairs) { if (OnContactCallback != null) { OnContactCallback(contactPairHeader, pairs); } }
public override void OnWake(PhysX.Actor[] actors) { if (OnWakeCallback != null) { OnWakeCallback(actors); } }
public override void OnTrigger(PhysX.TriggerPair[] pairs) { if (OnTriggerCallback != null) { OnTriggerCallback(pairs); } }
public override void OnObstacleHit(PhysX.ControllerObstacleHit hit) { if (OnObstacleHitCallback != null) { OnObstacleHitCallback(hit); } }
public override void OnShapeHit(PhysX.ControllerShapeHit hit) { if (OnShapeHitCallback != null) { OnShapeHitCallback(hit); } }
public override void SecondaryAbility() { GameObject fball = Instantiate("DaenerysFireball"); fball.transform.SetPosition(GetSecondaryPosition(curr_position)); fball.transform.SetRotation(player.transform.GetRotation()); Fireball fballscript = fball.GetComponent <Fireball>(); fballscript.vfront = curr_forward; fballscript.fireball_particles = daenerys_fireball_particles; fballscript.fireball_particles2 = daenerys_fireball_particles2; fballscript.fireball_particles3 = daenerys_fireball_particles3; fballscript.fireball_particles4 = daenerys_fireball_particles4; fballscript.SetDamage(sec_ability_dmg); GameObject coll_object = PhysX.RayCast(curr_position, curr_forward, 254.0f); if (coll_object != null) { coll_object.GetTag(); if (coll_object.CompareTag("Enemy")) { fballscript.vfront = GetSecondaryForwardToEnemy(fball.transform.GetPosition(), coll_object.transform.GetPosition()); } } // Decrease stamina ----------- DecreaseStamina(sec_ability_cost); }
public static void SetCollisionGroup(CollisionGroupFlag group, PhysX.Shape shape) { PhysX.FilterData newFilterData = CollisionGroup.GetFilterData(shape.SimulationFilterData.Word0, shape.SimulationFilterData.Word1, group); shape.SimulationFilterData = newFilterData; shape.QueryFilterData = newFilterData; }
/// <summary> /// Remove a user avatar from the physical objects inside of the /// physics engine. /// </summary> /// <param name="actor">The user's physical object that represents the /// user's avatar inside of the physics engine that is to be removed /// from the scene</param> public override void RemoveAvatar(PhysicsActor actor) { PxPhysObject pxActor; // Make sure the scene has been initialized before removing avatar if (!m_isInitialized) { return; } // Cast the abstract class to the specific PhysX class pxActor = actor as PxPhysObject; // Check that the actor was cast succesfully if (pxActor != null) { // Tell PhysX to remove this actor from the scene PhysX.RemoveActor(pxActor.LocalID); // Prevent updates being made to the object dictionary lock (m_physObjectsDict) { // Remove object from the dictionary; if removal // was unsuccessful, say so if (m_physObjectsDict.Remove(pxActor.LocalID) == false) { m_log.WarnFormat("{0}: Attempted to remove avatar " + "that is not in the physics scene", LogHeader); } } // Prevent updates being made to the avatar set lock (m_avatarsSet) { // Remove the avatar from the dictionary if (m_avatarsSet.Remove(pxActor) == false) { // Warn the user that the avatar was unable to be // removed from the avatar list m_log.WarnFormat("{0}: Attempted to remove avatar " + "from the avatar list and it didn't exist.", LogHeader); } else { // Clean up the actor pxActor.Destroy(); } } } else { // Log that the given actor could not be removed m_log.ErrorFormat("{0}: Requested to remove avatar that is " + "not a Physics Object", LogHeader); } }
// Start is called before the first frame update void Start() { //players = new List<Player>(); physics = FindObjectOfType <PhysX>(); polarity = Polarity.Neutral; rigidBody = GetComponent <Rigidbody2D>(); spriteRenderer = GetComponent <SpriteRenderer>(); //physics.players.Add(this); //PlayerPrefs.SetInt("time", 0); }
private bool IsRideOnPrim(PhysX.Shape shape) { if (_standingOnPrim == null) { return false; } PhysxPrim shapePrim = shape.Actor.UserData as PhysxPrim; return IsRideOnPrim(shapePrim); }
public override PhysX.ControllerBehaviorFlag GetBehaviorFlags(PhysX.Shape shape) { if (IsRideOnPrim(shape)) { return PhysX.ControllerBehaviorFlag.CctCanRideOnObject; } else { return 0; } }
private PhysX.RigidDynamic CreateBox(PhysX.Scene scene, int offset) { const float HEIGHT = 20.0f; var rigid = scene.Physics.CreateRigidDynamic(); var shape = rigid.CreateShape(new PhysX.BoxGeometry(1.0f, 1.0f, 1.0f), material); rigid.GlobalPose = PhysX.Math.Matrix.Translation(130f, 130f, HEIGHT + offset); return rigid; }
public override void OnStateEnter() { //Handler Setup eventManager.AddHandler <HitEvent>(OnHit); //Set Animation sm._character._xAnimator.SetAnimation(Services.AnimationLibray.GetXAnimation(sm.c, AnimationLibrary.AnimationTags.Fall) as XAnimation); //Pre-Calculations sm._character.gravity = PhysX.CalculateGravity(sm._character.jump_height_max, sm._character.final_distance_to_peak, sm._character.horizontal_air_speed); }
/// <summary> /// Create the terrain inside of the physics engine using the height /// map provided by OpenSim. /// <summary> /// <param name="heightMap">The list of heights for the entire /// terrain</param> public override void SetTerrain(float[] heightMap) { // Fetch a new unique identifier for the height field shape m_terrainShapeID = GetNewShapeID(); // Send the height map to the PhysX wrapper, so the wrapper can // generate the terrain PhysX.SetHeightField(TERRAIN_ACTOR_ID, m_terrainShapeID, (int)m_regionExtents.X, (int)m_regionExtents.Y, 1.0f, 1.0f, heightMap, UserConfig.HeightFieldScaleFactor); }
/// <summary> /// Method to set up the initial values of necessary variables. /// <summary> /// <param name="meshmerizer">Mesher used for creating meshes from /// shape descriptions</param> /// <param name="config">Configuration file that will load the initial /// values set up inside of TBD</param> /// <param name="regionExtent">The size of the region which will either /// be the basic 256 by 256 or a value given by the scene class</param> public override void Initialise(IMesher meshmerizer, IConfigSource config, Vector3 regionExtent) { // Get the PhysX configuration section IConfig physicsConfig = config.Configs["PhysX"]; // Create the configuration using the user given values inside // of the PhysX.ini file located in the bin/config-include UserConfig.Initialize(physicsConfig); // Create the PhysX scene that will be used to represent the // region; all physics objects will be depicted in this scene; PhysX.CreateScene(UserConfig.GPUEnabled, UserConfig.CPUMaxThreads); // Create the initial ground plane for the physics engine PhysX.CreateGroundPlane(0.0f, 0.0f, -500.0f); // The scene has now been initialized m_isInitialized = true; // Initialize the mesher SceneMesher = meshmerizer; // Store the size of the region for use with height field // generation m_regionExtents = regionExtent; // New dictionary to keep track of physical objects // added to the scene m_physObjectsDict = new Dictionary <uint, PxPhysObject>(); // New dictionary to keep track of avatars that need to send a // collision update for OpenSim to update animations m_avatarsSet = new HashSet <PxPhysObject>(); // Allocate memory for returning of the updates from the // physics engine and send data to the PhysX engine m_updateArray = new EntityProperties[ UserConfig.MaxUpdatesPerFrame]; PhysX.InitEntityUpdate(ref m_updateArray, UserConfig.MaxUpdatesPerFrame); // Allocate memory for returning of the collisions // from the physics engine and send data to the PhysX engine m_collisionArray = new CollisionProperties[UserConfig.MaxCollisionsPerFrame]; PhysX.InitCollisionUpdate( ref m_collisionArray, UserConfig.MaxCollisionsPerFrame); // Create the material library that will track various material // archetypes MaterialLibrary = new PxMaterialLibrary(UserConfig); }
/// <summary> /// Clean up all objects in the scene and the scene itself. /// </summary> public override void Dispose() { // Make sure that a physics step doesn't happen during // object deletion m_isInitialized = false; // Remove all physical objects that are being tracked m_physObjectsDict.Clear(); // Delete the scene PhysX.DisposeScene(); }
private PhysX.RigidDynamic CreateSphere(PhysX.Scene scene, int offset) { const float HEIGHT = 20.0f; var rigid = scene.Physics.CreateRigidDynamic(); var shape = rigid.CreateShape(new PhysX.SphereGeometry(1.0f), material); rigid.GlobalPose = PhysX.Math.Matrix.Translation(128f, 128f, HEIGHT + offset); rigid.AngularDamping = 0.2f; rigid.LinearDamping = 0.2f; return rigid; }
public void DoRightAbility() //Might be virtual { GameObject coll_object = PhysX.RayCast(curr_position, curr_forward, 40.0f); Debug.Log("RIGHT ABILITY", Department.IA); if (coll_object != null) { PlayFx("TheonMeleHit"); if (coll_object.GetTag() == "Enemy") { // Check the specific enemy in front of you and apply dmg or call object OnContact enemy_manager.Push(coll_object, movement.GetForwardDir()); } } }
//Player[] players; // Start is called before the first frame update void Start() { //camera = GetComponent<Camera>(); //players = FindObjectsOfType<Player>(); physics = FindObjectOfType <PhysX>(); portals = FindObjectsOfType <Portal>(); arrows = new List <GameObject>(); foreach (Portal p in portals) { GameObject q = Instantiate(arrowPrefab, new Vector3(0, 0, 0), Quaternion.identity); q.GetComponent <QuestHelper>().target = p.gameObject; q.GetComponent <QuestHelper>().source = gameObject; //q.transform.parent = Camera.main.transform; arrows.Add(q); } }
protected override void LoadPhysics(PhysX.Scene scene) { var material = scene.Physics.CreateMaterial(0.7f, 0.7f, 0.1f); var sphereA = scene.Physics.CreateRigidDynamic(); sphereA.CreateShape(new SphereGeometry(1), material); sphereA.GlobalPose = Matrix4x4.CreateTranslation(0, 30, 0); scene.AddActor(sphereA); // var sphereB = scene.Physics.CreateRigidDynamic(); sphereB.CreateShape(new SphereGeometry(1), material); sphereB.GlobalPose = Matrix4x4.CreateTranslation(0, 40, 0); scene.AddActor(sphereB); // var sphereC = scene.Physics.CreateRigidDynamic(); sphereC.CreateShape(new SphereGeometry(1), material); sphereC.GlobalPose = Matrix4x4.CreateTranslation(0, 50, 0); scene.AddActor(sphereC); _sphereC = sphereC; // var revoluteABJoint = scene.CreateJoint<RevoluteJoint>(sphereA, Matrix4x4.Identity, sphereB, Matrix4x4.Identity); revoluteABJoint.SetGlobalFrame(new Vector3(0, 35, 0), new Vector3(0, 0, 1)); revoluteABJoint.ConstraintFlag = ConstraintFlag.Visualization; var revoluteBCJoint = scene.CreateJoint<RevoluteJoint>(sphereB, Matrix4x4.Identity, sphereC, Matrix4x4.Identity); revoluteBCJoint.SetGlobalFrame(new Vector3(0, 45, 0), new Vector3(0, 0, 1)); revoluteBCJoint.ConstraintFlag = ConstraintFlag.Visualization; var revoluteAJoint = scene.CreateJoint<RevoluteJoint>(sphereA, Matrix4x4.Identity, null, Matrix4x4.Identity); revoluteAJoint.SetGlobalFrame(new Vector3(0, 30, 0), new Vector3(0, 0, 1)); revoluteAJoint.ConstraintFlag = ConstraintFlag.Visualization; }
// Start is called before the first frame update void Start() { physics = FindObjectOfType <PhysX>(); polarity = (Polarity)default_polarity; }
/// <summary> /// Simulate the physics scene, and do all the related actions. /// </summary> /// <param name="timeStep">The timestep amount to be simulated</param> public override float Simulate(float timeStep) { Stopwatch physicsFrameTime; uint updatedEntityCount = 0; uint updateCollisionCount = 0; // Create a profile timer that will profile the different parts of // running PhysX #if DEBUG Stopwatch profileTimer = new Stopwatch(); #endif // Start a stopwatch to get the total time it took PhysX to // complete an update of the physics physicsFrameTime = new Stopwatch(); physicsFrameTime.Start(); // Start the profiler to acquire the time it takes to update all // the avatar velocities #if DEBUG profileTimer.Start(); #endif // Update all script movement and vehicle movement before starting // the PhysX update TriggerPreStepEvent(timeStep); // Re-build any tainted objects in a thread-safe manner lock (m_taintedObjects) { // Go through each of the tainted objects in the dictionary foreach (KeyValuePair <uint, PxPhysObject> currPair in m_taintedObjects) { // Rebuild the current object currPair.Value.BuildPhysicalShape(); } // Now that the objects have been re-built, clear the list // so that they do not get repeatedly re-built m_taintedObjects.Clear(); } // Prevent the avatar set from being manipulated lock (m_avatarsSet) { // Update all avatars in the scene, during this frame foreach (PxPhysObject pxObj in m_avatarsSet) { // Set the avatar's linear velocity, during each simulation // frame, to ensure that it has a constant velocity // while it is colliding with something (e.g. terrain) if (pxObj.IsColliding) { // Use the target velocity which should // indicate the desired velocity of the avatar PhysX.SetLinearVelocity( pxObj.LocalID, pxObj.TargetVelocity); } } } // Report how long it took for the avatar velocities to be updated // and start the timer again for the time PhysX runs the simulation // call #if DEBUG profileTimer.Stop(); m_log.DebugFormat("{0}: Time for avatar velocity to be" + " updated = {1}MS", LogHeader, profileTimer.Elapsed.TotalMilliseconds); profileTimer.Restart(); #endif // Tell PhysX to advance the simulation PhysX.RunSimulation( timeStep, out updatedEntityCount, out updateCollisionCount); // Report how long it took for the PhysX simulation call and start // the timer again for the time OpenSim took to process all the // collisions that occurred #if DEBUG profileTimer.Stop(); m_log.DebugFormat("{0}: Time for PhysX Simulation call" + " = {1}MS", LogHeader, profileTimer.Elapsed.TotalMilliseconds); profileTimer.Restart(); #endif // Update the current simulation time; this is used to synchronize // the updates between collisions and physical objects m_simulationTime = Util.EnvironmentTickCount(); // Update the physical object collisions and their physical // properties SimulateUpdatedCollisions(updateCollisionCount); // Report how long it took for OpenSim to process all the // collisions for this frame and start the timer again for the time // OpenSim took to process all the updates that occurred #if DEBUG profileTimer.Stop(); m_log.DebugFormat("{0}: Time for OpenSim to process the " + "frame collisions = {1}MS", LogHeader, profileTimer.Elapsed.TotalMilliseconds); profileTimer.Restart(); #endif SimulateUpdatedEntities(updatedEntityCount); // Report how long it took for OpenSim to process all the updates // that occurred and turn off the profiling timer since that is the // last profiling value that is needed #if DEBUG profileTimer.Stop(); m_log.DebugFormat("{0}: Time for OpenSim to update the " + "entities = {1}MS", LogHeader, profileTimer.Elapsed.TotalMilliseconds); #endif // Stop the stopwatch now that PhysX has completed the update // of the physics scene physicsFrameTime.Stop(); // Return the amount of time (in seconds) it took for the // PhysX engine to process the scene return((float)physicsFrameTime.Elapsed.TotalMilliseconds * 1000.0f); }
private bool ShapeIsVolumeDetect(PhysX.Shape shape) { return (shape.Flags & PhysX.ShapeFlag.TriggerShape) != 0; }
public override void ControlCharacter() { //Debug.Log(state, Department.PLAYER, Color.PINK); curr_hp = health.GetCurrentHealth(); // First check if you are alive if (curr_hp > 0) { //Check play breath audio base.CheckHealth(curr_hp, max_hp, "DaenerysBreathing"); // Check if player is moving to block attacks/abilities if (!movement.IsMoving()) { /* Player is alive */ switch (state) { case State.IDLE: { //Check For Input + It has to check if she's moving to block attack (¿?) CheckAttack(); break; } case State.ATTACKING: { AttackLeftTimer += Time.deltaTime; //Check for end of the Attack animation if (anim_controller.IsAnimationStopped("Idle")) { if (anim_controller.IsAnimOverXTime(0.6f) && play_audio_roar) { GameObject flamethr = Instantiate("CorrectDaenerysFireBreath"); flamethr.transform.SetPosition(GetFlameBreathPosition(curr_position)); flamethr.transform.SetRotation(flamethr.transform.GetRotation()); Fireball fballscript = flamethr.GetComponent <Fireball>(); fballscript.vfront = curr_forward; fballscript.SetDamage(left_ability_dmg); fballscript.SetDistance(left_ability_distance); GameObject coll_object = PhysX.RayCast(curr_position, curr_forward, 254.0f); if (coll_object != null) { coll_object.GetTag(); if (coll_object.CompareTag("Enemy")) { fballscript.vfront = GetSecondaryForwardToEnemy(flamethr.transform.GetPosition(), coll_object.transform.GetPosition()); } } PlayFx("DaenerysDragonRoar"); play_audio_roar = false; } if (anim_controller.IsAnimationStopped("AttackLeft")) { state = State.IDLE; } } else if (play_audio_roar == false) { state = State.IDLE; } if (AttackLeftTimer >= 1.35f) { state = State.IDLE; } break; } case State.FIRE_WALL: { //Check for end of the Attack animation if (anim_controller.IsAnimationStopped("Idle")) { if (set_fire_wall == false && anim_controller.IsAnimOverXTime(0.3f)) { int tile_x, tile_y; movement.GetPlayerPos(out tile_x, out tile_y); Vector3 player_pos = player.GetComponent <Transform>().GetPosition(); player_pos.y -= 9.1f; MovementController.Direction direction = movement.curr_dir; switch (direction) { case MovementController.Direction.NORTH: { tile_y -= 1; player_pos.z -= 25.4f; break; } case MovementController.Direction.SOUTH: { tile_y += 1; player_pos.z += 25.4f; break; } case MovementController.Direction.EAST: { tile_x += 1; player_pos.x += 25.4f; break; } case MovementController.Direction.WEST: { tile_x -= 1; player_pos.x -= 25.4f; break; } default: { break; } } //GET TILE POS! GameObject fire_wall = Instantiate("FireWall"); fire_wall.transform.SetPosition(player_pos); FireWall fire_wall_controller = fire_wall.GetComponent <FireWall>(); fire_wall_controller.SetTiles(tile_x, tile_y); fire_wall_controller.SetDamage(right_ability_dmg); set_fire_wall = true; } if (anim_controller.IsAnimOverXTime(0.8f)) { state = State.IDLE; } } else if (set_fire_wall == true && IsAnimationStopped("AttackRight")) { state = State.IDLE; } break; } case State.HIT: { //Check for end of the Attack animation if (anim_controller.IsAnimationStopped("Hit")) { state = State.IDLE; } break; } case State.DEAD: { break; } default: { break; } } } } }
public void TheonSecondaryAbility() { if (secondary_ability == true) { arrowtimers += Time.deltaTime; if (arrowtimers >= 0.5f && arrow1 == false) { arrow1 = true; PlayFx("CrossbowShot"); GameObject arrow = Instantiate("ArrowTheon"); Vector3 player_pos = curr_position; player_pos.y += 4; arrow.transform.SetPosition(GetSecondaryPosition(player_pos)); arrow.transform.SetRotation(player.transform.GetRotation()); Arrow arrow_script = arrow.GetComponent <Arrow>(); arrow_script.speed = GetSecondaryForward(curr_forward); arrow_script.SetDamage(sec_ability_dmg); GameObject coll_object = PhysX.RayCast(curr_position, curr_forward, 254.0f); if (coll_object != null) { coll_object.GetTag(); if (coll_object.CompareTag("Enemy")) { Vector3 enemypos = coll_object.transform.GetPosition(); enemypos.y += 7; arrow_script.speed = GetSecondaryForwardToEnemy(arrow.transform.GetPosition(), enemypos); arrow_script.speed *= 2; } } arrow_script.arrow_blood_particles = theon_blood_particles; arrow_script.arrow_sparks_particles = theon_sparks_particles; } if (arrowtimers >= 1.0f && arrow2 == false) { arrow2 = true; PlayFx("CrossbowShot"); GameObject arrow = Instantiate("ArrowTheon"); Vector3 player_pos = curr_position; player_pos.y += 4; arrow.transform.SetPosition(GetSecondaryPosition(player_pos)); arrow.transform.SetRotation(player.transform.GetRotation()); Arrow arrow_script = arrow.GetComponent <Arrow>(); arrow_script.speed = GetSecondaryForward(curr_forward); arrow_script.SetDamage(sec_ability_dmg); GameObject coll_object = PhysX.RayCast(curr_position, curr_forward, 254.0f); if (coll_object != null) { coll_object.GetTag(); if (coll_object.CompareTag("Enemy")) { Vector3 enemypos = coll_object.transform.GetPosition(); enemypos.y += 7; arrow_script.speed = GetSecondaryForwardToEnemy(arrow.transform.GetPosition(), enemypos); arrow_script.speed *= 2.5f; } } arrow_script.arrow_blood_particles = theon_blood_particles; arrow_script.arrow_sparks_particles = theon_sparks_particles; } if (arrowtimers >= 1.5f && arrow3 == false) { arrowtimers = 0.0f; arrow1 = false; arrow2 = false; secondary_ability = false; PlayFx("CrossbowShot"); GameObject arrow = Instantiate("ArrowTheon"); Vector3 player_pos = curr_position; player_pos.y += 4; arrow.transform.SetPosition(GetSecondaryPosition(player_pos)); arrow.transform.SetRotation(player.transform.GetRotation()); Arrow arrow_script = arrow.GetComponent <Arrow>(); arrow_script.speed = GetSecondaryForward(curr_forward); arrow_script.SetDamage(sec_ability_dmg); GameObject coll_object = PhysX.RayCast(curr_position, curr_forward, 254.0f); if (coll_object != null) { coll_object.GetTag(); if (coll_object.CompareTag("Enemy")) { Vector3 enemypos = coll_object.transform.GetPosition(); enemypos.y += 7; arrow_script.speed = GetSecondaryForwardToEnemy(arrow.transform.GetPosition(), enemypos); arrow_script.speed *= 1.5f; } } arrow_script.arrow_blood_particles = theon_blood_particles; arrow_script.arrow_sparks_particles = theon_sparks_particles; } } }
private float CalculateDepenetrationZOffset(OpenMetaverse.Vector3 pos, PhysX.Geometry avaGeom, PhysX.Shape avaShape) { const int MAX_ITERATIONS = 8; const float PUSH_MULTIPLIER = 1.5F; float pushFactor = 0.1f; OpenMetaverse.Vector3 offset = OpenMetaverse.Vector3.Zero; bool foundOverlap = false; //constant from looking at the rot returned from the live avatar, //remember that capsules are always upright, and z rotations don't have an effect //on their geometry OpenMetaverse.Quaternion capsuleRot = new OpenMetaverse.Quaternion(0f, -0.7071069f, 0f, 0.7071067f); for (int i = 0; i < MAX_ITERATIONS; i++) { foundOverlap = false; OpenMetaverse.Vector3 translatedPose = pos + offset; PhysX.Shape[] overlap = _scene.SceneImpl.OverlapMultiple(avaGeom, PhysUtil.PositionToMatrix(translatedPose, capsuleRot)); if (overlap == null) { foundOverlap = true; } else { foreach (var shape in overlap) { if (shape != avaShape && !ShapeIsVolumeDetect(shape)) { foundOverlap = true; break; } } } if (foundOverlap && i + 1 < MAX_ITERATIONS) { offset += new OpenMetaverse.Vector3(0f, 0f, pushFactor); pushFactor *= PUSH_MULTIPLIER; } else { break; } } if (foundOverlap == false && offset != OpenMetaverse.Vector3.Zero) { return offset.Z; } return 0.0f; }
private void OnContact(PhysX.ContactPairHeader contactPairHeader, PhysX.ContactPair[] pairs) { if ((contactPairHeader.Flags & PhysX.ContactPairHeaderFlag.DeletedActor0) == 0) { bool wasPrim = TryInformPrimOfContactChange(contactPairHeader, pairs, 0); if (! wasPrim) { TryInformCharacterOfContactChange(contactPairHeader, pairs, 0); } } if ((contactPairHeader.Flags & PhysX.ContactPairHeaderFlag.DeletedActor1) == 0) { bool wasPrim = TryInformPrimOfContactChange(contactPairHeader, pairs, 1); if (!wasPrim) { TryInformCharacterOfContactChange(contactPairHeader, pairs, 1); } } }
public VehicleMotor(ref PhysxPrim _actor, ref VehicleProperties _props, ref PhysX.Physics _physics, ref PhysxScene _scene) { this._actor = _actor; this._props = _props; this._physics = _physics; this._scene = _scene; }
public VehicleDynamics(PhysxPrim physxPrim, VehicleProperties shadowProps, PhysX.Physics physics, PhysxScene scene) { _angularstatsX = new RunningStat(); _angularstatsY = new RunningStat(); _angularstatsZ = new RunningStat(); _linearstatsX = new RunningStat(); _linearstatsY = new RunningStat(); _linearstatsZ = new RunningStat(); _actor = physxPrim; _props = new VehicleProperties(); _physics = physics; _scene = scene; _motor = new VehicleMotor(ref _actor, ref _props, ref _physics, ref _scene); // Preset the defaults and new common keys. This ensures scripts with older versions of saved state // do not crash the simulator since the new keys do not exist in the old state. _props.Type = VehicleType.None; SetVehicleDefaults(_props); // Merge the new properties. _props.Merge(shadowProps); SetVehicleDefaultActions(); if (VehicleLimits.DebugVehicleChange) m_log.InfoFormat("[VehicleDynamics] constructed type={0} name={1} at {2}", _props.Type, _actor.SOPName, _actor.Position); //DisplayParameters(); }
public TerrainMesher(PhysX.Scene parentScene) { _scene = parentScene; _cooking = _scene.Physics.CreateCooking(); }
public Tuple<PhysX.TriangleMesh, MemoryStream> GenerateTrimeshFromIndexedTriangles(PhysX.Math.Vector3[] points, int[] triangles) { PhysX.TriangleMeshDesc triangleMeshDesc = new PhysX.TriangleMeshDesc() { Triangles = triangles, Points = points, }; MemoryStream ms = new MemoryStream(); if (!_cooking.CookTriangleMesh(triangleMeshDesc, ms)) { throw new PhysxSdkException("TerrainMesher: GenerateTrimeshFromIndexedTriangles(): CookTriangleMesh() failed"); } ms.Position = 0; PhysX.TriangleMesh triangleMesh = _scene.Physics.CreateTriangleMesh(ms); return new Tuple<PhysX.TriangleMesh, MemoryStream>(triangleMesh, ms); }
private void SetToRemoveAfterReport(PhysX.Shape otherShape, PhysxPrim colPrim) { ExternalReport report; if (_externalCollisionReports.TryGetValue(otherShape, out report)) { if (report.Reported) { //this collision was reported already. remove it RemoveExternalCollidingPrimShape(otherShape, colPrim); } else { //this collision hasn't been reported yet. make sure the //collision processor knows to remove it after it is reported report.RemoveAfterReport = true; } } }
// Use this for initialization void Start() { _sm = new FSM(this); _sm.TransitionTo(new IdleState(_sm), true); gravity = PhysX.CalculateGravity(jump_height_max, initial_distance_to_peak, horizontal_speed_max); }
private bool TryInformPrimOfContactChange(PhysX.ContactPairHeader contactPairHeader, PhysX.ContactPair[] pairs, int actorIndex) { PhysxPrim prim = contactPairHeader.Actors[actorIndex].UserData as PhysxPrim; if (prim != null) { prim.OnContactChangeSync(contactPairHeader, pairs, actorIndex); return true; } else { return false; } }
public void DoLeftAbility() { // Attack the enemy in front of you GameObject coll_object = PhysX.RayCast(curr_position, curr_forward, 30.0f); if (coll_object != null) { coll_object.GetTag(); if (coll_object.CompareTag("Enemy")) { //Get current hit streak int hit_streak = combo_controller.GetHitStreak(); //Enable particles emission of enemy blood sword_particles.EnableEnemyCollision(true); // Check the specific enemy in front of you and apply dmg or call object OnContact float damage = 1.0f; if (hit_streak == 0) { damage = left_ability_dmg; } else if (hit_streak == 1) { damage = left_ability_dmg2; } else if (hit_streak == 2) { damage = left_ability_dmg3; } /* ---------- IN CASE THAT THE ENEMY BLOCKS THE ATTACK, UNCOMMENT AND COMPLETE THIS CODE ---------- */ if (enemy_manager.ApplyDamage(coll_object, damage, Enemy_BT.ENEMY_GET_DAMAGE_TYPE.DEFAULT)) { //Increase the blood of the sword sword_particles.SetBlood(blood_amount); PlayFx("Enemy_Flesh_Hit"); if (hit_streak == 0) { //Start combo time controller to manage hit streaks combo_controller.StartComboTime(); } // If damage done effectively, increase Hit Streak combo_controller.IncreaseHitStreak(); } else { //Decrease the blood of the sword sword_particles.SetBlood(-blood_amount); // Reset Hit Count combo_controller.ResetHitStreak(); //Enable particles emission of enemy blood sword_particles.EnableWallCollision(true); //Set FailAttack Transition & Audio anim_controller.PlayAnimationNode("FailAttack"); SpawnPrefabFromPos("Particle_MetalCollision", transform.GetGlobalPosition(), player.transform.GetRotation(), new Vector3(0, 7, 5)); SetState(State.FAIL_ATTACK); } /* ----------------------------------------------------------------------------------- */ } else if (coll_object.CompareTag("obstacle") || coll_object.CompareTag("trap_floor")) { //Decrease the blood of the sword sword_particles.SetBlood(-blood_amount); //Reset Hit Count combo_controller.ResetHitStreak(); //Enable particles emission of sparks sword_particles.EnableWallCollision(true); //Set FailAttack Transition & Audio anim_controller.PlayAnimationNode("FailAttack"); Debug.Log(transform.GetGlobalPosition(), Department.PLAYER); SpawnPrefabFromPos("Particle_RockCollision", transform.GetGlobalPosition(), player.transform.GetRotation(), new Vector3(0, 7, 5)); PlayFx("JaimeImpact"); SetState(State.FAIL_ATTACK); } } else { //Decrease the blood of the sword sword_particles.SetBlood(-blood_amount); //Reset Hit Count combo_controller.ResetHitStreak(); } }
private void AddExternalCollidingPrimShape(PhysX.Shape otherShape, PhysxPrim colPrim) { _externalCollisionReports[otherShape] = new ExternalReport { RemoveAfterReport = false, Reported = false }; HashSet<PhysX.Shape> primShapes; if (!_externalCollisionPrims.TryGetValue(colPrim, out primShapes)) { primShapes = new HashSet<PhysX.Shape>(); _externalCollisionPrims.Add(colPrim, primShapes); colPrim.OnDeleted += colPrim_OnDeleted; } primShapes.Add(otherShape); }
// Start is called before the first frame update void Start() { victory_achieved = false; physics = FindObjectOfType <PhysX>(); }
private static PhysicsShape CreatePhysicsShapeFromSingleConvexAndCache(MeshingStage meshingStage, ulong meshHash, PhysX.ConvexMeshGeometry convex) { PhysicsShape phyShape; phyShape = new PhysicsShape(new List<PhysX.ConvexMeshGeometry> { convex }, meshHash, true); phyShape.AddRef(); //complex shapes are cached meshingStage.CacheShape(meshHash, phyShape, ShapeType.SingleConvex); return phyShape; }
// // Motor add force that applies the vehicle linear offset. // internal void AddForce(OpenMetaverse.Vector3 force, PhysX.ForceMode mode, bool wakeup) { OpenMetaverse.Vector3 loffset = _props.ParamsVec[VectorParams.VehicleLinearMotorOffset]; // Only wake up the object if the forces are above the threshold. Smaller forces, though // affecting the object sould permit it to sleep. This stops perpetual drifting issues. wakeup = (Vector3.Mag(force) > VehicleLimits.ThresholdLinearMotorDeltaV) ? true : false; if (loffset == OpenMetaverse.Vector3.Zero) _actor.DynActorImpl.AddForce(PhysUtil.OmvVectorToPhysx(force), mode, wakeup); else { // Velocity change is not supported for this PhysX function, so simulate it. if (mode == PhysX.ForceMode.VelocityChange) { force *= _actor.Mass; } _actor.DynActorImpl.AddForceAtLocalPosition(PhysUtil.OmvVectorToPhysx(force), PhysUtil.OmvVectorToPhysx(loffset), PhysX.ForceMode.Impulse, wakeup); } //m_log.DebugFormat("[VehicleMotor AddForce] force {0}", force); }
private static PhysicsShape CreatePhysicsShapeFromTrimeshAndCache(MeshingStage meshingStage, ulong meshHash, PhysX.TriangleMeshGeometry triMesh) { PhysicsShape phyShape; phyShape = new PhysicsShape(triMesh, ShapeType.TriMesh, meshHash); phyShape.AddRef(); //complex shapes are cached meshingStage.CacheShape(meshHash, phyShape, ShapeType.TriMesh); return phyShape; }
private bool TryInformCharacterOfContactChange(PhysX.ContactPairHeader contactPairHeader, PhysX.ContactPair[] pairs, int actorIndex) { PhysxCharacter character = contactPairHeader.Actors[actorIndex].UserData as PhysxCharacter; if (character != null) { character.OnContactChangeSync(contactPairHeader, pairs, actorIndex); return true; } else { return false; } }
// // Motor add torque. It acumulates velocity and impulse // torques separately so that they can be applied finally at the end of the physics frame. // internal void AddTorque(OpenMetaverse.Vector3 force, PhysX.ForceMode mode, string code) { OpenMetaverse.Vector3 torque = force; if (mode == PhysX.ForceMode.VelocityChange) AccumTorqueVel += torque; if (mode == PhysX.ForceMode.Impulse) AccumTorqueImpulse += torque; if (VehicleLimits.DebugAngular) { if (AccumTorqueFirst) { m_log.DebugFormat("[----------------------]"); m_log.DebugFormat("[VehicleMotor BgnTorque] InitialVelocity {0}", worldAngularVel * Quaternion.Inverse(rotation)); } m_log.DebugFormat("[VehicleMotor AddTorque] {2} {1} {0}", torque * Quaternion.Inverse(rotation), code, mode); } AccumTorqueFirst = false; }
void OnTrigger(PhysX.TriggerPair[] pairs) { foreach (var pair in pairs) { if (pair.TriggerShape != null) { PhysxPrim triggerPrim = pair.TriggerShape.Actor.UserData as PhysxPrim; if (triggerPrim != null) { triggerPrim.OnTrigger(pair); } } } }
private void RemoveExternalCollidingPrimShape(PhysX.Shape otherShape, PhysxPrim colPrim) { _externalCollisionReports.Remove(otherShape); HashSet<PhysX.Shape> primShapes; if (_externalCollisionPrims.TryGetValue(colPrim, out primShapes)) { primShapes.Remove(otherShape); if (primShapes.Count == 0) { _externalCollisionPrims.Remove(colPrim); colPrim.OnDeleted -= colPrim_OnDeleted; } } }