private void ChocarConBolasDeCanion() { foreach (var mesh in scene.Meshes) { var mainMeshBoundingBox = personajePrincipal.BoundingBox; var sceneMeshBoundingBox = mesh.BoundingBox; if (mainMeshBoundingBox == sceneMeshBoundingBox) { continue; } var collisionResult = TgcCollisionUtils.classifyBoxBox(mainMeshBoundingBox, sceneMeshBoundingBox); if (collisionResult != TgcCollisionUtils.BoxBoxResult.Afuera) { if (mesh.Name == "Sphere") { if (cantVidas < 1) { AdministradorDeEscenarios.getSingleton().agregarEscenario(new GameOver(), camaraInterna); } personajePrincipal.Position = puntoCheckpointActual; cantVidas--; } } } }
public bool colisionaPorArribaDe(TgcMesh mesh) { TgcBoundingSphere esferaAuxiliar = new TgcBoundingSphere(esferaPersonaje.Center, esferaPersonaje.Radius); esferaAuxiliar.moveCenter(new TGCVector3(0f, -RADIO_ESFERA, 0f)); return(TgcCollisionUtils.testSphereAABB(esferaAuxiliar, mesh.BoundingBox)); }
/// <summary> /// Detección de colisiones, filtrando los obstaculos que se encuentran dentro del radio de movimiento /// </summary> private void collideWithWorld(TgcBoundingSphere characterSphere, Vector3 movementVector, List <Collider> colliders, bool sliding, float slidingMinY) { //Ver si la distancia a recorrer es para tener en cuenta var distanceToTravelSq = movementVector.LengthSq(); if (distanceToTravelSq < EPSILON) { return; } //Dejar solo los obstáculos que están dentro del radio de movimiento de la esfera var halfMovementVec = Vector3.Multiply(movementVector, 0.5f); movementSphere.setValues( characterSphere.Center + halfMovementVec, halfMovementVec.Length() + characterSphere.Radius ); objetosCandidatos.Clear(); foreach (var collider in colliders) { if (collider.Enable && TgcCollisionUtils.testSphereSphere(movementSphere, collider.BoundingSphere)) { objetosCandidatos.Add(collider); } } //Detectar colisiones y deplazar con sliding doCollideWithWorld(characterSphere, movementVector, objetosCandidatos, 0, movementSphere, sliding, slidingMinY); }
public void ajustarCamaraSegunColision(Auto auto, List <ObstaculoRigido> obstaculos) { TgcThirdPersonCamera camera = GuiController.Instance.ThirdPersonCamera; Vector3 segmentA; Vector3 segmentB; camera.generateViewMatrix(out segmentA, out segmentB); //Detectar colisiones entre el segmento de recta camara-personaje y todos los objetos del escenario Vector3 q; float minDistSq = FastMath.Pow2(camera.OffsetForward); foreach (ObstaculoRigido obstaculo in obstaculos) { //Hay colision del segmento camara-personaje y el objeto if (TgcCollisionUtils.intersectSegmentAABB(segmentB, segmentA, obstaculo.mesh.BoundingBox, out q)) { //Si hay colision, guardar la que tenga menor distancia float distSq = (Vector3.Subtract(q, segmentB)).LengthSq(); if (distSq < minDistSq) { minDistSq = distSq; //Le restamos un poco para que no se acerque tanto minDistSq /= 2; } } } //Acercar la camara hasta la minima distancia de colision encontrada (pero ponemos un umbral maximo de cercania) float newOffsetForward = FastMath.Sqrt(minDistSq); camera.OffsetForward = newOffsetForward; }
/// <summary> /// Separa los modelos en dos listas, segun el testo contra el plano de corte /// </summary> private void splitByPlane(TGCPlane cutPlane, List <TgcMesh> modelos, List <TgcMesh> possitiveList, List <TgcMesh> negativeList) { TgcCollisionUtils.PlaneBoxResult c; foreach (var modelo in modelos) { c = TgcCollisionUtils.classifyPlaneAABB(cutPlane, modelo.BoundingBox); //possitive side if (c == TgcCollisionUtils.PlaneBoxResult.IN_FRONT_OF) { possitiveList.Add(modelo); } //negative side else if (c == TgcCollisionUtils.PlaneBoxResult.BEHIND) { negativeList.Add(modelo); } //both sides else { possitiveList.Add(modelo); negativeList.Add(modelo); } } }
/// <summary> /// Picking con los planos XZ e YZ ubicados en el centro del objeto /// </summary> public TGCVector3 getPickingZ(TgcRay ray, TGCVector3 objCenter) { //Mover ambos planos hacia el centro del objeto pickingXZAabb.setExtremes( new TGCVector3(pickingXZAabb.PMin.X, objCenter.Y - SMALL_VAL, pickingXZAabb.PMin.Z), new TGCVector3(pickingXZAabb.PMax.X, objCenter.Y, pickingXZAabb.PMax.Z)); pickingYZAabb.setExtremes( new TGCVector3(objCenter.X - SMALL_VAL, pickingYZAabb.PMin.Y, pickingYZAabb.PMin.Z), new TGCVector3(objCenter.X, pickingYZAabb.PMax.Y, pickingYZAabb.PMax.Z)); TGCVector3 q1, q2; bool r1, r2; r1 = TgcCollisionUtils.intersectRayAABB(ray, pickingXZAabb, out q1); r2 = TgcCollisionUtils.intersectRayAABB(ray, pickingYZAabb, out q2); if (r1 && r2) { var objPos = new TGCVector2(objCenter.X, objCenter.Y); var diff1 = TGCVector2.Length(new TGCVector2(q1.X, q1.Y) - objPos); var diff2 = TGCVector2.Length(new TGCVector2(q2.X, q2.Y) - objPos); return(diff1 < diff2 ? q1 : q2); } if (r1) { return(clampPickingResult(q1)); } if (r2) { return(clampPickingResult(q2)); } return(objCenter); }
public override bool intersectRay(TgcRay ray, Matrix transform, out Vector3 q) { COLLISION_SPHERE.setCenter(Vector3.TransformCoordinate(position, transform)); float t; return(TgcCollisionUtils.intersectRaySphere(ray, COLLISION_SPHERE, out t, out q)); }
//refactorizar este metodo static public void CheckColisions() { List <BolaDeCanion> disparosDisposables = new List <BolaDeCanion>(); List <Barco> barcosDisposables = new List <Barco>(); foreach (BolaDeCanion disparo in Disparos) { foreach (Barco barco in Barcos) { if (TgcCollisionUtils.testSphereSphere(disparo.boundingSphere, barco.boundingSphere) && disparo.noEsDel(barco)) { disparosDisposables.Add(disparo); barco.vida--; if (barco.vida == 0) { barcosDisposables.Add(barco); } } } } foreach (BolaDeCanion tiro in disparosDisposables) { InteractionManager.Disparos.Remove(tiro); } foreach (Barco barca in barcosDisposables) { InteractionManager.Barcos.Remove(barca); } }
public bool CheckCollision(NaveEspacial nave) { TGCVector3 offset = this.GetOffsetVectorMoved(); foreach (KeyValuePair <TgcBoundingAxisAlignBox, TGCVector3> entry in boundingBoxes) { entry.Key.scaleTranslate(entry.Value + offset, TGCVector3.One); if (TgcCollisionUtils.testObbAABB(nave.OOB, entry.Key)) { return(true); } } foreach (var m in boundingBoxesTowers) { m.Transform = TGCMatrix.Translation(offset); m.BoundingBox.transform(m.Transform); if (TgcCollisionUtils.testObbAABB(nave.OOB, m.BoundingBox)) { return(true); } } return(torres.FindAll(t => TgcCollisionUtils.testObbAABB(nave.OOB, t.Scene.BoundingBox)).Count > 0); }
/// <summary> /// Picking sobre un triangulo /// </summary> public bool pickTriangle(out TgcTriangle triangle, out int triangleIndex) { pickingRay.updateRay(); var segmentA = pickingRay.Ray.Origin; var segmentB = segmentA + TGCVector3.Scale(pickingRay.Ray.Direction, 10000f); var minDist = float.MaxValue; triangle = null; triangleIndex = -1; //Buscar la menor colision rayo-triangulo for (var i = 0; i < Triangles.Count; i++) { var tri = Triangles[i]; float t; TGCVector3 uvw; TGCVector3 col; if (TgcCollisionUtils.intersectLineTriangle(segmentA, segmentB, tri.A, tri.B, tri.C, out uvw, out t, out col)) { var dist = TGCVector3.Length(col - segmentA); if (dist < minDist) { minDist = dist; triangle = tri; triangleIndex = i; } } } return(triangle != null); }
virtual public Quadrant GetCuadrante(TGCVector3 testPoint) { GlobalConcepts global = GlobalConcepts.GetInstance(); if (global.IsInFrontOf(testPoint, AI.planoCostado) && TgcCollisionUtils.testPlaneAABB(AI.directionPlane, Scene.GetInstance().auto.mesh.BoundingBox)) { return(new QuadranInFrontOf(this.AI.GetEstado())); } if (global.IsInFrontOf(testPoint, AI.planoCostado) && global.IsInFrontOf(testPoint, AI.directionPlane)) { return(new QuadrantTopRight(this.AI.GetEstado())); } if (global.IsInFrontOf(testPoint, AI.planoCostado) && !global.IsInFrontOf(testPoint, AI.directionPlane)) { return(new QuadrantTopLeft(this.AI.GetEstado())); } if (!global.IsInFrontOf(testPoint, AI.planoCostado) && !global.IsInFrontOf(testPoint, AI.directionPlane)) { return(new QuadrantBottomLeft(this.AI.GetEstado())); } if (!global.IsInFrontOf(testPoint, AI.planoCostado) && global.IsInFrontOf(testPoint, AI.directionPlane)) { return(new QuadrantBottomRight(this.AI.GetEstado())); } throw new Exception("No se encuentra en ningun cuadrante"); }
public void Update(TgcD3dInput Input) { efecto.SetValue("_Time", GameModel.time); efecto.SetValue("alturaEnY", GameLogic.cantidadZombiesMuertos * 10); #region chequeoDeColision //Si hacen clic con el mouse, ver si hay colision RayAABB if (Input.buttonPressed(TgcD3dInput.MouseButtons.BUTTON_LEFT)) { pickingRay.updateRay(); //Testear Ray contra el AABB de todos los meshes foreach (var unaPlataforma in plataformas)//.Where(p => !p.ocupado).ToList()) { var aabb = unaPlataforma.mesh.BoundingBox; //Ejecutar test, si devuelve true se carga el punto de colision collisionPoint selected = TgcCollisionUtils.intersectRayAABB(pickingRay.Ray, aabb, out collisionPoint); if (selected) { plataformaSeleccionada = unaPlataforma; unaPlataforma.mesh.BoundingBox.setRenderColor(Color.LightBlue); break; } } } #endregion }
public void renderPasto(float tLeftMoved, float tRightMoved, int parte) { if ((CustomFpsCamera.Instance.eye - partePasto[parte].Origin).Length() < CustomFpsCamera.FAR_PLANE / 4.5) { TgcCollisionUtils.FrustumResult result = TgcCollisionUtils.classifyFrustumAABB(GuiController.Instance.Frustum, partePasto[parte].BoundingBox); if (result != TgcCollisionUtils.FrustumResult.OUTSIDE) { Device d3dDevice = GuiController.Instance.D3dDevice; TgcTexture.Manager texturesManager = GuiController.Instance.TexturesManager; d3dDevice.RenderState.AlphaTestEnable = true; d3dDevice.RenderState.AlphaBlendEnable = true; TgcPlaneWall pastoWall = partePasto[parte]; texturesManager.shaderSet(pastoWall.Effect, "texDiffuseMap", pastoWall.Texture); texturesManager.clear(1); GuiController.Instance.Shaders.setShaderMatrixIdentity(pastoWall.Effect); d3dDevice.VertexDeclaration = GuiController.Instance.Shaders.VdecPositionTextured; pastoWall.Effect.Technique = pastoWall.Technique; //Render con shader pastoWall.Effect.Begin(0); pastoWall.Effect.BeginPass(0); d3dDevice.DrawUserPrimitives(PrimitiveType.TriangleList, 2, actualizarPasto(tLeftMoved, tRightMoved, parte, pastoWall)); pastoWall.Effect.EndPass(); pastoWall.Effect.End(); d3dDevice.RenderState.AlphaTestEnable = false; d3dDevice.RenderState.AlphaBlendEnable = false; } } }
public static Vector3 getClosesPointBetween(TgcRay rayCast, BoundingBoxCollider boundingBox) { Vector3 vector = new Vector3(); TgcCollisionUtils.intersectRayAABB(rayCast, boundingBox.Aabb, out vector); return(vector); }
/// <summary> /// testea colisiones AABB /// </summary> private void testCollisions() { if (Player1.Moving) { foreach (InteractiveObject objeto in MyWorld.Objetos) { if (objeto.mesh.Enabled && objeto.Solid) { MyCamera.CameraBox.Position = Camara.Position; TgcBox cameraBox = MyCamera.CameraBox; if (TgcCollisionUtils.testAABBAABB(cameraBox.BoundingBox, objeto.mesh.BoundingBox)) { collidedObject = objeto; MyCamera.Collisioned = true; break; } else { MyCamera.Collisioned = false; } } } } }
private void updateLighting() { Microsoft.DirectX.Direct3D.Effect currentShader; //Con luz: Cambiar el shader actual por el shader default que trae el framework para iluminacion dinamica con PointLight if (personaje.tieneLuz) { currentShader = TGCShaders.Instance.TgcMeshSpotLightShader; } else { currentShader = TGCShaders.Instance.TgcMeshPointLightShader; } if (personaje.estoyAdentro) { currentShader = TGCShaders.Instance.LoadEffect(ShadersDir + "ShaderIndoor.fx"); } var iluminablesFiltrado = iluminables.FindAll(mesh => TgcCollisionUtils.classifyFrustumAABB(this.Frustum, mesh.BoundingBox) != TgcCollisionUtils.FrustumResult.OUTSIDE); //Aplicar a cada mesh el shader actual foreach (TgcMesh mesh in iluminablesFiltrado) { this.AplicarShader(mesh, currentShader); } }
/// <summary> /// Hacer picking contra todos los ejes y devolver el eje seleccionado (si hay colision). /// Tambien se evaluan los ejes compuestos (XY, XZ, YZ) /// </summary> public Axis doPickAxis(TgcRay ray) { TGCVector3 collP; if (TgcCollisionUtils.intersectRayAABB(ray, boxX.BoundingBox, out collP)) { return(Axis.X); } if (TgcCollisionUtils.intersectRayAABB(ray, boxY.BoundingBox, out collP)) { return(Axis.Y); } if (TgcCollisionUtils.intersectRayAABB(ray, boxZ.BoundingBox, out collP)) { return(Axis.Z); } if (TgcCollisionUtils.intersectRayAABB(ray, boxXZ.BoundingBox, out collP)) { return(Axis.XZ); } if (TgcCollisionUtils.intersectRayAABB(ray, boxXY.BoundingBox, out collP)) { return(Axis.XY); } if (TgcCollisionUtils.intersectRayAABB(ray, boxYZ.BoundingBox, out collP)) { return(Axis.YZ); } return(Axis.None); }
public void HandleCollision(Vehicle car) { if (TgcCollisionUtils.testObbObb(car.GetTGCBoundingOrientedBox(), this.GetTGCBoundingOrientedBox())) { this.Collide(car); } }
/// <summary> /// Hacer visible las meshes de un nodo si es visible por el Frustum /// </summary> private void testChildVisibility(TgcFrustum frustum, OctreeNode childNode, float boxLowerX, float boxLowerY, float boxLowerZ, float boxUpperX, float boxUpperY, float boxUpperZ) { if (childNode == null) { return; } //test frustum-box intersection var caja = new TgcBoundingAxisAlignBox( new TGCVector3(boxLowerX, boxLowerY, boxLowerZ), new TGCVector3(boxUpperX, boxUpperY, boxUpperZ)); var c = TgcCollisionUtils.classifyFrustumAABB(frustum, caja); //complementamente adentro: cargar todos los hijos directamente, sin testeos if (c == TgcCollisionUtils.FrustumResult.INSIDE) { addAllLeafMeshes(childNode); } //parte adentro: seguir haciendo testeos con hijos else if (c == TgcCollisionUtils.FrustumResult.INTERSECT) { findVisibleMeshes(frustum, childNode, boxLowerX, boxLowerY, boxLowerZ, boxUpperX, boxUpperY, boxUpperZ); } }
private static void chequearColision(TgcBoundingSphere sphere, Barril barril) { if (TgcCollisionUtils.testSphereAABB(sphere, barril.mesh.BoundingBox)) { barril.explotar(); } }
public bool personajeSobreLava() { var auxiliarBoundingBox = personaje.boundingBox(); auxiliarBoundingBox.move(new TGCVector3(0, -Ypiso, 0)); return(LavaMesh().Exists(lava => TgcCollisionUtils.testAABBAABB(lava.BoundingBox, auxiliarBoundingBox))); }
/// <summary> /// Renderiza el terreno /// </summary> public void render() { TgcFrustum frustum = GuiController.Instance.Frustum; for (int i = 0; i < vbTerrains.Count; i++) { TgcCollisionUtils.FrustumResult c = TgcCollisionUtils.classifyFrustumAABB(frustum, boundingBoxes[i]); if (c == TgcCollisionUtils.FrustumResult.INSIDE || c == TgcCollisionUtils.FrustumResult.INTERSECT) { Vector3 centroBB = (boundingBoxes[i].PMax + boundingBoxes[i].PMin); centroBB.Multiply(0.5f); if (((CustomFpsCamera.Instance.eye - centroBB).Length() < CustomFpsCamera.FAR_PLANE / 1.5f)) { renderTerrain(vbTerrains[i]); GameManager.Instance.terrenosVisibles++; } } bool drawBoundingBoxes = GameManager.Instance.drawBoundingBoxes; if (drawBoundingBoxes) { boundingBoxes[i].render(); } } }
public override void render(float elapsedTime) { TgcModifiers modifiers = GuiController.Instance.Modifiers; Vector2 size = (Vector2)modifiers.getValue("size"); Vector3 position = (Vector3)modifiers.getValue("position"); Vector3 rotation = (Vector3)modifiers.getValue("rotation"); collider.Center = position; collider.Rotation = rotation; collider.Radius = size.X; collider.Length = size.Y; collider.updateValues(); if (TgcCollisionUtils.testSphereCylinder(collisionableSphere, collider)) { collisionableSphere.setRenderColor(collisionColor); } else { collisionableSphere.setRenderColor(noCollisionColor); } collider.render(); collisionableSphere.render(); }
private void ColisionNave(float elapsedTime) { TgcBoundingBox NaveBBox = nave.Modelo.BoundingBox; TgcBoundingBox EnemigoBBox = NaveEnemiga1.Modelo.BoundingBox; if (TgcCollisionUtils.classifyBoxBox(NaveBBox, EnemigoBBox) != TgcCollisionUtils.BoxBoxResult.Afuera) // CONVERTIR EN UN FOREACH CUANDO HAYA LISTA DE ENEMIGOS { NaveEnemiga1.Modelo.Position -= new Vector3(-50, 0, 0); return; } foreach (TgcMesh mesh in Universo.Meshes) { if (mesh.Name == "Universo") { continue; } TgcBoundingBox SceneBBox = mesh.BoundingBox; TgcCollisionUtils.BoxBoxResult collisionResult = TgcCollisionUtils.classifyBoxBox(NaveBBox, SceneBBox); if (collisionResult != TgcCollisionUtils.BoxBoxResult.Afuera) { nave.Modelo.moveOrientedY(10000f * elapsedTime); return; } } }
public bool colisionaConCaja(Caja box) { TgcBoundingAxisAlignBox boundingBoxColision = boundingBox(); boundingBoxColision.scaleTranslate(position(), new TGCVector3(2.5f, 2.5f, 2.5f)); return(TgcCollisionUtils.testAABBAABB(boundingBoxColision, box.boundingBox())); }
private void _Build(Single deltaTime) { _PickingRay.updateRay(); Single t; Vector3 position; TgcCollisionUtils.intersectRayPlane(_PickingRay.Ray, Plane, out t, out position); _Selected.Build(deltaTime); _Selected.Position = position; _SelectedColor = _Menu.Collides(_Selected) ? Color.Blue : (_Items.Any(i => i.Collides(_Selected)) ? Color.Red : Color.Green); var input = GuiController.Instance.D3dInput; var left = TgcD3dInput.MouseButtons.BUTTON_LEFT; if (input.buttonPressed(left)) { if (_SelectedColor == Color.Blue) { _Menu.Add(_Selected); _Selected = null; } else if (_SelectedColor == Color.Green) { _Actives.Add(Add(_Selected)); _Selected = null; } } }
public bool colisionConPisoDesnivelado(TgcMesh pisoDesnivelado) { TgcBoundingSphere esferaAuxiliar = new TgcBoundingSphere(esferaPersonaje.Center, esferaPersonaje.Radius); esferaAuxiliar.moveCenter(new TGCVector3(0f, -RADIO_ESFERA, 0f)); return(TgcCollisionUtils.testSphereAABB(esferaAuxiliar, pisoDesnivelado.BoundingBox)); }
/// <summary> /// Detectar el eje seleccionado /// </summary> public void detectSelectedAxis(TgcPickingRay pickingRay) { pickingRay.updateRay(); TGCVector3 collP; //Buscar colision con eje con Picking if (TgcCollisionUtils.intersectRayAABB(pickingRay.Ray, boxX.BoundingBox, out collP)) { SelectedAxis = Axis.X; selectedAxisBox = boxX; } else if (TgcCollisionUtils.intersectRayAABB(pickingRay.Ray, boxY.BoundingBox, out collP)) { SelectedAxis = Axis.Y; selectedAxisBox = boxY; } else if (TgcCollisionUtils.intersectRayAABB(pickingRay.Ray, boxZ.BoundingBox, out collP)) { SelectedAxis = Axis.Z; selectedAxisBox = boxZ; } else { SelectedAxis = Axis.None; selectedAxisBox = null; } //Desplazamiento inicial if (SelectedAxis != Axis.None) { initMouseP = new TGCVector2(input.XposRelative, input.YposRelative); } }
//Gamemodel functions public void Spawn() { //Reset vars canDealDamage = true; SetPlayerGoalPos(); //Position shark Random r = new Random(); var sign = r.Next(-1, 1) >= 0 ? 1 : -1; var x = FastMath.Max(0.3f, (float)r.NextDouble() * sign); var z = FastMath.Max(0.3f, (float)r.NextDouble() * sign); var y = FastMath.Min(yMax, Player.Instance().Position().Y); TGCVector3 playerPos = Player.Instance().Position(); playerPos.Y = y; mesh.Position = playerPos + new TGCVector3(x, 0, z) * 250f; //Check for collisions foreach (var naveMesh in Nave.Instance().obtenerMeshes()) { bool col = TgcCollisionUtils.testAABBAABB(mesh.BoundingBox, naveMesh.BoundingBox); if (col) { mesh.Position = TGCVector3.Empty; break; } } }
private void DetectarColisionesMovibles(TGCVector3 lastPos, TgcMesh meshAProbar) { var collisionFound = false; foreach (var mesh in scene.Meshes) { //Los dos BoundingBox que vamos a testear var mainMeshBoundingBox = meshAProbar.BoundingBox; var sceneMeshBoundingBox = mesh.BoundingBox; if (mainMeshBoundingBox == sceneMeshBoundingBox) { continue; } //Ejecutar algoritmo de detección de colisiones var collisionResult = TgcCollisionUtils.classifyBoxBox(mainMeshBoundingBox, sceneMeshBoundingBox); if (collisionResult != TgcCollisionUtils.BoxBoxResult.Afuera && mainMeshBoundingBox != personajePrincipal.BoundingBox) { collisionFound = true; } } if (collisionFound) { meshAProbar.Position = lastPos; } }