public void GenerateParticleOffset(string blendShapeName) { SkinnedMeshRenderer skinnedMeshRender = Model.GetComponentInChildren <SkinnedMeshRenderer>(); BlendShapeLoader loader = BlendShapeLoader.GetComponent <BlendShapeLoader>(); MeshCollider meshCollider = loader.CurrentModel.AddComponent <MeshCollider>(); Dictionary <string, float> blendValues = loader.GetBlendShapeValues(); loader.SetBlendShapeValue(blendShapeName, 1.0f); Mesh bakedMesh = new Mesh(); skinnedMeshRender.BakeMesh(bakedMesh); meshCollider.sharedMesh = bakedMesh; foreach (GameObject gameObject in m_particleEntities.Values) { DynamicParticleComponent particle = gameObject.GetComponent <DynamicParticleComponent>(); BodyShapeOffSetTable offsets = particle.ParticleInfo.VertInfo.BodyShapeOffsetTable; float colliderRadius = particle.ParticleInfo.ConfigValues.m_colliderRadius; float colliderRadiusScale = particle.ParticleInfo.VertInfo.ColliderRadiusScale; Vector3 pointOnMesh = meshCollider.ClosestPoint(gameObject.transform.position); Vector3 dir = (pointOnMesh - gameObject.transform.position).normalized; Vector3 finalPosition = pointOnMesh + dir * (colliderRadius * colliderRadiusScale); offsets.Definitions[blendShapeName] = finalPosition; } DestroyImmediate(meshCollider); }
//Creates an empty cube of equally spaced points around an object using size variables defined in awake() //afterwards, "snaps" each point to the closest point on the game object this script is attached to. void GenerateGrid() { Vector3 startPos = renderer.transform.position; //generate empty cube list of vertices. Surrounds object in question. float step = 1f; int reset = 0; vertices = new Vector3[(int)((2 * (xSize) * (ySize)) + (2 * (zSize) * (ySize)) + (2 * (xSize) * (zSize))) / (3)]; int i = 0; for (float y = 0; y <= ySize; y += step) { for (float z = 0; z <= zSize; z += step) { for (float x = 0; x <= xSize; x += step) { if (x == 0 || x == xSize || y == 0 || y == ySize || z == 0 || z == zSize) { if (reset == 2) { vertices[i] = new Vector3( startPos.x - (xSize / 2) + (float)x, startPos.y - (ySize / 2) + (float)y, startPos.z - (zSize / 2) + (float)z); i++; reset = 0; } else { reset++; } } } } } //vertices[] is a list of vertices creating a box around an object. //snap vertices to object // moves each point ever so slightly away from the surface. Vector3[] tempVertices = vertices; for (int j = 0; j < tempVertices.Length; j++) { Vector3 closePoint = collider.ClosestPoint(tempVertices[j]); //vertices[j] = closePoint; vertices[j] = Vector3.MoveTowards(closePoint, collider.transform.position, -0.03f); } }
public override Vector3 FieldValue(Vector3 fieldPoint) { //Finds the closest point on the generator to the field point, and returns a vector pointing straight at it. closePoint = collider.ClosestPoint(fieldPoint); Vector3 field = twoDStrength.Strength / Mathf.Pow(Vector3.Distance(closePoint, fieldPoint), 3) * (fieldPoint - closePoint); return(field); }
private void CheckDistanceAdvanced() { MeshCollider obstacleCollider = Obstacle.ObstacleGO.GetComponentInChildren <MeshCollider>(); Vector3 obstacleColliderPoint = obstacleCollider.ClosestPoint(Ship.GetPosition()); MeshCollider shipCollider = Ship.GetCollider(); Vector3 shipColliderPoint = shipCollider.ClosestPoint(obstacleColliderPoint); float distanceBetweenEdges = Vector3.Distance(shipColliderPoint, obstacleColliderPoint); Range = Mathf.Max(1, Mathf.CeilToInt(distanceBetweenEdges / Board.DISTANCE_INTO_RANGE)); }
public void Dis_Manager() { GameObject point_cloud = GameObject.Find("point_cloud"); GameObject point_cloud_data = point_cloud.transform.Find("default").gameObject; GameObject master = GameObject.Find("master_data"); GameObject master_data = master.transform.Find("default").gameObject; Mesh point_cloud_mesh = point_cloud_data.GetComponent <MeshFilter>().mesh; Mesh master_data_mesh = master_data.GetComponent <MeshFilter>().mesh; master_data_mesh.SetIndices(master_data_mesh.GetIndices(0), MeshTopology.Triangles, 0); point_cloud_mesh.SetIndices(point_cloud_mesh.GetIndices(0), MeshTopology.Triangles, 0); point_cloud_data.AddComponent <MeshCollider>(); master_data.AddComponent <MeshCollider>(); MeshCollider point_cloud_col = point_cloud_data.GetComponent <MeshCollider>(); MeshCollider master_data_col = master_data.GetComponent <MeshCollider>(); point_cloud_col.convex = true; master_data_col.convex = true; Matrix4x4 master_data_matrix = master_data.transform.localToWorldMatrix; Vector3[] master_data_vertices = master_data_mesh.vertices; List <float> master_dis_save = new List <float>(); float Max_dis = -10000; foreach (Vector3 vertex in master_data_vertices) { Vector3 vec = master_data_matrix.MultiplyPoint3x4(vertex); float dis = Vector3.Distance(vec, point_cloud_col.ClosestPoint(vec)); // Debug.Log(vec + " " + point_cloud_col.ClosestPoint(vec) + " " + dis); master_dis_save.Add(dis); if (dis > Max_dis) { Max_dis = dis; } } Color[] master_mesh_colors = new Color[master_data_vertices.Length]; for (int i = 0; i < master_mesh_colors.Length; i++) { if (master_dis_save[i] == 0f) { master_mesh_colors[i] = new Color(1.0f, 0.0f, 0.0f, 0.0f); } else { master_mesh_colors[i] = new Color(0.0f, 1.0f * (1.0f - master_dis_save[i] / Max_dis), 1.0f * (master_dis_save[i] / Max_dis), 0.5f); } } master_data_mesh.colors = master_mesh_colors; master_data_mesh.SetIndices(master_data_mesh.GetIndices(0), MeshTopology.Points, 0); point_cloud.SetActive(false); }
private void CheckDistanceAdvanced() { MeshCollider obstacleCollider = Obstacle.ObstacleGO.GetComponentInChildren <MeshCollider>(); NearestPointObstacle = obstacleCollider.ClosestPoint(Ship.GetPosition()); MeshCollider shipCollider = Ship.GetCollider(); NearestPointShip = shipCollider.ClosestPoint(NearestPointObstacle); DistanceReal = Vector3.Distance(NearestPointShip, NearestPointObstacle); Range = Board.DistanceToRange(DistanceReal); }
private void CheckDistanceAdvanced() { MeshCollider obstacleCollider = Obstacle.ObstacleGO.GetComponentInChildren <MeshCollider>(); NearestPointObstacle = obstacleCollider.ClosestPoint(Ship.GetPosition()); MeshCollider shipCollider = Ship.GetCollider(); NearestPointShip = shipCollider.ClosestPoint(NearestPointObstacle); DistanceReal = Vector3.Distance(NearestPointShip, NearestPointObstacle); Range = Mathf.Max(1, Mathf.CeilToInt(DistanceReal / Board.DISTANCE_INTO_RANGE)); }
/// <summary>Calcule la distance minimum entre un point et un mesh. Si c'est négatif, indique la profondeur du point dans le mesh.</summary> public static float Dist(MeshCollider m, Point p) { float max = float.MinValue; foreach (Plane pl in m.GetPlanes()) { max = Mathf.Max(DistSigned(pl, p), max); } float d = (max > 0) ? Dist(m.ClosestPoint(p), p) : max; return(d); //return Dist(m.ClosestPoint(p), p); }
public override Vector3 FieldValue(Vector3 fieldPoint) { //scales between close point and center of mass of object, further away the more the center takes over closePoint = collider.ClosestPoint(fieldPoint); Vector3 field = 2 * Vector3.Normalize(fieldPoint - closePoint) / (Vector3.Distance(closePoint, fieldPoint)); Vector3 fieldCenter = (Vector3.Distance(closePoint, fieldPoint)) * Vector3.Normalize(fieldPoint - gameObject.transform.position); Vector3 finalField = threeDStrength.Strength * (field + fieldCenter) / (3 * Mathf.Pow(Vector3.Distance(fieldPoint, closePoint), 3)); return finalField; }
IEnumerator Spawn(GameObject prefab) { var bounds = collider.sharedMesh.bounds; //var objbounds = prefab.GetComponent<SpawnedObject>().myCollider.bounds.extents ; //Debug.Log(objbounds); var readyToSpawn = true; var position = Vector3.zero; readyToSpawn = true; var newX = Random.Range(bounds.min.x * 1.8f, bounds.max.x * 1.8f); var newZ = Random.Range(bounds.min.z * 1.8f, bounds.max.z * 1.8f); var newY = bounds.max.y * 2; position = new Vector3(newX, newY, newZ) + transform.position; position = collider.ClosestPoint(position); //RaycastHit[] hits = Physics.BoxCastAll(position, objbounds, Vector3.one); RaycastHit[] hits = Physics.SphereCastAll(new Ray(position, new Vector3(1, 1, 1)), 1.5f); foreach (var item in hits) { if (item.collider.gameObject.layer == LayerMask.NameToLayer("SpawnedObject")) { readyToSpawn = false; counter++; yield break; } } var go = Instantiate(prefab, transform); yield return(new WaitForEndOfFrame()); go.transform.position = position; if (currentTile) { go.GetComponent <SpawnedObject>().audioSource = currentTile.audioSource; } go.GetComponent <SpawnedObject>().PlaySound(); go.GetComponent <SpawnedObject>().desiredScale = Vector3.one * Random.Range(0.8f, 1.2f); spawned++; trees.Add(go); //go.transform.SetParent(transform); }
private void CheckDistanceAdvanced() { float minDistance = float.MaxValue; foreach (Vector3 bombPoint in BombsManager.GetBombPoints(Bomb)) { MeshCollider obstacleCollider = Obstacle.ObstacleGO.GetComponentInChildren <MeshCollider>(); Vector3 obstacleColliderPoint = obstacleCollider.ClosestPoint(bombPoint); float distanceBetweenEdges = Vector3.Distance(bombPoint, obstacleColliderPoint); if (distanceBetweenEdges < minDistance) { minDistance = distanceBetweenEdges; } } Range = Mathf.Max(1, Mathf.CeilToInt(minDistance / Board.DISTANCE_INTO_RANGE)); }
void OnCollisionEnter(Collision collisionInfo) { // Get instantiated mesh Mesh mesh = GetComponent <MeshFilter>().mesh; MeshCollider mc = GetComponent <MeshCollider>(); // get all the vertices Vector3[] vertices = mesh.vertices; //for each contact point foreach (var c in collisionInfo.contacts) { var impact = mc.ClosestPoint(c.point); //we look for the closest vertices int p = 0; while (p < vertices.Length) { //We get (into world coordinates) the current vertice Vector3 v = transform.TransformPoint(vertices[p]); //We compute the distance from the impact point to the vertex float dist = (impact - v).sqrMagnitude; //Collision deforms a zone around the collision (not only one point) //We check if we are in the "deformation" zone if (dist <= minDist) { //We clamp the distance (we don't want division by 0 or very small distances) dist = Clamp <float>(dist, 0.01f, minDist); Vector3 offset = -c.normal; //We compute the vertex offset offset.Scale(collisionInfo.relativeVelocity / 1000.0f); //we must scale the offset vertices[p] += offset / dist * 100; } p++; } } //we refresh the vertices and the normals mesh.vertices = vertices; mesh.RecalculateNormals(); }
public AuroraObject FirstPersistentObject(AuroraObject oPersistentObject, int nResidentObjectType, int nPersistentZone) { MeshCollider mc = oPersistentObject.GetComponent <MeshCollider>(); persistentObjects = new List <AuroraObject>(); foreach (List <AuroraObject> list in auroraObjects.Values) { foreach (AuroraObject obj in list) { Vector3 objPos = obj.transform.position; if (mc.ClosestPoint(objPos) == objPos) { // Object is inside collider persistentObjects.Add(obj); } } } return(NextPersistentObject()); }
void UpdateCollider() { if (meshCollider == null) { return; } GameObject camera = GameObject.FindGameObjectWithTag("MainCamera"); Vector3 closestPoint = meshCollider.ClosestPoint(camera.transform.position); debugCenter.transform.position = closestPoint; Debug.Log("Distance " + (closestPoint - camera.transform.position).magnitude); if ((closestPoint - camera.transform.position).magnitude < portalTriggerDistance) { SceneChanger sc = GameObject.FindGameObjectWithTag("PersistentScripts").GetComponentInChildren <SceneChanger>(); if (sc == null) { Debug.LogError("No scene changer could be found"); return; } sc.StartChange(); } }
public float GetBlendValue(Vector3 point, VolumeType type = VolumeType.directionIndepentant, bool useTrigger = false) { if (useTrigger) { if (!outerMeshCollider.bounds.Contains(point)) { return(0f); } } else { if (!outerMeshCollider.bounds.Contains(point)) { return(0f); } } Vector3 closesPoint = innerMeshCollider.ClosestPoint(point); if (closesPoint == point) { return(1f); } Vector3 rayDirection = (closesPoint - point).normalized; Ray ray = new Ray { origin = point - rayDirection * rayDistance, direction = rayDirection * rayDistance }; outerMeshCollider.Raycast(ray, out RaycastHit hit, rayDistance); float distanceToInner = (hit.point - closesPoint).magnitude; float distanceToPoint = (hit.point - point).magnitude; return(Mathf.Clamp01(distanceToPoint / distanceToInner)); }
/// <summary> /// Called after the camera has moved to a new position in the scene (we assume that the /// camera is moved during the regular update). We move our audio source accordingly. /// </summary> private void LateUpdate() { // child volumes do not have any execution logic themselves. if (IsChildVolume) { return; } // emergency - when the audio source no longer exists (user error), skip this. if (!audioSource) { return; } // there can only be one active audio listener in the scene. // we use this to automatically determine the position of the camera. // if we can't find an appropriate audio listener we stop here. if (!TryGetAudioListener()) { return; } // find the closest position to our mesh collider position. Vector3 audioListenerPosition = GetAudioListenerPosition(); Vector3 closestPosition = meshCollider.ClosestPoint(audioListenerPosition); float distance = Vector3.Distance(audioListenerPosition, closestPosition); // there can be floating point errors on the exact border of colliders that apparently cause values of 0,0,0. // if this happens we stop execution here to prevent audio glitches, it simply uses the previous values. if (transform.InverseTransformPoint(closestPosition) == Vector3.zero) { return; } // iterate through our child volumes and find an even closer position. for (int i = 0; i < childVolumes.Length; i++) { // emergency - when a child volume no longer exists (user error or editor undo issue), skip it. if (!childVolumes[i]) { continue; } Vector3 closestChildPosition = childVolumes[i].GetComponent <MeshCollider>().ClosestPoint(audioListenerPosition); float closestChildDistance = Vector3.Distance(audioListenerPosition, closestChildPosition); // there can be floating point errors on the exact border of colliders that apparently cause values of 0,0,0. // if this happens we stop execution here to prevent audio glitches, it simply uses the previous values. if (transform.InverseTransformPoint(closestChildPosition) == Vector3.zero) { return; } if (closestChildDistance < distance) { distance = closestChildDistance; closestPosition = closestChildPosition; } } // there can be floating point errors on the exact border of colliders that apparently cause values of 0,0,0. // if this happens we stop execution here to prevent audio glitches, it simply uses the previous values. if (transform.InverseTransformPoint(closestPosition) == Vector3.zero) { return; } // move the audio source to the closest point we just calculated. audioSource.transform.position = closestPosition; // when the audio listener enters the volume we switch to 2D. // this gives the illusion that the sound surrounds you completely. audioSource.spatialBlend = LerpInnerOuterRadius(spatialDistance2D, spatialDistance3D, distance); // game-only code that fades-in the volume to prevent a sudden burst of sound in built games. if (Application.isPlaying && !initializedAudioVolume) { // we wait until a frame has been rendered so we know there's no more loading times. if (!initializedGame) { initializedGame = true; audioVolumeFadeInTime = Time.time; } // fade in the audio source volume. audioSource.volume = Mathf.Lerp(audioSource.volume, desiredAudioVolume, Time.time - audioVolumeFadeInTime); if (Mathf.Approximately(audioSource.volume, desiredAudioVolume)) { audioSource.volume = desiredAudioVolume; initializedAudioVolume = true; } } }