public EggData(SaveMaster mast) { int num = mast.capsules.Length; vels = new float[num][]; transes = new float[num][]; allItems = new string[num][]; for (int i = 0; i < mast.capsules.Length; i++) { CapsuleController egg = mast.capsules[i]; Rigidbody2D rb = egg.GetComponent <Rigidbody2D>(); float[] v = new float[2]; v[0] = rb.velocity.x; v[1] = rb.velocity.y; //Debug.Log(v[0] + ' ' + v[1]); vels[i] = v; float[] t = new float[3]; t[0] = egg.transform.position.x; t[1] = egg.transform.position.y; t[2] = egg.transform.rotation.eulerAngles.z; transes[i] = t; allItems[i] = new ItemListSave(egg.stringIts).items.ToArray(); } }
public void Initialize(StillDesign.PhysX.Scene _scene) { scene = _scene; manager = scene.CreateControllerManager(); CapsuleControllerDescription capsuleControllerDesc = new CapsuleControllerDescription(0.5f, 1); controllerHitReport = new PlayerControllerHitReport(); capsuleControllerDesc.Callback = controllerHitReport; /*{ * Callback = new ControllerHitReport() * };*/ CapsuleController capsuleController = manager.CreateController <CapsuleController>(capsuleControllerDesc); capsuleController.Position = player.Position.xna(); capsuleController.Actor.Name = "PlayerController"; capsuleController.SetCollisionEnabled(true); controller = capsuleController; }
public async void RemoveMessageFromCapsule(Models.Capsule[] capsules) { // Arrange var capsule = capsules[0]; var messageToRemove = capsule[0]; var messageSrvMock = new Mock <IMessageService>(); messageSrvMock.Setup(srv => srv.GetMessageByIdAsync(It.IsAny <int>())).Returns(() => Task <Message> .Run(() => messageToRemove)); var capsuleSrvMock = new Mock <ICapsuleService>(); capsuleSrvMock.Setup(srv => srv.GetCapsuleByUserAsync()).Returns(Task <Capsule> .Run(() => capsule)); capsuleSrvMock.Setup(srv => srv.SaveCapsuleAsync(It.IsAny <Capsule>())).Verifiable(); var controller = new CapsuleController(messageService: messageSrvMock.Object, capsuleService: capsuleSrvMock.Object); // Act var result = await controller.RemoveFromCapsule(messageId : messageToRemove.Id, returnUrl : string.Empty) as RedirectToActionResult; // Assert Assert.IsType <RedirectToActionResult>(result); Assert.Equal("Capsule", result.ControllerName); Assert.Equal("Index", result.ActionName); capsuleSrvMock.Verify(srv => srv.GetCapsuleByUserAsync(), Times.Once); capsuleSrvMock.Verify(srv => srv.SaveCapsuleAsync(It.IsAny <Capsule>()), Times.Once); }
public static void RunCharacterTest() { Core core = new Core(); StillDesign.PhysX.Scene scene = core.CreateScene(); ControllerManager manager = scene.CreateControllerManager(); CapsuleControllerDescription desc = new CapsuleControllerDescription(2, 10); CapsuleController capsuleController = manager.CreateController <CapsuleController>(desc); BoxShapeDescription boxShapeDesc = new BoxShapeDescription(1, 1, 1); ActorDescription actorDesc = new ActorDescription(boxShapeDesc); actorDesc.BodyDescription = new BodyDescription(1f); Actor actor = scene.CreateActor(actorDesc); //capsuleController.Move( Vector3.Up ); // Update Physics scene.Simulate(1.0f / 60.0f); scene.FlushStream(); scene.FetchResults(SimulationStatus.RigidBodyFinished, true); capsuleController.Move(Vector3.Up); core.Dispose(); }
public async void AddMessageToCapsuleMessageDoesNotExist() { // Arrange var messageSrvMock = new Mock <IMessageService>(); messageSrvMock.Setup(srv => srv.GetMessageByIdAsync(It.IsAny <int>())).Returns(() => Task <Message> .Run(() => default(Message))); var capsuleSrvMock = new Mock <ICapsuleService>(); capsuleSrvMock.Setup(srv => srv.GetCapsuleByUserAsync()).Verifiable(); capsuleSrvMock.Setup(srv => srv.SaveCapsuleAsync(It.IsAny <Capsule>())).Verifiable(); var controller = new CapsuleController(messageService: messageSrvMock.Object, capsuleService: capsuleSrvMock.Object); // Act var result = await controller.AddMessageToCapsule(messageId : int.MaxValue, returnUrl : null) as RedirectToActionResult; // Assert Assert.IsType <RedirectToActionResult>(result); Assert.Equal("Capsule", result.ControllerName); Assert.Equal("Index", result.ActionName); messageSrvMock.Verify(srv => srv.GetMessageByIdAsync(It.IsAny <int>()), Times.Once); capsuleSrvMock.Verify(srv => srv.GetCapsuleByUserAsync(), Times.Never); capsuleSrvMock.Verify(srv => srv.SaveCapsuleAsync(It.IsAny <Capsule>()), Times.Never); }
protected override void LoadPhysics(Scene scene) { var material = scene.Physics.CreateMaterial(0.1f, 0.1f, 0.1f); var controllerManager = scene.CreateControllerManager(); // User controllable character { var desc = new CapsuleControllerDesc() { Height = 4, Radius = 1, Material = material, UpDirection = new Vector3(0, 1, 0), Position = new Vector3(0, 3, 0), ReportCallback = new ControllerHitReport() }; _controller = controllerManager.CreateController <CapsuleController>(desc); } // Another controller to walk into { var desc = new CapsuleControllerDesc() { Height = 4, Radius = 1, Material = material, UpDirection = new Vector3(0, 1, 0), Position = new Vector3(15, 3, 15) }; controllerManager.CreateController <CapsuleController>(desc); } }
// Use this for initialization void Start() { if (followTarget != null) { player = followTarget.GetComponent <CapsuleController>(); } zOffset = transform.position.z; }
private void OnTriggerEnter(Collider other) { if (other.CompareTag("Player")) { Transform player = other.gameObject.transform; CapsuleController controller = player.GetComponent <CapsuleController>(); controller.SetDestination(_destination.position); } }
void OnTriggerEnter2D(Collider2D collision) { CapsuleController player = collision.GetComponent <CapsuleController>(); if (player != null) { player.IncreaseHealth(healsPercent); Instantiate(particleEffect, transform.position, Quaternion.identity); SoundManager.Instance.PlayFX(SoundManager.SoundFX.HealthPickUp); Destroy(gameObject); } }
public GameObject SpawnEnemy(EnemySpawnPoint point, EnemyType type, EnemyObserver enemyObserver) { GameObject go = SpawnEnemy(point, type); CapsuleController capsuleController = go.GetComponent <CapsuleController>(); if (capsuleController != null && enemyObserver != null) { capsuleController.Observer = enemyObserver; } return(go); }
public async void GetCapsuleByUserBadRequest() { // Arrange var mock = new Mock <ICapsuleRepository>(); CapsuleController controller = new CapsuleController(mock.Object); // Act BadRequestObjectResult result = await controller.GetCapsuleByUser(null) as BadRequestObjectResult; // Assert Assert.Equal(400, result.StatusCode); mock.Verify(rep => rep.GetCapsuleByUserAsync(It.IsAny <string>()), Times.Never); }
IEnumerator ReturnEgg() { yield return(new WaitForSeconds(1)); if (!egg) { yield break; } if (egg.items.Count > 0) { StartCoroutine(ReturnEgg()); } else { egg.GetComponent <Animator>().SetTrigger("Close"); anim.SetTrigger("Throw"); yield return(new WaitForSeconds(0.5f)); //wait a sec, throw, then close egg //unfreeze egg Rigidbody2D e = egg.GetComponent <Rigidbody2D>(); e.constraints = RigidbodyConstraints2D.None; e.AddForce(holdingPoint.right * -fireForce * 2); yield return(new WaitForSeconds(0.05f)); for (int i = 0; i < 100; i++) { yield return(new WaitForEndOfFrame()); if (egg) { egg.transform.localScale *= 0.9f; if (egg.transform.localScale.x < 0.1f) { break; } } } if (egg) { Transform part = Instantiate(eggParticle, egg.transform.position, Quaternion.identity).transform; Destroy(egg.gameObject); } //times 5 becuz of hge mass of egg egg = null; } }
public async void SaveCapsuleIsNullBadRequest() { // Arrange var mock = new Mock <ICapsuleRepository>(); CapsuleController controller = new CapsuleController(mock.Object); // Act BadRequestObjectResult result = await controller.SaveCapsule(null) as BadRequestObjectResult; // Assert Assert.Equal((int?)HttpStatusCode.BadRequest, result?.StatusCode); mock.Verify(rep => rep.GetCapsuleByUserAsync(It.IsAny <string>()), Times.Never); mock.Verify(rep => rep.SaveCapsuleAsync(It.IsAny <Models.Capsule>()), Times.Never); mock.Verify(rep => rep.CreateNewCapsuleAsync(It.IsAny <Models.Capsule>()), Times.Never); }
public async void GetMessageByIdThrowsException() { // Arrange var mock = new Mock <ICapsuleRepository>(); mock.Setup(rep => rep.GetCapsuleByUserAsync(It.IsAny <string>())).Throws <CapsuleDomainException>(); CapsuleController controller = new CapsuleController(mock.Object); // Act & Assert Exception ex = await Assert.ThrowsAsync <CapsuleDomainException>( async() => await controller.GetCapsuleByUser("User1") ); Assert.Equal(expected: typeof(CapsuleDomainException), actual: ex.GetType()); }
private void setupPhysics() { CapsuleControllerDesc desc = new CapsuleControllerDesc(); desc.Position = entityNode.Position; desc.StepOffset = 0.01f; desc.SlopeLimit = 0.5f; // max slope the character can walk desc.Radius = 2.5f; //radius of the capsule desc.Height = CHAR_HEIGHT; //height of the controller desc.ClimbingMode = CapsuleClimbingModes.Easy; desc.UpDirection = HeightFieldAxes.Y; // Specifies the 'up' direction desc.Position = entityNode.Position; physicsController = cotrollerManager.CreateController(physicsScene, desc); physicsController.Actor.Group = 3; }
public async void SaveCapsuleOk(Models.Capsule[] capsules) { // Arrange var mock = new Mock <ICapsuleRepository>(); Models.Capsule capsuleToSave = capsules[0]; mock.Setup(rep => rep.GetCapsuleByUserAsync(It.IsAny <string>())).Returns(Task <Models.Capsule> .Run(() => capsuleToSave)); CapsuleController controller = new CapsuleController(mock.Object); // Act OkObjectResult result = await controller.SaveCapsule(capsuleToSave) as OkObjectResult; // Assert Assert.Equal((int?)HttpStatusCode.OK, result?.StatusCode); mock.Verify(rep => rep.SaveCapsuleAsync(It.IsAny <Models.Capsule>()), Times.Once); }
protected override void LoadPhysics(Scene scene) { var material = scene.Physics.CreateMaterial(0.1f, 0.1f, 0.1f); var controllerManager = scene.CreateControllerManager(); var desc = new CapsuleControllerDesc() { Height = 4, Radius = 1, Material = material, UpDirection = new Math.Vector3(0, 1, 0), Position = new Math.Vector3(0, 2, 0) }; _controller = controllerManager.CreateController<CapsuleController>(desc); }
public async void GetCapsuleByUserOk(Models.Capsule[] capsules) { // Arrange var user = "******"; var capsuleToFind = capsules[0]; var mock = new Mock <ICapsuleRepository>(); mock.SetupSequence(rep => rep.GetCapsuleByUserAsync(It.IsAny <string>())).Returns(Task <Models.Capsule> .Run(() => capsuleToFind)); CapsuleController controller = new CapsuleController(mock.Object); // Act OkObjectResult result = await controller.GetCapsuleByUser(user) as OkObjectResult; // Assert Assert.Equal((int?)HttpStatusCode.OK, result.StatusCode); Assert.Equal(capsuleToFind, (Models.Capsule)result.Value, Comparer.Get <Models.Capsule>((m1, m2) => m1.Id == m2.Id)); }
protected override void LoadPhysics(Scene scene) { var material = scene.Physics.CreateMaterial(0.1f, 0.1f, 0.1f); var controllerManager = scene.CreateControllerManager(); var desc = new CapsuleControllerDesc() { Height = 4, Radius = 1, Material = material, UpDirection = new Math.Vector3(0, 1, 0), Position = new Math.Vector3(0, 2, 0) }; _controller = controllerManager.CreateController <CapsuleController>(desc); }
public async void GetCapsuleByUserCreated() { // Arrange string userId = "Unexisting user"; var mock = new Mock <ICapsuleRepository>(); mock.Setup(rep => rep.GetCapsuleByUserAsync(It.IsAny <string>())).Returns(Task <Models.Capsule> .Run(() => { return(default(Models.Capsule)); })); mock.Setup(rep => rep.CreateNewCapsuleAsync(It.IsAny <string>())).Returns(Task <Models.Capsule> .Run(() => { return(new Models.Capsule(userId: userId)); })); CapsuleController controller = new CapsuleController(mock.Object); // Act CreatedAtRouteResult result = await controller.GetCapsuleByUser(userId) as CreatedAtRouteResult; // Assert Assert.Equal((int?)HttpStatusCode.Created, result.StatusCode); Assert.Equal(userId, ((Models.Capsule)result.Value).Id); Assert.Empty(((Models.Capsule)result.Value).Messages); }
void Eggs(AllData allData) { float[][] vels = allData.egg.vels; float[][] transes = allData.egg.transes; string[][] allItems = allData.egg.allItems; for (int i = 0; i < allData.egg.vels.Length; i++) { CapsuleController e = Instantiate(eggPrefab, Vector3.zero, Quaternion.identity); e.transform.position = new Vector3(transes[i][0], transes[i][1], 0); e.transform.rotation = Quaternion.Euler(0, 0, transes[i][2]); Rigidbody2D rb = e.GetComponent <Rigidbody2D>(); rb.velocity = new Vector2(vels[i][0], vels[i][1]); for (int j = 0; j < allItems[i].Length; j++) { Item it = Instantiate(StaticFunctions.GetItemFromString(allItems[i][j]), transform.position, Quaternion.identity); e.AddItem(it); } } }
IEnumerator LaunchEgg() { launching = true; egg.transform.parent = null; Rigidbody2D r = egg.GetComponent <Rigidbody2D>(); r.constraints = RigidbodyConstraints2D.None; egg = null; yield return(new WaitForSeconds(0.25f)); r.AddForce(firePoint.up * launchForce); //r.AddTorque(250); //now make an egg yield return(new WaitForSeconds(0.5f)); egg = Instantiate(eggPrefab, firePoint.position, firePoint.rotation); egg.transform.parent = transform; egg.GetComponent <Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeAll; launching = false; capacityDisplay.color = Color.red; }
void OnTriggerEnter2D(Collider2D collision) { /* Player hits Enemy */ Enemy enemy = collision.gameObject.GetComponent <Enemy>(); // Dirty hack to prevent sword colliding with other colliders in the same game object if (m_isAttacking && enemy != null && collision.gameObject.tag.Equals("Enemy") && (collision as CapsuleCollider2D) != null) { enemy.TakeDamage(damage); float knockbackDir = this.transform.parent.transform.localScale.x; enemy.GetComponent <Rigidbody2D>().AddForce(new Vector2(knockbackDir * knockbackForce, 400)); } /* Player hits a Button */ Button button = collision.gameObject.GetComponent <Button>(); if (m_isAttacking && button != null) { button.Press(); } /* Enemy hits player */ CapsuleController player = collision.gameObject.GetComponent <CapsuleController>(); if (m_isAttacking && player != null && collision.gameObject.tag.Equals("Player") && (collision as CapsuleCollider2D) != null) { player.TakeDamage(damage); float knockbackDir = this.transform.parent.transform.localScale.x; player.GetComponent <Rigidbody2D>().AddForce(new Vector2(knockbackDir * knockbackForce, 400)); } }
public override bool UpdateEvent() { Debug.Log("update spawnEvent"); for (int i = 0; i < spawnPoints.Count; ++i) { if (spawnPoints[i].delay <= 0 && !spawnPoints[i].done) { CapsuleController aux = manager.SpawnEnemy(spawnPoints[i]).GetComponent <CapsuleController>(); turrets.capsules.Add(aux); spawnPoints[i].done = true; spawnPoints[i].delay = spawnPoints[i].initialDelay; //Destroy(spawnPoints[i]); //spawnPoints.RemoveAt(i); } else { spawnPoints[i].delay -= Time.deltaTime; } } return(base.UpdateEvent()); }
private void OnTriggerEnter2D(Collider2D other) { //when hit by a capsule, say this if (other.GetComponent <CapsuleController>()) { egg = other.GetComponent <CapsuleController>(); //THIS IS WHERE THE ITEMS ARE DISSAPEARING WHYYYYYYYYYY //FUTURE SELF FIGURE IT OUT NERDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD //activaate anims anim.SetTrigger("Grab"); //snap egg egg.transform.position = holdingPoint.transform.position; egg.transform.rotation = holdingPoint.transform.rotation; //freeze egg egg.GetComponent <Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeAll; egg.Unload(gameObject.GetComponent <UnPackager>()); StartCoroutine(ReturnEgg()); } }
void OnTriggerEnter2D(Collider2D collision) { CapsuleController player = collision.gameObject.GetComponent <CapsuleController>(); if (player != null) { player.TakeDamage(damage); Destroy(gameObject); float knockbackDir = this.transform.localScale.normalized.x * -1; if (force > 0) { player.GetComponent <Rigidbody2D>().AddForce(new Vector2(knockbackDir * force, 400)); } print(force); } else if (collision.gameObject.tag == "Wall") { Destroy(gameObject); } }
private void OnTriggerEnter2D(Collider2D other) { if (other.GetComponent <Item>()) { //so its an item... //okay now load egg with item if (egg) { //now update the sprite display float color = (egg.items.Count * 1f / maxItems * 1f); capacityDisplay.color = new Color((1 - color), color, 0, 1); if (egg.items.Count < maxItems) { //print(other.name); egg.AddItem(other.GetComponent <Item>()); } else { StartCoroutine(LaunchEgg()); } } else { //if no egg, reject other.GetComponent <Rigidbody2D>().AddForce(firePoint.up * -200); //if not launching, that means no egg is being created to replace. So, another must be made if (!launching) { egg = Instantiate(eggPrefab, firePoint.position, firePoint.rotation); egg.transform.parent = transform; egg.GetComponent <Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeAll; egg.AddItem(other.GetComponent <Item>()); } } } }
//private void DrawCapsuleLayer(Device device, ShapeLayer layer) //{ // effect.Apply(() => // device.DrawIndexedUserPrimitives(IAPrimitive.TriangleList, layer.StartIndex, layer.StartVertex, // layer.VertexCount, layer.PrimitiveCount, capsuleBuilder.Indices, Format.Index16, capsuleBuilder.Vertices, vd.Size)); //} //public void DrawPlane(Matrix pose) //{ // var camera = Engine.Scene.ActiveCamera; // DrawBox(pose, new Vector3(camera.ZFar, 0, camera.ZFar)); //} //public void DrawBox(Matrix pose, Vector3 dimensions) //{ // var scale = Matrix.Scaling(dimensions); // effect.SetWorldMatrix(scale * pose); // effect.Apply(() => // GraphicDeviceFactory.Device.DrawIndexedUserPrimitives(IAPrimitive.TriangleList, 0, boxBuilder.Vertices.Length, // boxBuilder.Indices.Length / 3, boxBuilder.Indices, true, boxBuilder.Vertices)); //} //public override void Draw(object component) //{ // Draw((Actor)component); //} public void DrawController(CharacterController characterController) { var device = GraphicDeviceFactory.Device; device.RasterizerStack.Push(_rasterizer); device.PrimitiveTopology = IAPrimitive.TriangleList; var effect = Effect; if (characterController is BoxController) { BoxController boxController = (BoxController)characterController; effect.Input.World = Matrix.Scale(boxController.Extents) * characterController.GlobalPose; DrawMesh(_box, GraphicDeviceFactory.Device); } else { CapsuleController capsuleController = (CapsuleController)characterController; float radius = capsuleController.Radius; float height = capsuleController.Height; effect.Input.World = Matrix.Translate(0, -0.5f, 0) * Matrix.Scale(radius, radius, radius) * Matrix.Translate(0, height * 0.5f, 0) * capsuleController.GlobalPose; DrawMeshPart(_capsule, _capsule.Layers[0], GraphicDeviceFactory.Device); effect.Input.World = Matrix.Translate(0, 0.5f, 0) * Matrix.Scale(radius, radius, radius) * Matrix.Translate(0, -(height * 0.5f), 0) * capsuleController.GlobalPose; DrawMeshPart(_capsule, _capsule.Layers[2], GraphicDeviceFactory.Device); effect.Input.World = Matrix.Scale(radius, height, radius) * capsuleController.GlobalPose; DrawMeshPart(_capsule, _capsule.Layers[1], GraphicDeviceFactory.Device); } device.RasterizerStack.Pop(); }
protected override void LoadPhysics(Scene scene) { var material = scene.Physics.CreateMaterial(0.1f, 0.1f, 0.1f); var controllerManager = scene.CreateControllerManager(); // User controllable character { var desc = new CapsuleControllerDesc() { Height = 4, Radius = 1, Material = material, UpDirection = new Vector3(0, 1, 0), Position = new Vector3(0, 3, 0), // TODO: I think this is coming back in 3.3 (> beta 2) //Callback = new ControllerHitReport() }; _controller = controllerManager.CreateController<CapsuleController>(desc); } // Another controller to walk into { var desc = new CapsuleControllerDesc() { Height = 4, Radius = 1, Material = material, UpDirection = new Vector3(0, 1, 0), Position = new Vector3(15, 3, 15) }; controllerManager.CreateController<CapsuleController>(desc); } }
IEnumerator OnBegin() { yield return(new WaitForSeconds(0.5f)); //now check if u have an egg if (!egg) { //check if there is an egg nearby bool obj = Physics2D.OverlapCircle(firePoint.position, 4, eggMask); if (obj) { egg = Physics2D.OverlapCircle(firePoint.position, 1, eggMask).GetComponent <CapsuleController>(); egg.transform.position = firePoint.position; egg.transform.rotation = firePoint.rotation; } else { egg = Instantiate(eggPrefab, firePoint.position, firePoint.rotation); } egg.GetComponent <Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeAll; egg.transform.parent = transform; } }
public void LoadPhysics() { Core _core = this.Core; Scene _scene = this.Scene; #region Some Boxes for (int x = 0; x < 5; x++) { BoxShapeDescription boxShapeDesc = new BoxShapeDescription(2, 3, 8); ActorDescription actorDesc = new ActorDescription() { Name = String.Format("Box {0}", x), BodyDescription = new BodyDescription(10.0f), GlobalPose = Matrix.Translation(100, 15 + 3 * x, 20), Shapes = { boxShapeDesc } }; Actor actor = _scene.CreateActor(actorDesc); } #endregion //#region Cloth (Flag) //{ // // Create a Grid of Points // VertexGrid grid = VertexGrid.CreateGrid( 10, 10 ); // ClothMeshDescription clothMeshDesc = new ClothMeshDescription(); // clothMeshDesc.AllocateVertices<Vector3>( grid.Points.Length ); // clothMeshDesc.AllocateTriangles<int>( grid.Indices.Length / 3 ); // clothMeshDesc.VertexCount = grid.Points.Length; // clothMeshDesc.TriangleCount = grid.Indices.Length / 3; // clothMeshDesc.VerticesStream.SetData( grid.Points ); // clothMeshDesc.TriangleStream.SetData( grid.Indices ); // // We are using 32 bit integers, so make sure the 16 bit flag is removed. // // 32 bits are the default, so this isn't technically needed // clothMeshDesc.Flags &= ~MeshFlag.Indices16Bit; // // Write the cooked data to memory // MemoryStream memoryStream = new MemoryStream(); // Cooking.InitializeCooking(); // Cooking.CookClothMesh( clothMeshDesc, memoryStream ); // Cooking.CloseCooking(); // // Need to reset the position of the stream to the beginning // memoryStream.Position = 0; // ClothMesh clothMesh = _core.CreateClothMesh( memoryStream ); // // // ClothDescription clothDesc = new ClothDescription() // { // ClothMesh = clothMesh, // Flags = ClothFlag.Gravity | ClothFlag.Bending | ClothFlag.CollisionTwoway | ClothFlag.Visualization, // GlobalPose = // Matrix.CreateFromYawPitchRoll( 0, (float)Math.PI / 2.0f, (float)Math.PI / 2.0f ) * // Matrix.CreateTranslation( 0, 20, 0 ) // }; // clothDesc.MeshData.AllocatePositions<Vector3>( grid.Points.Length ); // clothDesc.MeshData.AllocateIndices<int>( grid.Indices.Length ); // clothDesc.MeshData.MaximumVertices = grid.Points.Length; // clothDesc.MeshData.MaximumIndices = grid.Indices.Length; // clothDesc.MeshData.NumberOfVertices = grid.Points.Length; // clothDesc.MeshData.NumberOfIndices = grid.Indices.Length; // _flag = _scene.CreateCloth( clothDesc ); // // Flag Pole // ActorDescription flagPoleActorDesc = new ActorDescription() // { // GlobalPose = Matrix.CreateTranslation( 0, 10, 0 ), // Shapes = { new BoxShapeDescription( 1.0f, 20.0f, 1.0f ) } // }; // Actor flagPoleActor = _scene.CreateActor( flagPoleActorDesc ); // _flag.AttachToShape( flagPoleActor.Shapes[ 0 ], 0 ); // _flag.WindAcceleration = new Vector3( 10, 10, 10 ); // _flag.BendingStiffness = 0.1f; //} //#endregion #region Revolute Joint { BoxShapeDescription boxShapeDescA = new BoxShapeDescription(3, 3, 3); BoxShapeDescription boxShapeDescB = new BoxShapeDescription(3, 3, 3); ActorDescription actorDescA = new ActorDescription() { BodyDescription = new BodyDescription(10.0f), GlobalPose = Matrix.Translation(75, 1.5f, 55), Shapes = { boxShapeDescA } }; Actor actorA = _scene.CreateActor(actorDescA); ActorDescription actorDescB = new ActorDescription() { BodyDescription = new BodyDescription(10.0f), GlobalPose = Matrix.Translation(70, 1.5f, 55), Shapes = { boxShapeDescB } }; Actor actorB = _scene.CreateActor(actorDescB); // RevoluteJointDescription revoluteJointDesc = new RevoluteJointDescription() { Actor1 = actorA, Actor2 = actorB, Motor = new MotorDescription(20, 20.1f, true) }; revoluteJointDesc.Flags |= RevoluteJointFlag.MotorEnabled; revoluteJointDesc.SetGlobalAnchor(new Vector3(73.5f, 1.5f, 55)); revoluteJointDesc.SetGlobalAxis(new Vector3(1, 0, 0)); RevoluteJoint revoluteJoint = _scene.CreateJoint(revoluteJointDesc) as RevoluteJoint; } #endregion #region Prismatic Joint with Limit { Actor actorA, actorB; { BoxShapeDescription boxShapeDesc = new BoxShapeDescription(3, 3, 3); BodyDescription bodyDesc = new BodyDescription(10.0f); bodyDesc.BodyFlags |= BodyFlag.Kinematic; ActorDescription actorDesc = new ActorDescription() { BodyDescription = bodyDesc, GlobalPose = Matrix.Translation(70, 25, 65), Shapes = { boxShapeDesc } }; actorA = _scene.CreateActor(actorDesc); } { BoxShapeDescription boxShapeDesc = new BoxShapeDescription(3, 3, 3); ActorDescription actorDesc = new ActorDescription() { BodyDescription = new BodyDescription(10.0f), GlobalPose = Matrix.Translation(70, 15, 65), Shapes = { boxShapeDesc } }; actorB = _scene.CreateActor(actorDesc); } PrismaticJointDescription prismaticJointDesc = new PrismaticJointDescription() { Actor1 = actorA, Actor2 = actorB, }; prismaticJointDesc.SetGlobalAnchor(new Vector3(70, 20, 65)); prismaticJointDesc.SetGlobalAxis(new Vector3(0, 1, 0)); PrismaticJoint prismaticJoint = _scene.CreateJoint(prismaticJointDesc) as PrismaticJoint; LimitPlane limitPlane = new LimitPlane(new Vector3(0, 1, 0), new Vector3(-30, 8, -30), 0); prismaticJoint.AddLimitPlane(limitPlane); } #endregion #region Fluid { const int maximumParticles = 1000; FluidEmitterDescription fluidEmitterDesc = new FluidEmitterDescription() { DimensionX = 0.5f, DimensionY = 0.5f, Rate = 15, RelativePose = Matrix.Translation(-40, 10, 50), Shape = EmitterShape.Rectangular, Type = EmitterType.ConstantFlowRate, RandomAngle = 0.5f }; fluidEmitterDesc.Flags |= (FluidEmitterFlag.Enabled | FluidEmitterFlag.Visualization); FluidDescription fluidDesc = new FluidDescription() { Emitters = { fluidEmitterDesc }, Flags = FluidFlag.Enabled | FluidFlag.Visualization, MaximumParticles = maximumParticles }; fluidDesc.ParticleWriteData.AllocatePositionBuffer <Vector3>(maximumParticles); fluidDesc.ParticleWriteData.NumberOfParticles = maximumParticles; Fluid fluid = _scene.CreateFluid(fluidDesc); // Ledge { BoxShapeDescription boxShapeDesc = new BoxShapeDescription(5, 0.1f, 5); ActorDescription drainActorDesc = new ActorDescription() { GlobalPose = Matrix.RotationX(0.5f) * Matrix.Translation(-40, 5, 52), Shapes = { boxShapeDesc } }; Actor drianActor = _scene.CreateActor(drainActorDesc); } // Drain { BoxShapeDescription boxShapeDesc = new BoxShapeDescription(5, 0.1f, 5); boxShapeDesc.Flags |= ShapeFlag.FluidDrain; ActorDescription drainActorDesc = new ActorDescription() { GlobalPose = Matrix.Translation(-40, 0, 55), Shapes = { boxShapeDesc } }; Actor drianActor = _scene.CreateActor(drainActorDesc); } } #endregion #region Force Field { BoxForceFieldShapeDescription boxForceFieldShapeDesc = new BoxForceFieldShapeDescription() { Size = new Vector3(10, 10, 10) }; ForceFieldLinearKernelDescription kernelDesc = new ForceFieldLinearKernelDescription() { Constant = new Vector3(0, 100.0f, 0) }; ForceFieldLinearKernel kernel = _scene.CreateForceFieldLinearKernel(kernelDesc); ForceFieldShapeGroupDescription shapeGroupDesc = new ForceFieldShapeGroupDescription() { Shapes = { boxForceFieldShapeDesc } }; ForceFieldShapeGroup shapeGroup = _scene.CreateForceFieldShapeGroup(shapeGroupDesc); BoxForceFieldShape boxForceFieldShape = shapeGroup.CreateShape(boxForceFieldShapeDesc) as BoxForceFieldShape; boxForceFieldShape.Pose = Matrix.Translation(30, 5, 0); ForceFieldDescription forceFieldDesc = new ForceFieldDescription() { Kernel = kernel, ShapeGroups = { shapeGroup } }; ForceField forceField = _scene.CreateForceField(forceFieldDesc); } #endregion #region Heightfield { int rows = 25; int columns = 25; HeightFieldSample[] samples = new HeightFieldSample[rows * columns]; for (int r = 0; r < rows; r++) { for (int c = 0; c < columns; c++) { // Put a z and x curve together double h = Math.Sin(c) * Math.Cos(r) * short.MaxValue; HeightFieldSample sample = new HeightFieldSample() { Height = (short)h, MaterialIndex0 = 0, MaterialIndex1 = 1, TessellationFlag = 0 }; samples[r * columns + c] = sample; } } HeightFieldDescription heightFieldDesc = new HeightFieldDescription() { NumberOfRows = rows, NumberOfColumns = columns }; heightFieldDesc.SetSamples(samples); HeightField heightField = _core.CreateHeightField(heightFieldDesc); // HeightFieldShapeDescription heightFieldShapeDesc = new HeightFieldShapeDescription() { HeightField = heightField, HoleMaterial = 2, // The max height of our samples is short.MaxValue and we want it to be 1 HeightScale = 1.0f / (float)short.MaxValue, RowScale = 3, ColumnScale = 3 }; heightFieldShapeDesc.LocalPosition = new Vector3(-0.5f * rows * 1 * heightFieldShapeDesc.RowScale, 0, -0.5f * columns * 1 * heightFieldShapeDesc.ColumnScale); ActorDescription actorDesc = new ActorDescription() { GlobalPose = Matrix.Translation(100, 0, 0), Shapes = { heightFieldShapeDesc } }; Actor actor = _scene.CreateActor(actorDesc); } #endregion //#region Convex Mesh //{ // ModelMesh mesh = _torusModel.Meshes.First(); // Matrix[] transforms = new Matrix[ _torusModel.Bones.Count ]; // _torusModel.CopyAbsoluteBoneTransformsTo( transforms ); // // Gets the vertices from the mesh // VertexPositionNormalTexture[] vertices = new VertexPositionNormalTexture[ mesh.MeshParts[ 0 ].NumVertices ]; // mesh.VertexBuffer.GetData<VertexPositionNormalTexture>( vertices ); // // // // Allocate memory for the points and triangles // var convexMeshDesc = new ConvexMeshDescription() // { // PointCount = vertices.Length // }; // convexMeshDesc.Flags |= ConvexFlag.ComputeConvex; // convexMeshDesc.AllocatePoints<Vector3>( vertices.Length ); // // Write in the points and triangles // // We only want the Position component of the vertex. Also scale down the mesh // foreach( VertexPositionNormalTexture vertex in vertices ) // { // Vector3 position = Vector3.Transform( vertex.Position, Matrix.CreateScale( 0.1f, 0.1f, 0.1f ) * transforms[ 0 ] ); // convexMeshDesc.PointsStream.Write( position ); // } // // // // Cook to memory or to a file // MemoryStream stream = new MemoryStream(); // //FileStream stream = new FileStream( @"Convex Mesh.cooked", FileMode.CreateNew ); // Cooking.InitializeCooking( new ConsoleOutputStream() ); // Cooking.CookConvexMesh( convexMeshDesc, stream ); // Cooking.CloseCooking(); // stream.Position = 0; // ConvexMesh convexMesh = _core.CreateConvexMesh( stream ); // ConvexShapeDescription convexShapeDesc = new ConvexShapeDescription( convexMesh ); // ActorDescription actorDesc = new ActorDescription() // { // BodyDescription = new BodyDescription( 10.0f ), // GlobalPose = Matrix.CreateTranslation( 30, 30, 0 ) // }; // actorDesc.Shapes.Add( convexShapeDesc ); // _torusActor = _scene.CreateActor( actorDesc ); //} //#endregion //#region SoftBody //if( false ) // Enable to view soft bodies, they run slowly //{ // XmlDocument doc = new XmlDocument(); // doc.Load( "Teapot.xml" ); // // Not how NxuStream are meant to used but what ever :S // Vector3[] vertices = ReadVertices( doc.SelectSingleNode( "/NXUSTREAM2/NxuPhysicsCollection/NxSoftBodyMeshDesc/vertices" ) ); // int[] tetrahedraSingles = ReadTetrahedra( doc.SelectSingleNode( "/NXUSTREAM2/NxuPhysicsCollection/NxSoftBodyMeshDesc/tetrahedra" ) ); // var softBodyMeshDesc = new SoftBodyMeshDescription() // { // VertexCount = vertices.Length, // TetrahedraCount = tetrahedraSingles.Length / 4 // Tetrahedras come in quadruples of ints // }; // softBodyMeshDesc.AllocateVertices<Vector3>( softBodyMeshDesc.VertexCount ); // softBodyMeshDesc.AllocateTetrahedra<int>( softBodyMeshDesc.TetrahedraCount ); // Note: T is an int. T is the type of each point // softBodyMeshDesc.VertexStream.SetData( vertices ); // softBodyMeshDesc.TetrahedraStream.SetData( tetrahedraSingles ); // MemoryStream memoryStream = new MemoryStream(); // Cooking.InitializeCooking(); // Cooking.CookSoftBodyMesh( softBodyMeshDesc, memoryStream ); // Cooking.CloseCooking(); // memoryStream.Position = 0; // SoftBodyMesh softBodyMesh = _core.CreateSoftBodyMesh( memoryStream ); // SoftBodyDescription desc = new SoftBodyDescription() // { // GlobalPose = Matrix.CreateTranslation( -30, 20, -30 ), // SoftBodyMesh = softBodyMesh // }; // desc.Flags |= SoftBodyFlag.Visualization; // desc.MeshData.AllocatePositions<Vector3>( vertices.Length ); // desc.MeshData.AllocateIndices<int>( tetrahedraSingles.Length ); // SoftBody softBody = _scene.CreateSoftBody( desc ); //} //#endregion //#region Reports //// Contact report //// When the capsule actor hits the ground make it bounce by using the conact report //{ // CapsuleShapeDescription capsuleShapeDesc = new CapsuleShapeDescription( 1, 5 ); // ActorDescription actorDesc = new ActorDescription() // { // GlobalPose = Matrix.CreateTranslation( -30, 20, 0 ), // BodyDescription = new BodyDescription( 10.0f ), // Name = "Report Capsule", // Shapes = { capsuleShapeDesc } // }; // _contactReportActor = _scene.CreateActor( actorDesc ); // _scene.SetActorPairFlags( _contactReportActor, _groundActor, ContactPairFlag.All ); // _scene.UserContactReport = new ContactReport( this ); //} //// Trigger Reports //{ // BoxShapeDescription boxShapeDesc = new BoxShapeDescription( 15, 8, 15 ); // boxShapeDesc.Flags |= ( ShapeFlag.TriggerOnEnter | ShapeFlag.TriggerOnLeave ); // ActorDescription actorDesc = new ActorDescription() // { // GlobalPose = Matrix.CreateTranslation( -30, 4, 0 ), // Shapes = { boxShapeDesc } // }; // _scene.CreateActor( actorDesc ); // _scene.UserTriggerReport = new TriggerReport( this ); //} //_scene.UserNotify = new Notify( this ); //#endregion //#region Wheel //{ // _basicVehicle = new Vehicle( this ); //} //#endregion #region Controller { ControllerManager manager = _scene.CreateControllerManager(); CapsuleControllerDescription capsuleControllerDesc = new CapsuleControllerDescription(4, 3); CapsuleController capsuleController = manager.CreateController <CapsuleController>(capsuleControllerDesc); capsuleController.Position = new Vector3(0, 1.5f + 2, -15); capsuleController.Actor.Name = "BoxController"; capsuleController.SetCollisionEnabled(true); } #endregion }
public static void TestPhysicsError() { Game game1 = new Game(); game1.Run(); /*XNAGame game = new XNAGame(); * bool flag = false; * game.UpdateEvent += delegate * { * if ( flag ) game.Exit(); * flag = true; * }; * * game.Run();*/ using (PhysicsEngine engine = new PhysicsEngine()) { StillDesign.PhysX.Scene scene; CapsuleController controller = null; ControllerManager manager; /* * game.InitializeEvent += * delegate * {*/ engine.Initialize(null); scene = engine.Scene; manager = scene.CreateControllerManager(); CapsuleControllerDescription capsuleControllerDesc = new CapsuleControllerDescription(0.5f, 1); CapsuleController capsuleController = manager.CreateController <CapsuleController>(capsuleControllerDesc); controller = capsuleController; ActorDescription actorDesc; Actor actor; BoxShapeDescription boxShapeDesc = new BoxShapeDescription(1, 1, 1); actorDesc = new ActorDescription(boxShapeDesc); actorDesc.BodyDescription = new BodyDescription(1f); actor = engine.Scene.CreateActor(actorDesc); actor.GlobalPosition = new Vector3(1, 4, 0); controller.Move(Vector3.Up); engine.Update(null); controller.Move(Vector3.Up); /* }; * * game.UpdateEvent += delegate { if (flag) game.Exit(); * flag = true; }; * * game.Run();*/ } }