private void GenerateMesh(Vector3[] points, Vector3[] nextSegmentPoints, Vector3 previousPoint, float heightOffset, Transform segment, Transform mesh, string name, Material material, int smoothnessAmount, RoadCreator roadCreator, PhysicMaterial physicMaterial, bool generate = true) { if (generate == true) { Vector3[] vertices = new Vector3[points.Length * 2]; Vector2[] uvs = new Vector2[vertices.Length]; int numTriangles = 2 * (points.Length - 1); int[] triangles = new int[numTriangles * 3]; int verticeIndex = 0; int triangleIndex = 0; float totalDistance = 0; float currentDistance = 0; for (int i = 1; i < points.Length; i++) { totalDistance += Vector3.Distance(points[i - 1], points[i]); } for (int i = 0; i < points.Length; i++) { Vector3 left = Misc.CalculateLeft(points, nextSegmentPoints, previousPoint, i); float correctedHeightOffset = heightOffset; if (i > 0) { currentDistance += Vector3.Distance(points[i - 1], points[i]); } float roadWidth = Mathf.Lerp(startRoadWidth, endRoadWidth, currentDistance / totalDistance); if (i == 0 && previousPoint != Misc.MaxVector3) { correctedHeightOffset = (previousPoint.y + heightOffset); } else if (i == points.Length - 1 && nextSegmentPoints != null && nextSegmentPoints.Length == 1) { correctedHeightOffset = (nextSegmentPoints[0].y + heightOffset); } if (name == "Road") { vertices[verticeIndex] = (points[i] + left * roadWidth + new Vector3(0, correctedHeightOffset, 0)) - segment.position; vertices[verticeIndex + 1] = (points[i] - left * roadWidth + new Vector3(0, correctedHeightOffset, 0)) - segment.position; } else if (name == "Left Shoulder") { vertices[verticeIndex] = (points[i] + left * roadWidth + left * leftShoulderWidth + new Vector3(0, correctedHeightOffset + leftShoulderHeightOffset, 0)) - segment.position; vertices[verticeIndex + 1] = (points[i] + left * roadWidth + new Vector3(0, correctedHeightOffset, 0)) - segment.position; } else if (name == "Right Shoulder") { vertices[verticeIndex] = (points[i] - left * roadWidth + new Vector3(0, correctedHeightOffset, 0)) - segment.position; vertices[verticeIndex + 1] = (points[i] - left * roadWidth - left * rightShoulderWidth + new Vector3(0, correctedHeightOffset + rightShoulderHeightOffset, 0)) - segment.position; } if (terrainOption == TerrainOption.deform) { DeformTerrain(vertices[verticeIndex] + segment.transform.position, roadCreator.globalSettings.roadLayer); DeformTerrain(vertices[verticeIndex + 1] + segment.transform.position, roadCreator.globalSettings.roadLayer); } if (i < points.Length - 1) { triangles[triangleIndex] = verticeIndex; triangles[triangleIndex + 1] = (verticeIndex + 2) % vertices.Length; triangles[triangleIndex + 2] = verticeIndex + 1; triangles[triangleIndex + 3] = verticeIndex + 1; triangles[triangleIndex + 4] = (verticeIndex + 2) % vertices.Length; triangles[triangleIndex + 5] = (verticeIndex + 3) % vertices.Length; } verticeIndex += 2; triangleIndex += 6; } // Fix texture overlapping with intersections if (nextSegmentPoints != null && nextSegmentPoints.Length == 1) { vertices = fixVertices(0, vertices, (nextSegmentPoints[0] - points[points.Length - 1]).normalized, segment, roadCreator); vertices = fixVertices(-1, vertices, (nextSegmentPoints[0] - points[points.Length - 1]).normalized, segment, roadCreator); } if (previousPoint != Misc.MaxVector3) { vertices = fixVerticesBeggining(0, vertices, (points[0] - previousPoint).normalized, segment, roadCreator); vertices = fixVerticesBeggining(1, vertices, (points[0] - previousPoint).normalized, segment, roadCreator); } if (smoothnessAmount > 0) { vertices = fixVerticesBeggining(vertices.Length - 3 - (2 * smoothnessAmount), vertices, (points[points.Length - smoothnessAmount] - points[points.Length - smoothnessAmount - 2]).normalized, segment, roadCreator); vertices = fixVerticesBeggining(vertices.Length - 4 - (2 * smoothnessAmount), vertices, (points[points.Length - smoothnessAmount] - points[points.Length - smoothnessAmount - 2]).normalized, segment, roadCreator); } Mesh generatedMesh = new Mesh(); generatedMesh.vertices = vertices; generatedMesh.triangles = triangles; generatedMesh.uv = uvs; generatedMesh = GenerateUvs(generatedMesh); mesh.GetComponent<MeshFilter>().sharedMesh = generatedMesh; mesh.GetComponent<MeshCollider>().sharedMesh = generatedMesh; mesh.GetComponent<MeshCollider>().sharedMaterial = physicMaterial; mesh.GetComponent<MeshRenderer>().sharedMaterial = material; } else { mesh.GetComponent<MeshFilter>().sharedMesh = null; mesh.GetComponent<MeshCollider>().sharedMesh = null; } }
/// <summary> /// Indexer to return a <see cref="MovementEventLibrary"/> based on a PhysicMaterial /// </summary> public MovementEventLibrary this[PhysicMaterial physicMaterial] { get { return(m_ZonesDefinition[physicMaterial]); } }
private void SetupPhysicMaterial(PhysicMaterial material, Creature creature) { material.dynamicFriction = creature.DynamicFriction; material.staticFriction = creature.StaticFriction; material.bounciness = creature.Bounciness; }
/// <summary> /// Builds the Third Person Controller character. /// </summary> public static void BuildCharacter(GameObject character, bool aiAgent, bool isNetworked, RigidbodyCharacterController.MovementType movementType, RuntimeAnimatorController animatorController, PhysicMaterial maxFrictionMaterial, PhysicMaterial frictionlessMaterial, Transform[] itemTransforms, Transform[] feet) { // Set the internal variables. m_Character = character; m_AIAgent = aiAgent; #if !(UNITY_4_6 || UNITY_4_7 || UNITY_5_0) m_IsNetworked = isNetworked; #endif m_MovementType = movementType; m_AnimatorController = animatorController; m_MaxFrictionMaterial = maxFrictionMaterial; m_FrictionlessMaterial = frictionlessMaterial; // Build the character. BuildStandardComponents(feet); for (int i = 0; i < itemTransforms.Length; ++i) { BuildItemHands(itemTransforms[i]); } #if !(UNITY_4_6 || UNITY_4_7 || UNITY_5_0) if (m_IsNetworked) { BuildNetwork(); } #endif }
public static MeshInstanceKey GenerateKey(RenderSurfaceType renderSurfaceType, Material renderMaterial, PhysicMaterial physicsMaterial) { var realRenderMaterial = renderMaterial; if (renderSurfaceType != RenderSurfaceType.Normal) { realRenderMaterial = null; } return(new MeshInstanceKey(renderSurfaceType, (!realRenderMaterial) ? 1 : realRenderMaterial.GetInstanceID(), (!physicsMaterial) ? 1 : physicsMaterial.GetInstanceID())); }
/// <summary> /// Climbstep property constructor. /// </summary> /// <param name="physicMaterial">Climb physic material.</param> /// <param name="sounds">Climb step sounds.</param> public ClimbstepProperty(PhysicMaterial physicMaterial, AudioClip[] sounds) { this.physicMaterial = physicMaterial; this.sounds = sounds; }
public override void OnInspectorGUI() { CSGModel csgModel = (CSGModel)target; // Ensure the default material is set csgModel.EnsureDefaultMaterialSet(); DrawDefaultInspector(); this.serializedObject.Update(); using (NamedVerticalScope scope = new NamedVerticalScope("Build Settings")) { scope.WikiLink = "Build-Settings"; EditorGUIUtility.fieldWidth = 0; EditorGUIUtility.labelWidth = 160; EditorGUILayout.PropertyField(generateCollisionMeshesProperty, new GUIContent("Generate Collision Meshes")); EditorGUILayout.PropertyField(generateTangentsProperty, new GUIContent("Generate Tangents")); EditorGUILayout.PropertyField(generateLightmapUVsProperty, new GUIContent("Generate Lightmap UVs")); EditorGUIUtility.labelWidth = 125; GUI.enabled = generateLightmapUVsProperty.boolValue; EditorGUI.indentLevel = 1; EditorGUILayout.PropertyField(unwrapAngleErrorProperty, new GUIContent("Unwrap Angle Error")); EditorGUILayout.PropertyField(unwrapAreaErrorProperty, new GUIContent("Unwrap Area Error")); EditorGUILayout.PropertyField(unwrapHardAngleProperty, new GUIContent("Unwrap Hard Angle")); EditorGUILayout.PropertyField(unwrapPackMarginProperty, new GUIContent("Unwrap Pack Margin")); EditorGUI.indentLevel = 0; EditorGUIUtility.labelWidth = 0; GUI.enabled = true; EditorGUILayout.PropertyField(shadowCastingModeProperty, new GUIContent("Shadow Casting Mode")); EditorGUILayout.PropertyField(reflectionProbeUsageProperty, new GUIContent("Reflection Probes")); // Experimental build settings to enable features that are not yet completely stable GUILayout.Label("Experimental", EditorStyles.boldLabel); EditorGUI.indentLevel = 1; EditorGUILayout.PropertyField(optimizeGeometryProperty, new GUIContent("Optimize Geometry")); EditorGUILayout.PropertyField(saveMeshesAsAssetsProperty, new GUIContent("Save Meshes As Assets")); EditorGUI.indentLevel = 0; } using (new NamedVerticalScope("Default Material")) { PhysicMaterial lastPhysicsMaterial = defaultPhysicsMaterialProperty.objectReferenceValue as PhysicMaterial; EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(defaultPhysicsMaterialProperty, new GUIContent("Default Physics Material")); if (EditorGUI.EndChangeCheck()) { PhysicMaterial newPhysicsMaterial = defaultPhysicsMaterialProperty.objectReferenceValue as PhysicMaterial; // Update the built mesh colliders that use the old material UpdatePhysicsMaterial(lastPhysicsMaterial, newPhysicsMaterial); } // Track the last visual material, so that if the user changes it we can update built renderers instantly Material lastVisualMaterial = defaultVisualMaterialProperty.objectReferenceValue as Material; EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(defaultVisualMaterialProperty, new GUIContent("Default Visual Material")); if (EditorGUI.EndChangeCheck()) { // User has changed the material, so grab the new material Material newVisualMaterial = defaultVisualMaterialProperty.objectReferenceValue as Material; // EnsureDefaultMaterialSet hasn't had a chance to run yet, so make sure we have a solid material reference if (newVisualMaterial == null) { newVisualMaterial = csgModel.GetDefaultFallbackMaterial(); defaultVisualMaterialProperty.objectReferenceValue = newVisualMaterial; } // Update the built renderers that use the old material, also update source brush polygons UpdateVisualMaterial(lastVisualMaterial, newVisualMaterial); // Update the last build's default material because we don't need to build again lastBuildDefaultVisualMaterialProperty.objectReferenceValue = newVisualMaterial; } EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Lit Texture (No Tint)")) { Material newVisualMaterial = AssetDatabase.LoadMainAssetAtPath(CSGModel.GetSabreCSGPath() + "Resources/Materials/Default_Map.mat") as Material; SetVisualMaterial(lastVisualMaterial, newVisualMaterial); } if (GUILayout.Button("Lit Vertex Tint")) { Material newVisualMaterial = AssetDatabase.LoadMainAssetAtPath(CSGModel.GetSabreCSGPath() + "Resources/Materials/Default_LitWithTint.mat") as Material; SetVisualMaterial(lastVisualMaterial, newVisualMaterial); } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Unlit Vertex Color")) { Material newVisualMaterial = AssetDatabase.LoadMainAssetAtPath(CSGModel.GetSabreCSGPath() + "Resources/Materials/Default_VertexColor.mat") as Material; SetVisualMaterial(lastVisualMaterial, newVisualMaterial); } if (GUILayout.Button("Lit Vertex Color")) { Material newVisualMaterial = AssetDatabase.LoadMainAssetAtPath(CSGModel.GetSabreCSGPath() + "Resources/Materials/Default_VertexColorLit.mat") as Material; SetVisualMaterial(lastVisualMaterial, newVisualMaterial); } EditorGUILayout.EndHorizontal(); } using (NamedVerticalScope scope = new NamedVerticalScope("Export")) { scope.WikiLink = "Build-Settings#exporting-obj-files"; if (GUILayout.Button("Export All To OBJ")) { csgModel.ExportOBJ(false); } if (GUILayout.Button("Export Selected To OBJ")) { csgModel.ExportOBJ(true); } } using (new NamedVerticalScope("Import")) { GuiLayoutBeginImporterSection(SabreCSGResources.ImporterUnrealGoldTexture, "Unreal Gold Importer", "Henry de Jongh"); importerUnrealGoldScale = EditorGUILayout.IntField("Scale", importerUnrealGoldScale); if (importerUnrealGoldScale < 1) { importerUnrealGoldScale = 1; } EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Import Unreal Gold Map (*.t3d)")) { try { string path = EditorUtility.OpenFilePanel("Import Unreal Gold Map", "", "t3d"); if (path.Length != 0) { EditorUtility.DisplayProgressBar("SabreCSG: Importing Unreal Gold Map", "Parsing Unreal Text File (*.t3d)...", 0.0f); var importer = new Importers.UnrealGold.T3dImporter(); var map = importer.Import(path); Importers.UnrealGold.T3dMapConverter.Import(csgModel, map, importerUnrealGoldScale); } } catch (Exception ex) { EditorUtility.ClearProgressBar(); EditorUtility.DisplayDialog("Unreal Gold Map Import", "An exception occurred while importing the map:\r\n" + ex.Message, "Ohno!"); } } if (GUILayout.Button("?", GUILayout.Width(16))) { EditorUtility.DisplayDialog("Unreal Gold Importer", "This importer was created using Unreal Gold 227 (http://oldunreal.com/).\n\nImportant Notes:\n* It will try to find the materials in your project automatically. First it looks for the full name like 'PlayrShp.Ceiling.Hullwk' then the last word 'Hullwk'. The latter option could cause some false positives, try creating a material with the full name if this happens.\n* This importer requires you to place a massive additive cube around your whole level as Unreal Editor uses the subtractive workflow.\n\nKnown Issues:\n* Concave brushes may cause corruptions.", "Okay"); } EditorGUILayout.EndHorizontal(); GuiLayoutEndImporterSection(); // EditorGUILayout.Space(); // GuiLayoutBeginImporterSection(SabreCSGResources.ImporterValveMapFormat2006Texture, "Source Engine 2006 Importer", "Henry de Jongh"); EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Import Source Engine Map (*.vmf)")) { try { string path = EditorUtility.OpenFilePanel("Import Source Engine Map", "", "vmf"); if (path.Length != 0) { EditorUtility.DisplayProgressBar("SabreCSG: Importing Source Engine Map", "Parsing Valve Map Format File (*.vmf)...", 0.0f); var importer = new Importers.ValveMapFormat2006.VmfImporter(); var map = importer.Import(path); Importers.ValveMapFormat2006.VmfWorldConverter.Import(csgModel, map); } } catch (Exception ex) { EditorUtility.ClearProgressBar(); EditorUtility.DisplayDialog("Source Engine Map Import", "An exception occurred while importing the map:\r\n" + ex.Message, "Ohno!"); } } if (GUILayout.Button("?", GUILayout.Width(16))) { EditorUtility.DisplayDialog("Source Engine 2006 Importer", "This importer was created using Source SDK maps and Hammer 4.1.\n\nImportant Notes:\n* It will try to find the materials in your project automatically. First it looks for the full name with forward slashes '/' replaced by periods '.' like 'BRICK.BRICKFLOOR001A' then the last word 'BRICKFLOOR001A'. The latter option could cause some false positives, try creating a material with the full name if this happens.", "Okay"); } EditorGUILayout.EndHorizontal(); GuiLayoutEndImporterSection(); // EditorGUILayout.Space(); // GuiLayoutBeginImporterSection(SabreCSGResources.ImporterQuake1Texture, "Quake 1 Importer", "Jasmine Mickle"); EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Import Quake 1 Map (*.map)")) { try { string path = EditorUtility.OpenFilePanel("Import Quake 1 Map", "", "map"); if (path.Length != 0) { EditorUtility.DisplayProgressBar("SabreCSG: Importing Quake 1 Map", "Parsing Quake 1 Map File (*.map)...", 0.0f); var importer = new Importers.Quake1.MapImporter(); var map = importer.Import(path); Importers.Quake1.MapWorldConverter.Import(csgModel, map); } } catch (Exception ex) { EditorUtility.ClearProgressBar(); EditorUtility.DisplayDialog("Quake 1 Map Import", "An exception occurred while importing the map:\r\n" + ex.Message, "Ohno!"); } } if (GUILayout.Button("?", GUILayout.Width(16))) { EditorUtility.DisplayDialog("Quake 1 Importer", "This importer (parser by Henry de Jongh) was created using Trenchbroom 2.0.6.\n\nImportant Notes:\n* It will try to find the materials in your project automatically. It will replace any leading '*' with '#' like '#teleport'.\n\nKnown Issues:\n* 45 degree angled walls may not have correct UV texture coordinates (are not correctly picking the dominant axis because there are two).\n* Negative vertex coordinates may not have correct UV texture coordinates (feel free to contribute improved UV mapping code if you know how it works, we had to guess most of the maths).", "Okay"); } EditorGUILayout.EndHorizontal(); GuiLayoutEndImporterSection(); } using (new NamedVerticalScope("Stats")) { BuildMetrics buildMetrics = csgModel.BuildMetrics; GUILayout.Label("Brushes: " + csgModel.BrushCount); GUILayout.Label("Vertices: " + buildMetrics.TotalVertices); GUILayout.Label("Triangles: " + buildMetrics.TotalTriangles); GUILayout.Label("Meshes: " + buildMetrics.TotalMeshes); GUILayout.Label("Build Time: " + buildMetrics.BuildTime.ToString()); } // Make sure any serialize property changes are committed to the underlying Unity Object bool anyApplied = this.serializedObject.ApplyModifiedProperties(); if (anyApplied) { // Make sure that nothing else is included in the Undo, as an immediate rebuild may take place and // we don't want the rebuild's lastBuildSettings being included in the undo step Undo.IncrementCurrentGroup(); } }
public bool UpdateCollider(CGColliderEnum mode, bool convex, PhysicMaterial material) { if (Collider == null) { switch (mode) { case CGColliderEnum.Mesh: if (canAddMeshCollider(Filter.sharedMesh.bounds)) { var mc = gameObject.AddComponent <MeshCollider>(); mc.convex = convex; mCollider = mc; } break; case CGColliderEnum.Box: gameObject.AddComponent <BoxCollider>(); break; case CGColliderEnum.Sphere: gameObject.AddComponent <SphereCollider>(); break; } } if (Collider != null) { switch (mode) { case CGColliderEnum.Mesh: var mc = Collider as MeshCollider; if (mc != null) { mc.sharedMesh = null; if (!canAddMeshCollider(Filter.sharedMesh.bounds)) { return(false); } try { mc.sharedMesh = Filter.sharedMesh; } catch { return(false); } } break; case CGColliderEnum.Box: var bc = Collider as BoxCollider; if (bc != null) { bc.center = Filter.sharedMesh.bounds.center; bc.size = Filter.sharedMesh.bounds.size; } break; case CGColliderEnum.Sphere: var sc = Collider as SphereCollider; if (sc != null) { sc.center = Filter.sharedMesh.bounds.center; sc.radius = Filter.sharedMesh.bounds.extents.magnitude; } break; } Collider.material = material; } return(true); }
public ColliderKey(PhysicMaterial material, int layer) { this.material = material; this.layer = layer; }
public WXPhysicsMaterial(PhysicMaterial mat) { this.material = mat; this.path = wxFileUtil.cleanIllegalChar(AssetDatabase.GetAssetPath(mat.GetInstanceID()), false); _fileName = this.path.Split('.')[0]; }
public void OnFixedUpdate(Vector3 torsoFeedback) { stepToAlignOverride -= Time.fixedDeltaTime; float num = (human.state != HumanState.Slide) ? ballFriction : 0f; if (num != ballMaterial.staticFriction) { PhysicMaterial physicMaterial = ballMaterial; float num2 = num; ballMaterial.dynamicFriction = num2; physicMaterial.staticFriction = num2; PhysicMaterial physicMaterial2 = footMaterial; num2 = ((human.state != HumanState.Slide) ? footFriction : 0f); footMaterial.dynamicFriction = num2; physicMaterial2.staticFriction = num2; ragdoll.partBall.collider.sharedMaterial = ballMaterial; ragdoll.partLeftFoot.collider.sharedMaterial = footMaterial; ragdoll.partRightFoot.collider.sharedMaterial = footMaterial; } switch (human.state) { case HumanState.Idle: { int num3 = (!human.controls.leftGrab && !human.controls.rightGrab) ? 90 : 75; if (Vector2.Angle(new Vector2(0f, 1f).Rotate((0f - human.controls.targetYawAngle) * ((float)Math.PI / 180f)), ragdoll.partHips.transform.forward.To2D()) > (float)num3) { stepToAlignOverride = stepToAlignOverrideDuration; } if (stepToAlignOverride > 0f) { RunAnimation(torsoFeedback, 0.5f); } else { StandAnimation(torsoFeedback, 1f); } break; } case HumanState.Walk: RunAnimation(torsoFeedback, 1f); break; case HumanState.Climb: if (human.controls.walkSpeed > 0f) { RunAnimation(torsoFeedback, 0f); } else { StandAnimation(torsoFeedback, 0f); } break; case HumanState.Jump: JumpAnimation(torsoFeedback); break; case HumanState.Slide: StandAnimation(torsoFeedback, 1f); break; case HumanState.Fall: NoAnimation(torsoFeedback); break; case HumanState.FreeFall: NoAnimation(torsoFeedback); break; case HumanState.Unconscious: NoAnimation(torsoFeedback); break; case HumanState.Dead: NoAnimation(torsoFeedback); break; case HumanState.Spawning: NoAnimation(torsoFeedback); break; } }
//public virtual void Init() { } //this is used by the car player controller to add the input manager and the speedo public override void Awake() { base.Awake(); SkidPrefab = Resources.Load("Prefabs/SkidmarkPrefab"); SkidAudioSource = GetComponent <AudioSource>(); Transform Eng = transform.Find("Engine"); EngineAudioSource = transform.Find("Engine").GetComponent <AudioSource>(); CoughAudioSource = Eng.Find("Cough").GetComponent <AudioSource>(); ClutchAudioSource = Eng.Find("ClutchDown").GetComponent <AudioSource>(); IdleAudioSource = Eng.Find("Idle").GetComponent <AudioSource>(); EngineAudioSource.mute = true; CoughAudioSource.mute = true; IdleAudioSource.mute = true; FLWheel = transform.Find("car/FLWheel").gameObject; FRWheel = transform.Find("car/FRWheel").gameObject; WasRuttingFL = false; WasRuttingFR = false; RutMatrl = (Material)Resources.Load("Prefabs/Materials/WheelRutGrey"); SkidMatrl = (Material)Resources.Load("Prefabs/Materials/SkidMark"); psSprayL = transform.Find("WheelColliders/WCFL/SprayFL").GetComponent <ParticleSystem>(); psSprayR = transform.Find("WheelColliders/WCFR/SprayFR").GetComponent <ParticleSystem>(); psDustL = transform.Find("WheelColliders/WCFL/DustFL").GetComponent <ParticleSystem>(); psDustR = transform.Find("WheelColliders/WCFR/DustFR").GetComponent <ParticleSystem>(); peSprayL = psSprayL.emission; peSprayR = psSprayR.emission; peDustL = psDustL.emission; peDustR = psDustR.emission; pmSprayL = psSprayL.main; pmSprayR = psSprayR.main; pmDustL = psDustL.main; pmDustR = psDustR.main; try { _fLRimRenderer = transform.Find("car/FLWheel/FLRim").GetComponent <Renderer>(); _fRRimRenderer = transform.Find("car/FRWheel/FRRim").GetComponent <Renderer>(); _rLRimRenderer = transform.Find("car/RLWheel/RLRim").GetComponent <Renderer>(); _rRRimRenderer = transform.Find("car/RRWheel/RRRim").GetComponent <Renderer>(); _fRRimSpinRenderer = transform.Find("car/FRWheel/FRRimSpin").GetComponent <Renderer>(); _rLRimSpinRenderer = transform.Find("car/RLWheel/RLRimSpin").GetComponent <Renderer>(); _fLRimSpinRenderer = transform.Find("car/FLWheel/FLRimSpin").GetComponent <Renderer>(); _rRRimSpinRenderer = transform.Find("car/RLWheel/RRRimSpin").GetComponent <Renderer>(); } catch { _rimSpin = false; } StickyCarBodyPhysicsMaterial = (PhysicMaterial)Resources.Load("PhysicMaterials/StickyCarBodyPhysicsMaterial"); CarBodyPhysicsMaterial = (PhysicMaterial)Resources.Load("PhysicMaterials/CarBodyPhysicsMaterial"); RLWheel = transform.Find("car/RLWheel").gameObject; RRWheel = transform.Find("car/RRWheel").gameObject; WCFL = transform.Find("WheelColliders/WCFL").GetComponent <WheelController>(); WCFR = transform.Find("WheelColliders/WCFR").GetComponent <WheelController>(); WCRL = transform.Find("WheelColliders/WCRL").GetComponent <WheelController>(); WCRR = transform.Find("WheelColliders/WCRR").GetComponent <WheelController>(); _rearslipCoeff = WCRR.sideFriction.forceCoefficient; _rb = GetComponent <Rigidbody>(); _rb.centerOfMass = new Vector3(0, 0.65f, 0.4f); SkidThresh = 0.6f; motorForce = 1800f; _maxBrakeForce = 1400f; steerForce = 25f; AntiRollForce = 160f; Keyframe[] kfs; kfs = new Keyframe[4] { new Keyframe(0f, 0f, 2.3f, 2.3f), new Keyframe(0.3f, 1.4f, 0f, 0f), new Keyframe(0.4f, 0.9f, 0f, 0f), new Keyframe(1f, 1.2f, 0f, 0f) }; frontFrictTarmac = new AnimationCurve(kfs); kfs = new Keyframe[4] { new Keyframe(0f, 0f, 2.3f, 2.3f), new Keyframe(0.2f, 1.2f, 0f, 0f), new Keyframe(0.3f, 0.7f, 0f, 0f), new Keyframe(2f, 0.7f, 0f, 0f) }; rearFrictTarmac = new AnimationCurve(kfs); kfs = new Keyframe[4] { new Keyframe(0f, 0f, 2.0f, 2.0f), new Keyframe(0.2f, 0.7f, 0f, 0f), new Keyframe(0.3f, 0.5f, 0f, 0f), new Keyframe(1f, 0.6f, 0f, 0f) }; frontFrictDirtyRoad = new AnimationCurve(kfs); kfs = new Keyframe[4] { new Keyframe(0f, 0f, 2.0f, 2.0f), new Keyframe(0.15f, 0.7f, 0f, 0f), new Keyframe(0.2f, 0.5f, 0f, 0f), new Keyframe(1f, 0.5f, 0f, 0f) }; rearFrictDirtyRoad = new AnimationCurve(kfs); kfs = new Keyframe[4] { new Keyframe(0f, 0f, 2.0f, 2.0f), new Keyframe(0.2f, 0.7f, 0f, 0f), new Keyframe(0.3f, 0.3f, 0f, 0f), new Keyframe(1f, 1.1f, 0f, 0f) }; frontFrictDirt = new AnimationCurve(kfs); kfs = new Keyframe[4] { new Keyframe(0f, 0f, 2.1f, 2.1f), new Keyframe(0.15f, 0.5f, 0f, 0f), new Keyframe(0.2f, 0.3f, 0f, 0f), new Keyframe(1f, 0.4f, 0f, 0f) }; rearFrictDirt = new AnimationCurve(kfs); //Used for testing /* * WCFL.forwardFriction.frictionCurve = frontFrictDirtyRoad; * WCFR.forwardFriction.frictionCurve = frontFrictDirtyRoad; * WCRL.forwardFriction.frictionCurve = rearFrictDirtyRoad; * WCRR.forwardFriction.frictionCurve = rearFrictDirtyRoad; * WCFL.fFriction.slipCoefficient = 1.1f; * WCFR.fFriction.slipCoefficient = 1.1f; */ }
private void Awake() { // Create frictionless physmaterial for walls var material = new PhysicMaterial("Frictionless"); material.staticFriction = 0f; material.dynamicFriction = 0f; material.frictionCombine = PhysicMaterialCombine.Minimum; material.bounceCombine = PhysicMaterialCombine.Minimum; material.bounciness = 0f; var surfaces = new BoxCollider[6]; for (var i = 0; i < 6; i++) { var obj = new GameObject(); obj.transform.SetParent(transform, false); var collider = obj.AddComponent <BoxCollider>(); collider.sharedMaterial = material; surfaces[i] = collider; } var size = _thickness / transform.localScale.magnitude; var offset = 0.5f + size / 2f; // Floor surfaces[0].size = new Vector3(1f, size, 1f); surfaces[0].transform.localPosition = new Vector3(0f, -offset, 0f); surfaces[0].name = "Floor"; // Ceiling surfaces[1].size = new Vector3(1f, size, 1f); surfaces[1].transform.localPosition = new Vector3(0f, offset, 0f); surfaces[1].name = "Ceiling"; // Wall Z- surfaces[2].size = new Vector3(1f, 1f, size); surfaces[2].transform.localPosition = new Vector3(0f, 0f, -offset); surfaces[2].name = "Wall Z-"; // Wall Z+ surfaces[3].size = new Vector3(1f, 1f, size); surfaces[3].transform.localPosition = new Vector3(0f, 0f, offset); surfaces[3].name = "Wall Z+"; // Wall X- surfaces[4].size = new Vector3(size, 1f, 1f); surfaces[4].transform.localPosition = new Vector3(-offset, 0f, 0f); surfaces[4].name = "Wall X-"; // Wall X+ surfaces[5].size = new Vector3(size, 1f, 1f); surfaces[5].transform.localPosition = new Vector3(offset, 0f, 0f); surfaces[5].name = "Wall X+"; if (_useLayer) { for (var i = 0; i < surfaces.Length; i++) { surfaces[i].gameObject.layer = gameObject.layer; } } }
void OnCollisionEnter(Collision collisionInfo) { physicMaterial = collisionInfo.collider.sharedMaterial; }
static IntPtr CreateMaterial(PhysicMaterial material) { return(createMaterial(material.staticFriction, material.dynamicFriction, material.bounciness)); }
public ColliderKey(Collider collider) { this.material = collider.get_sharedMaterial(); this.layer = ((Component)collider).get_gameObject().get_layer(); }
void Start() { base.Init(); m_Capsule = GetComponent <CapsuleCollider> (); if (m_Capsule != null) { m_CapsuleHeight = m_Capsule.height * transform.lossyScale.y; m_CapsuleCenter = m_Capsule.center; if (Application.isPlaying && !useThirdPartyController && m_Capsule.sharedMaterial == null) { // ZeroFriction physic material is used to make easier climbing - however it's only used by this controller so if you're using other controllers do not touch the collider PhysicMaterial mat = Resources.Load <PhysicMaterial> ("VoxelPlay/Materials/ZeroFriction"); m_Capsule.sharedMaterial = mat; } } m_Rigidbody = GetComponent <Rigidbody> (); if (m_Rigidbody != null) { m_Rigidbody.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ; } m_OrigGroundCheckDistance = m_GroundCheckDistance; m_Animator = GetComponentInChildren <Animator> (); // Try to assign our designed camera if (m_Camera == null) { m_Camera = Camera.main; } if (env != null && m_Camera != null) { env.cameraMain = m_Camera; } // If no camera assigned, get Voxel Play Environment available camera if (m_Camera == null) { m_Camera = env.cameraMain; } if (env == null || !env.applicationIsPlaying) { return; } ToggleCharacterController(false); // Position character on ground if (!env.saveFileIsLoaded) { if (startOnFlat && env.world != null) { float minAltitude = env.world.terrainGenerator.maxHeight; Vector3 flatPos = transform.position; Vector3 randomPos; for (int k = 0; k < startOnFlatIterations; k++) { randomPos = Random.insideUnitSphere * 1000; float alt = env.GetTerrainHeight(randomPos); if (alt < minAltitude && alt >= env.waterLevel + 1) { minAltitude = alt; randomPos.y = alt + characterHeight * 0.5f + 0.1f; flatPos = randomPos; } } transform.position = flatPos; } } input = env.input; cameraX = 0; cameraY = 35; UpdateCamera(false); InitCrosshair(); if (!env.initialized) { env.OnInitialized += () => WaitForCurrentChunk(); } else { WaitForCurrentChunk(); } }
public ColliderKey(ColliderBatch batch) { this.material = ((Collider)batch.BatchCollider).get_sharedMaterial(); this.layer = ((Component)batch.BatchCollider).get_gameObject().get_layer(); }
/// <summary> /// Set climb physic material. /// </summary> /// <param name="physicMaterial">Climb physic material</param> public void SetPhysicMaterial(PhysicMaterial physicMaterial) { this.physicMaterial = physicMaterial; }
void Start() { colliding = false; grounded = false; // Second substitution, because RUISKinectAndMecanimCombiner might have already erased the original one and re-created it skeletonController = gameObject.GetComponentInChildren <RUISSkeletonController>(); if (skeletonController) { bodyParts.Add(skeletonController.leftFoot); bodyParts.Add(skeletonController.rightFoot); kinectPlayerId = skeletonController.playerId; bodyTrackingDeviceID = skeletonController.bodyTrackingDeviceID; } else { Debug.LogError("RUISCharacterController script in game object '" + gameObject.name + "' did not find RUISSkeletonController component from it's child objects!"); } coordinateSystem = FindObjectOfType(typeof(RUISCoordinateSystem)) as RUISCoordinateSystem; if (stabilizingCollider) { colliderComponent = stabilizingCollider.gameObject.GetComponent <Collider>(); if (colliderComponent) { if (characterPivotType == CharacterPivotType.KinectHead || characterPivotType == CharacterPivotType.KinectTorso) { if (coordinateSystem && inputManager.enableKinect && !coordinateSystem.setKinectOriginToFloor) { Debug.LogWarning("It is best to enable 'setKinectOriginToFloor' from RUISCoordinateSystem " + "when using Kinect and RUISCharacterController script."); } } if (colliderComponent.material) { originalMaterial = colliderComponent.material; } else { colliderComponent.material = new PhysicMaterial(); originalMaterial = colliderComponent.material; } if (dynamicMaterial == null) { dynamicMaterial = new PhysicMaterial(); /*dynamicMaterial.dynamicFriction = 0; * dynamicMaterial.staticFriction = 0; * dynamicMaterial.frictionCombine = PhysicMaterialCombine.Minimum; * try * { * if(colliderComponent.material) * { * dynamicMaterial.bounceCombine = originalMaterial.bounceCombine; * dynamicMaterial.bounciness = originalMaterial.bounciness; * dynamicMaterial.staticFriction2 = originalMaterial.staticFriction2; * dynamicMaterial.dynamicFriction2 = originalMaterial.dynamicFriction2; * dynamicMaterial.frictionDirection2 = originalMaterial.frictionDirection2; * } * } * catch(UnityException e) * { * * }*/ } } } if ((characterPivotType == CharacterPivotType.KinectHead || characterPivotType == CharacterPivotType.KinectTorso) && (skeletonController && skeletonController.playerId != kinectPlayerId)) { Debug.LogError("The 'Kinect Player Id' variable in RUISCharacterController script in gameObject '" + gameObject.name + "is different from the Kinect Player Id of the RUISSkeletonController script (located in child " + "object '" + skeletonController.gameObject.name + "). Make sure that these two values are " + "the same."); } //#if UNITY_EDITOR //if(UnityEditorInternal.InternalEditorUtility.HasPro()) //#endif { try { bool isRiftConnected = false; if (OVRManager.display != null) { isRiftConnected = OVRManager.display.isPresent; } if (OVRManager.capiHmd != null) { ovrHmdVersion = OVRManager.capiHmd.GetDesc().Type; } if (useOculusPositionalTracking && ovrHmdVersion == Ovr.HmdType.DK1 || ovrHmdVersion == Ovr.HmdType.DKHD || ovrHmdVersion == Ovr.HmdType.None) { Debug.LogError("Can't use Oculus Rift's tracked position as a pivot with Oculus Rift " + ovrHmdVersion); useOculusPositionalTracking = false; } if (useOculusPositionalTracking && !isRiftConnected) { Debug.LogError("Can't use Oculus Rift's tracked position as a pivot because Oculus Rift is not connected."); useOculusPositionalTracking = false; } } catch (UnityException e) { useOculusPositionalTracking = false; Debug.LogError(e); } } if (GetComponentInChildren <RUISKinectAndMecanimCombiner>()) { kinectAndMecanimCombinerExists = true; } previousPosition = transform.position; }
public static void BuildHumanoidCharacter(GameObject character, bool aiAgent, bool isNetworked, RigidbodyCharacterController.MovementType movementType, RuntimeAnimatorController animatorController, PhysicMaterial maxFrictionMaterial, PhysicMaterial frictionlessMaterial) { var animator = character.GetComponent <Animator>(); var hands = new Transform[] { animator.GetBoneTransform(HumanBodyBones.LeftHand), animator.GetBoneTransform(HumanBodyBones.RightHand) }; var feet = new Transform[] { animator.GetBoneTransform(HumanBodyBones.LeftFoot), animator.GetBoneTransform(HumanBodyBones.RightFoot) }; BuildCharacter(character, aiAgent, isNetworked, movementType, animatorController, maxFrictionMaterial, frictionlessMaterial, hands, feet); }
// Initializing constructor public PhysicsMaterialParser(PhysicMaterial material = null) { this.material = material; }
public virtual void EditMode__CreateCollider() { // Revert to runtime behaviour when the game is running if (Application.isPlaying) { UpdateCollider(); return; } tk2dSpriteDefinition sprite = collectionInst.spriteDefinitions[_spriteId]; if (sprite.colliderType == tk2dSpriteDefinition.ColliderType.Unset) { return; } PhysicMaterial physicsMaterial = GetComponent <Collider>()?GetComponent <Collider>().sharedMaterial:null; bool isTrigger = GetComponent <Collider>()?GetComponent <Collider>().isTrigger:false; #if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) PhysicsMaterial2D physicsMaterial2D = GetComponent <Collider2D>()?GetComponent <Collider2D>().sharedMaterial:null; if (GetComponent <Collider2D>() != null) { isTrigger = GetComponent <Collider2D>().isTrigger; } #endif boxCollider = gameObject.GetComponent <BoxCollider>(); meshCollider = gameObject.GetComponent <MeshCollider>(); #if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) boxCollider2D = gameObject.GetComponent <BoxCollider2D>(); edgeCollider2D.Clear(); edgeCollider2D.AddRange(gameObject.GetComponents <EdgeCollider2D>()); polygonCollider2D.Clear(); polygonCollider2D.AddRange(gameObject.GetComponents <PolygonCollider2D>()); #endif // Sanitize colliders - get rid of unused / incorrect ones in editor if (sprite.physicsEngine == tk2dSpriteDefinition.PhysicsEngine.Physics3D) { // Delete colliders from wrong physics engine #if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) if (boxCollider2D != null) { DestroyImmediate(boxCollider2D, true); } foreach (PolygonCollider2D c2d in polygonCollider2D) { if (c2d != null) { DestroyImmediate(c2d, true); } } polygonCollider2D.Clear(); foreach (EdgeCollider2D e2d in edgeCollider2D) { if (e2d != null) { DestroyImmediate(e2d, true); } } edgeCollider2D.Clear(); #endif // Delete mismatched collider if ((NeedBoxCollider() || sprite.colliderType == tk2dSpriteDefinition.ColliderType.Box) && meshCollider == null) { if (meshCollider != null) { DestroyImmediate(meshCollider, true); } } else if (sprite.colliderType == tk2dSpriteDefinition.ColliderType.Mesh) { if (boxCollider != null) { DestroyImmediate(boxCollider, true); } } else if (sprite.colliderType == tk2dSpriteDefinition.ColliderType.None) { if (meshCollider != null) { DestroyImmediate(meshCollider, true); } if (boxCollider != null) { DestroyImmediate(boxCollider, true); } } } else if (sprite.physicsEngine == tk2dSpriteDefinition.PhysicsEngine.Physics2D) { #if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) // Delete colliders from wrong physics engine if (boxCollider != null) { DestroyImmediate(boxCollider, true); } if (meshCollider != null) { DestroyImmediate(meshCollider, true); } foreach (PolygonCollider2D c2d in polygonCollider2D) { if (c2d != null) { DestroyImmediate(c2d, true); } } polygonCollider2D.Clear(); foreach (EdgeCollider2D e2d in edgeCollider2D) { if (e2d != null) { DestroyImmediate(e2d, true); } } edgeCollider2D.Clear(); if (boxCollider2D != null) { DestroyImmediate(boxCollider2D, true); boxCollider2D = null; } #endif } CreateCollider(); if (GetComponent <Collider>()) { GetComponent <Collider>().isTrigger = isTrigger; GetComponent <Collider>().material = physicsMaterial; } #if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) if (boxCollider2D) { boxCollider2D.isTrigger = isTrigger; boxCollider2D.sharedMaterial = physicsMaterial2D; } foreach (EdgeCollider2D ec in edgeCollider2D) { ec.isTrigger = isTrigger; ec.sharedMaterial = physicsMaterial2D; } foreach (PolygonCollider2D pc in polygonCollider2D) { pc.isTrigger = isTrigger; pc.sharedMaterial = physicsMaterial2D; } #endif }
private void RecursivelyAddSubObject(TankBlock block, ModContents mod, Transform targetTransform, JObject jData, Material defaultMaterial, bool isNewSubObject) { Debug.Log("[Nuterra] Called RecursivelyAddSubObject"); // Material - Used in the next step Material mat = null; bool hasMaterial = TryGetStringMultipleKeys(jData, out string materialName, "MaterialName", "MeshMaterialName"); bool hasAlbedo = TryGetStringMultipleKeys(jData, out string albedoName, "MeshTextureName", "TextureName"); bool hasGloss = TryGetStringMultipleKeys(jData, out string glossName, "MetallicTextureName", "GlossTextureName", "MeshGlossTextureName"); bool hasEmissive = TryGetStringMultipleKeys(jData, out string emissiveName, "EmissionTextureName", "MeshEmissionTextureName"); bool hasAnyOverrides = hasAlbedo || hasGloss || hasEmissive; // Calculate a unique string that defines this material string compoundMaterialName = ""; if (hasMaterial) { compoundMaterialName = $"{compoundMaterialName}M:{materialName};"; } if (hasAlbedo) { compoundMaterialName = $"{compoundMaterialName}A:{albedoName};"; } if (hasGloss) { compoundMaterialName = $"{compoundMaterialName}G:{glossName};"; } if (hasEmissive) { compoundMaterialName = $"{compoundMaterialName}E:{emissiveName};"; } if (hasAnyOverrides) { if (sMaterialCache.TryGetValue(compoundMaterialName, out Material existingMat)) { mat = existingMat; } else { // Default to missing texture, then see if we have a base texture reference mat = defaultMaterial; if (hasMaterial) { string matName = materialName.Replace("Venture_", "VEN_").Replace("GeoCorp_", "GC_"); mat = TTReferences.FindMaterial(matName); } Texture2D albedo = hasAlbedo ? TTReferences.Find <Texture2D>(albedoName, mod) : null; Texture2D gloss = hasGloss ? TTReferences.Find <Texture2D>(glossName, mod) : null; Texture2D emissive = hasEmissive ? TTReferences.Find <Texture2D>(emissiveName, mod) : null; mat = Util.CreateMaterial(mat, true, albedo, gloss, emissive); // Cache our newly created material in case it comes up again sMaterialCache.Add(compoundMaterialName, mat); } } else { // Actually, if we make no references, we can keep official modded block behaviour mat = defaultMaterial; } // Physics Material - Used in the next step PhysicMaterial physMat = new PhysicMaterial(); if (jData.TryGetValue("Friction", out JToken jFriction)) { physMat.dynamicFriction = jFriction.ToObject <float>(); } if (jData.TryGetValue("StaticFriction", out JToken jStaticFriction)) { physMat.staticFriction = jStaticFriction.ToObject <float>(); } if (jData.TryGetValue("Bounciness", out JToken jBounce)) { physMat.bounciness = jBounce.ToObject <float>(); } // MeshName & ColliderMeshName Override Mesh mesh = null; Mesh colliderMesh = null; bool supressBoxColliderFallback = TryParse(jData, "SupressBoxColliderFallback", TryParse(jData, "NoBoxCollider", false)); if (TryGetStringMultipleKeys(jData, out string meshName, "MeshName", "ModelName")) { foreach (UnityEngine.Object obj in mod.FindAllAssets(meshName)) { if (obj != null) { if (obj is Mesh) { mesh = (Mesh)obj; } else if (obj is GameObject) { mesh = ((GameObject)obj).GetComponentInChildren <MeshFilter>().sharedMesh; } } } Debug.Assert(mesh != null, $"[Nuterra] Failed to find mesh with name {meshName}"); } if (TryGetStringMultipleKeys(jData, out string meshColliderName, "ColliderMeshName", "MeshColliderName")) { foreach (UnityEngine.Object obj in mod.FindAllAssets(meshColliderName)) { if (obj is Mesh) { colliderMesh = (Mesh)obj; } else if (obj is GameObject) { colliderMesh = ((GameObject)obj).GetComponentInChildren <MeshFilter>().sharedMesh; } } Debug.Assert(colliderMesh != null, $"[Nuterra] Failed to find collider mesh with name {meshColliderName}"); } // This is the only bit where the root object majorly differs from subobjects if (targetTransform == block.transform) { // Generally speaking, the root of a TT block does not have meshes, so needs to add a child // Add mesh / collider mesh sub GameObject if we have either if (mesh != null || colliderMesh != null) { GameObject meshObj = CreateMeshGameObject(targetTransform, mesh, mat, colliderMesh, physMat, supressBoxColliderFallback); } } else // However, if we are poking around in a subobject, we may want to swap out existing renderers { // If we provided a new mesh, do a full swap if (mesh != null) { targetTransform.gameObject.EnsureComponent <MeshFilter>().sharedMesh = mesh; targetTransform.gameObject.EnsureComponent <MeshRenderer>().sharedMaterial = mat; } else // If we don't want to swap out the mesh we may still want to swap out the properties of existing renderers { bool forceEmissive = TryParse(jData, "ForceEmission", false); foreach (Renderer renderer in targetTransform.GetComponents <Renderer>()) { renderer.sharedMaterial = mat; if (renderer is ParticleSystemRenderer psrenderer) { psrenderer.trailMaterial = mat; } if (forceEmissive) { MaterialSwapper.SetMaterialPropertiesOnRenderer(renderer, ManTechMaterialSwap.MaterialColour.Normal, 1f, 0); } } } // If we provided a collider mesh, do a full swap if (colliderMesh != null) { MeshCollider mc = targetTransform.gameObject.EnsureComponent <MeshCollider>(); mc.convex = true; mc.sharedMesh = colliderMesh; mc.sharedMaterial = physMat; } // If we want a box collider, try to make one from our mesh bool makeBoxCollider = GetBoolMultipleKeys(jData, false, "MakeBoxCollider", "GenerateBoxCollider"); if (makeBoxCollider) { BoxCollider bc = targetTransform.gameObject.EnsureComponent <BoxCollider>(); bc.sharedMaterial = physMat; if (mesh != null) { mesh.RecalculateBounds(); bc.size = mesh.bounds.size - Vector3.one * 0.2f; bc.center = mesh.bounds.center; } else { bc.size = Vector3.one; bc.center = Vector3.zero; } } // Weird option from TTQMM that has a fixed size sphere bool makeSphereCollider = TryParse(jData, "MakeSphereCollider", false); if (makeSphereCollider) { SphereCollider sc = targetTransform.gameObject.EnsureComponent <SphereCollider>(); sc.radius = 0.5f; sc.center = Vector3.zero; sc.sharedMaterial = physMat; } } // ------------------------------------------------------ #region Deserializers if (TryGetTokenMultipleKeys(jData, out JToken jDeserialObj, "Deserializer", "JSONBLOCK") && jDeserialObj.Type == JTokenType.Object) { JObject jDeserializer = (JObject)jDeserialObj; // TTQMM Ref: GameObjectJSON.CreateGameObject(jBlock.Deserializer, blockbuilder.Prefab); NuterraDeserializer.DeserializeIntoGameObject(jDeserializer, block.gameObject); } #endregion // ------------------------------------------------------ // ------------------------------------------------------ #region Sub objects if (jData.TryGetValue("SubObjects", out JToken jSubObjectList) && jSubObjectList.Type == JTokenType.Array) { foreach (JToken token in (JArray)jSubObjectList) { if (token.Type == JTokenType.Object) { JObject jSubObject = (JObject)token; if (TryGetStringMultipleKeys(jSubObject, out string subObjName, "SubOverrideName", "OverrideName", "ObjectName")) { GameObject subObject = (targetTransform.RecursiveFindWithProperties(subObjName) as Component)?.gameObject; bool creatingNew = subObject == null; if (subObject != null) { if (TryGetTokenMultipleKeys(jSubObject, out JToken jLayer, "Layer", "PhysicsLayer") && jLayer.Type == JTokenType.Integer) { subObject.layer = jLayer.ToObject <int>(); } } else // Reference was not matched, so we want to add a new subobject { if (subObjName.NullOrEmpty()) { subObjName = $"SubObject_{targetTransform.childCount + 1}"; } subObject = new GameObject(subObjName); subObject.transform.parent = targetTransform; subObject.transform.localPosition = Vector3.zero; subObject.transform.localRotation = Quaternion.identity; if (TryGetTokenMultipleKeys(jSubObject, out JToken jLayer, "Layer", "PhysicsLayer") && jLayer.Type == JTokenType.Integer) { subObject.layer = jLayer.ToObject <int>(); } else { subObject.layer = 8; // Globals.inst.layerTank; } } // Target acquired, lets tweak a few things bool destroyColliders = GetBoolMultipleKeys(jSubObject, false, "DestroyExistingColliders", "DestroyColliders"); if (destroyColliders) { foreach (Collider col in subObject.GetComponents <Collider>()) { UnityEngine.Object.DestroyImmediate(col); } UnityEngine.Object.DestroyImmediate(subObject.GetComponentInParents <ColliderSwapper>()); } bool destroyRenderers = GetBoolMultipleKeys(jSubObject, false, "DestroyExistingRenderer", "DestroyExistingRenderers", "DestroyRenderers"); if (destroyRenderers) { foreach (Renderer renderer in subObject.GetComponents <Renderer>()) { UnityEngine.Object.DestroyImmediate(renderer); } foreach (MeshFilter mf in subObject.GetComponents <MeshFilter>()) { UnityEngine.Object.DestroyImmediate(mf); } } // If there is already a material set on this sub object ref, use it Material matForSubObject = mat; if (!creatingNew && !destroyRenderers) { Renderer ren = subObject.GetComponent <Renderer>(); if (ren) { matForSubObject = ren.sharedMaterial; } } // Optional resize settings if (TryGetTokenMultipleKeys(jSubObject, out JToken jPos, "SubPosition", "Position") && jPos.Type == JTokenType.Object) { subObject.transform.localPosition = GetVector3(jPos); } if (TryGetTokenMultipleKeys(jSubObject, out JToken jEuler, "SubRotation", "Rotation") && jEuler.Type == JTokenType.Object) { subObject.transform.localEulerAngles = GetVector3(jEuler); } if (TryGetTokenMultipleKeys(jSubObject, out JToken jScale, "SubScale", "Scale") && jScale.Type == JTokenType.Object) { subObject.transform.localScale = GetVector3(jScale); } RecursivelyAddSubObject(block, mod, subObject.transform, jSubObject, matForSubObject, creatingNew); } else { Debug.LogError($"[Nuterra] Failed to find SubOverrideName tag in sub object JSON"); } }
private bool IsGrounded() { RaycastHit hitInfo; if (Physics.Raycast(transform.position - BOTTOM_PLAYER_RAY_F + new Vector3(0, 0.05f, 0), Vector3.down, out hitInfo, 1.01f, ~0, QueryTriggerInteraction.Ignore)) { if (hitInfo.collider != null) { if (hitInfo.collider.material == null) { curSurface = surfaces[0]; } else { curSurface = hitInfo.collider.material; } return(true); } else { return(false); } } else if (Physics.Raycast(transform.position - BOTTOM_PLAYER_RAY_B + new Vector3(0, 0.05f, 0), Vector3.down, out hitInfo, 1.01f, ~0, QueryTriggerInteraction.Ignore)) { if (hitInfo.collider != null) { if (hitInfo.collider.material == null) { curSurface = surfaces[0]; } else { curSurface = hitInfo.collider.material; } return(true); } else { return(false); } } else if (Physics.Raycast(transform.position - BOTTOM_PLAYER_RAY_L + new Vector3(0, 0.05f, 0), Vector3.down, out hitInfo, 1.01f, ~0, QueryTriggerInteraction.Ignore)) { if (hitInfo.collider != null) { if (hitInfo.collider.material == null) { curSurface = surfaces[0]; } else { curSurface = hitInfo.collider.material; } return(true); } else { return(false); } } else if (Physics.Raycast(transform.position - BOTTOM_PLAYER_RAY_R + new Vector3(0, 0.05f, 0), Vector3.down, out hitInfo, 1.01f, ~0, QueryTriggerInteraction.Ignore)) { if (hitInfo.collider != null) { if (hitInfo.collider.material == null) { curSurface = surfaces[0]; } else { curSurface = hitInfo.collider.material; } return(true); } else { return(false); } } else if (Physics.Raycast(transform.position - BOTTOM_PLAYER_RAY_FR + new Vector3(0, 0.05f, 0), Vector3.down, out hitInfo, 1.01f, ~0, QueryTriggerInteraction.Ignore)) { if (hitInfo.collider != null) { if (hitInfo.collider.material == null) { curSurface = surfaces[0]; } else { curSurface = hitInfo.collider.material; } return(true); } else { return(false); } } else if (Physics.Raycast(transform.position - BOTTOM_PLAYER_RAY_FL + new Vector3(0, 0.05f, 0), Vector3.down, out hitInfo, 1.01f, ~0, QueryTriggerInteraction.Ignore)) { if (hitInfo.collider != null) { if (hitInfo.collider.material == null) { curSurface = surfaces[0]; } else { curSurface = hitInfo.collider.material; } return(true); } else { return(false); } } else if (Physics.Raycast(transform.position - BOTTOM_PLAYER_RAY_BR + new Vector3(0, 0.05f, 0), Vector3.down, out hitInfo, 1.01f, ~0, QueryTriggerInteraction.Ignore)) { if (hitInfo.collider != null) { if (hitInfo.collider.material == null) { curSurface = surfaces[0]; } else { curSurface = hitInfo.collider.material; } return(true); } else { return(false); } } else if (Physics.Raycast(transform.position - BOTTOM_PLAYER_RAY_BL + new Vector3(0, 0.05f, 0), Vector3.down, out hitInfo, 1.01f, ~0, QueryTriggerInteraction.Ignore)) { if (hitInfo.collider != null) { if (hitInfo.collider.material == null) { curSurface = surfaces[0]; } else { curSurface = hitInfo.collider.material; } return(true); } else { return(false); } } return(false); }
public Vehicle(Frame node, PhysicMaterial carMaterial = null, VehicleMotor motor = null, VehicleGears gears = null) : this((Actor)node.Affector, carMaterial, motor, gears) { }
//public float MoveInputTowardsTarget(float currentInput, float target, float acceleration) //{ // if (currentInput < target) // { // currentInput += acceleration * Time.deltaTime; // } // else if (currentInput > target) // { // currentInput -= acceleration * Time.deltaTime; // } // return currentInput; //} //private void OnCollisionStay(Collision collision) //{ // totalContacts += collision.contactCount; //} //public void OnCollisionEnter(Collision collision) //{ // ChangeFriction(collision.collider.material, .5f); //} //public void OnCollisionExit(Collision collision) //{ // ChangeFriction(collision.collider.material, 2f); //} public void ChangeFriction(PhysicMaterial material, float amountToTimesBy) { CharacterCollider.material.dynamicFriction = CharacterCollider.material.dynamicFriction * amountToTimesBy; CharacterCollider.material.staticFriction = CharacterCollider.material.staticFriction * amountToTimesBy; }
public MeshColliderConf(Mesh mesh, PhysicMaterial material) { Mesh = mesh; Material = material; }
public void setPhysicMaterial(PhysicMaterial pm) { phy_mat = pm; }
// Plays the right foot movement events // movementEventData: the data need to play the event // physicMaterial: physic material of the footstep void HandleRightFoot(MovementEventData movementEventData, PhysicMaterial physicMaterial) { SetPhysicMaterial(physicMaterial); movementEventData.normalizedSpeed = Mathf.Clamp01(m_ThirdPersonBrain.planarSpeed / m_MaximumSpeed); PlayRightFoot(movementEventData); }
private static void Internal_CreateDynamicsMaterial(PhysicMaterial mat, string name){}
// 物理素材の定義 PhysicMaterial CreatePhysicMaterial(PMDFormat format, PMDFormat.Rigidbody rigid) { PhysicMaterial material = new PhysicMaterial(format.name + "_r" + rigid.rigidbody_name); material.bounciness = rigid.rigidbody_recoil; material.staticFriction = rigid.rigidbody_friction; material.dynamicFriction = rigid.rigidbody_friction; AssetDatabase.CreateAsset(material, format.folder + "/Physics/" + material.name + ".asset"); return material; }