protected static SpriteBehavior InitializeSpriteBehavior(SpriteBehavior behavior, ColliderType collider_type, string sprite_path = "", float x = 0, float y = 0) { var game_object = behavior.gameObject; game_object.transform.position = new Vector3(x, y); behavior.sprite_renderer = game_object.AddComponent<SpriteRenderer>(); behavior.sprite_path = sprite_path; if (!string.IsNullOrEmpty(sprite_path)) { behavior.sprites = Resources.LoadAll<Sprite>(sprite_path); behavior.sprite_renderer.sprite = behavior.sprites[0]; } switch (collider_type) { case SpriteBehavior.ColliderType.Box: behavior.collider2d = game_object.AddComponent<BoxCollider2D>(); break; case SpriteBehavior.ColliderType.Circle: behavior.collider2d = game_object.AddComponent<CircleCollider2D>(); break; case SpriteBehavior.ColliderType.Polygon: behavior.collider2d = game_object.AddComponent<PolygonCollider2D>(); break; } behavior.touching_anything = false; return behavior; }
public CubeMesh Calculate(ref int visualVertexCount, ref int collisionVertexCount, Cube[,,] cubes, CubeLegend cubeLegend, ColliderType colliderType, string cubeTag) { // TODO: Put this back in when preprocessor directives are supported in Boo // Use UNITY_EDITOR //CubeGeneratorProgressEditor.ReportCube(chunk.gridPosition, gridPosition) if chunk // TODO: Vector3i.zero // TODO: Cached cube position of the chunk var position = (indexes - (chunk.dimensionsInCubes * chunk.gridPosition)).ToVector3() * cubeSize; var meshData = new CubeMesh(); if(!AdjacentCubeExistsInsideChunk(cubes, indexes.Down)) AddSide(Direction.Down, position, ref visualVertexCount, cubeLegend, meshData); if(!AdjacentCubeExistsInsideChunk(cubes, indexes.Up)) AddSide(Direction.Up, position, ref visualVertexCount, cubeLegend, meshData); if(!AdjacentCubeExistsInsideChunk(cubes, indexes.Right)) AddSide(Direction.Right, position, ref visualVertexCount, cubeLegend, meshData); if(!AdjacentCubeExistsInsideChunk(cubes, indexes.Left)) AddSide(Direction.Left, position, ref visualVertexCount, cubeLegend, meshData); if(!AdjacentCubeExistsInsideChunk(cubes, indexes.Front)) AddSide(Direction.Front, position, ref visualVertexCount, cubeLegend, meshData); if(!AdjacentCubeExistsInsideChunk(cubes, indexes.Back)) AddSide(Direction.Back, position, ref visualVertexCount, cubeLegend, meshData); if (cubeLegend.cubeDefinitions[type].hasCollision) { if(colliderType == ColliderType.MeshColliderPerChunk) { if(!AdjacentCubeExistsInsideChunkWithCollision(cubes, cubeLegend, indexes.Down)) AddCollisionSide(Direction.Down, position, ref collisionVertexCount, cubeLegend, meshData); if(!AdjacentCubeExistsInsideChunkWithCollision(cubes, cubeLegend, indexes.Up)) AddCollisionSide(Direction.Up, position, ref collisionVertexCount, cubeLegend, meshData); if(!AdjacentCubeExistsInsideChunkWithCollision(cubes, cubeLegend, indexes.Right)) AddCollisionSide(Direction.Right, position, ref collisionVertexCount, cubeLegend, meshData); if(!AdjacentCubeExistsInsideChunkWithCollision(cubes, cubeLegend, indexes.Left)) AddCollisionSide(Direction.Left, position, ref collisionVertexCount, cubeLegend, meshData); if(!AdjacentCubeExistsInsideChunkWithCollision(cubes, cubeLegend, indexes.Front)) AddCollisionSide(Direction.Front, position, ref collisionVertexCount, cubeLegend, meshData); if(!AdjacentCubeExistsInsideChunkWithCollision(cubes, cubeLegend, indexes.Back)) AddCollisionSide(Direction.Back, position, ref collisionVertexCount, cubeLegend, meshData); } else if(colliderType == ColliderType.BoxColliderPerCube) { // TODO: Defer this until the game objects are being created for async compatibility // if(generateCollider) CreateCollision(cubeTag); } } return meshData; }
public Collider(ICollidable owner, Rectangle bounds, ColliderType type, int npc_id) { this.m_owner = owner; this.m_bounds = new DoubleRect(bounds.X, bounds.Y, bounds.Width, bounds.Height); this.m_type = type; this.m_npc_id = npc_id; }
public Collider(ICollidable owner, Rectangle bounds, ColliderType type) { this.m_owner = owner; this.m_bounds = new DoubleRect(bounds.X, bounds.Y, bounds.Width, bounds.Height); this.m_bounds2 = new DoubleRect(bounds.X - 5, bounds.Y - 5, bounds.Width + 10, bounds.Height + 10); this.m_type = type; this.m_other = null; }
public EnemyController( Vector2 startPosition, int speed, Rectangle bounds, ColliderType type, float animationScale, string animationDataPath, string animationTexturePath ) : base(startPosition, speed, bounds, ColliderType.Enemy, animationScale, animationDataPath, animationTexturePath) { // nch }
/// <summary> /// Protected ctor - use the construct() method /// </summary> protected CharacterController( Vector2 startPosition, int speed, Rectangle bounds, ColliderType type, float animationScale, string animationDataPath, string animationTexturePath) { this.m_previousPosition = startPosition; this.m_position = startPosition; this.m_speedMax = speed; bounds.Offset((int)m_position.X, (int)m_position.Y); this.m_collider = new Collider(this, bounds, type); this.AnimationController = new AnimationController(animationDataPath, animationTexturePath); this.AnimationController.ActionTriggered += new ActionTriggeredEventHandler(this.handleAction); this.AnimationController.Scale = animationScale; this.GravityEffect = Gravity.Normal; this.Health = this.MaxHealth; this.m_previousAngle = (float)Math.PI / 2; }
public void CopyFrom(tk2dSpriteCollectionDefinition src) { name = src.name; disableTrimming = src.disableTrimming; additive = src.additive; scale = src.scale; texture = src.texture; materialId = src.materialId; anchor = src.anchor; anchorX = src.anchorX; anchorY = src.anchorY; overrideMesh = src.overrideMesh; doubleSidedSprite = src.doubleSidedSprite; customSpriteGeometry = src.customSpriteGeometry; geometryIslands = src.geometryIslands; dice = src.dice; diceUnitX = src.diceUnitX; diceUnitY = src.diceUnitY; diceFilter = src.diceFilter; pad = src.pad; source = src.source; fromSpriteSheet = src.fromSpriteSheet; hasSpriteSheetId = src.hasSpriteSheetId; spriteSheetX = src.spriteSheetX; spriteSheetY = src.spriteSheetY; spriteSheetId = src.spriteSheetId; extractRegion = src.extractRegion; regionX = src.regionX; regionY = src.regionY; regionW = src.regionW; regionH = src.regionH; regionId = src.regionId; colliderType = src.colliderType; boxColliderMin = src.boxColliderMin; boxColliderMax = src.boxColliderMax; polyColliderCap = src.polyColliderCap; colliderColor = src.colliderColor; colliderConvex = src.colliderConvex; colliderSmoothSphereCollisions = src.colliderSmoothSphereCollisions; extraPadding = src.extraPadding; colliderData = new List <ColliderData>(src.colliderData.Count); foreach (ColliderData srcCollider in src.colliderData) { ColliderData data = new ColliderData(); data.CopyFrom(srcCollider); colliderData.Add(data); } if (src.polyColliderIslands != null) { polyColliderIslands = new tk2dSpriteColliderIsland[src.polyColliderIslands.Length]; for (int i = 0; i < polyColliderIslands.Length; ++i) { polyColliderIslands[i] = new tk2dSpriteColliderIsland(); polyColliderIslands[i].CopyFrom(src.polyColliderIslands[i]); } } else { polyColliderIslands = new tk2dSpriteColliderIsland[0]; } if (src.geometryIslands != null) { geometryIslands = new tk2dSpriteColliderIsland[src.geometryIslands.Length]; for (int i = 0; i < geometryIslands.Length; ++i) { geometryIslands[i] = new tk2dSpriteColliderIsland(); geometryIslands[i].CopyFrom(src.geometryIslands[i]); } } else { geometryIslands = new tk2dSpriteColliderIsland[0]; } attachPoints = new List <tk2dSpriteDefinition.AttachPoint>(src.attachPoints.Count); foreach (tk2dSpriteDefinition.AttachPoint srcAp in src.attachPoints) { tk2dSpriteDefinition.AttachPoint ap = new tk2dSpriteDefinition.AttachPoint(); ap.CopyFrom(srcAp); attachPoints.Add(ap); } }
//draw custom editor window GUI void OnGUI() { //display label and object field for enemy model slot EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Enemy Model:"); enemyModel = (GameObject)EditorGUILayout.ObjectField(enemyModel, typeof(GameObject), false); EditorGUILayout.EndHorizontal(); //display label and objectfield for HUD bar prefab slot EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("HUD Bar Prefab:"); hudBar = (GameObject)EditorGUILayout.ObjectField(hudBar, typeof(GameObject), false); EditorGUILayout.EndHorizontal(); //display label and objectfield for shadow prefab slot EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Shadow Prefab:"); shadow = (GameObject)EditorGUILayout.ObjectField(shadow, typeof(GameObject), false); EditorGUILayout.EndHorizontal(); //display label and enum list for collider type EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Collider Type:"); colliderType = (ColliderType)EditorGUILayout.EnumPopup(colliderType); EditorGUILayout.EndHorizontal(); //display label and tag field for enemy tag EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Enemy Tag:"); tag = EditorGUILayout.TagField(tag); EditorGUILayout.EndHorizontal(); //display label and layer field for enemy layer EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Enemy Layer:"); layer = EditorGUILayout.LayerField(layer); EditorGUILayout.EndHorizontal(); //display label and checkbox for TweenMove component EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Attach TweenMove:"); attachTMove = EditorGUILayout.Toggle(attachTMove); EditorGUILayout.EndHorizontal(); //display label and checkbox for Properties component EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Attach Properties:"); attachProperties = EditorGUILayout.Toggle(attachProperties); EditorGUILayout.EndHorizontal(); //display label and checkbox for Rigidbody component EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Attach Rigidbody:"); attachRigidbody = EditorGUILayout.Toggle(attachRigidbody); EditorGUILayout.EndHorizontal(); //display info box below all settings EditorGUILayout.Space(); EditorGUILayout.HelpBox("By clicking on 'Apply!' all chosen components are added and a prefab will be created next to your enemy model.", MessageType.Info); EditorGUILayout.Space(); //apply button if (GUILayout.Button("Apply!")) { //cancel further execution if no enemy model is set if (enemyModel == null) { Debug.LogWarning("No enemy model chosen. Aborting Enemy Setup execution."); return; } //get model's asset path in this project to place the new prefab next to it string assetPath = AssetDatabase.GetAssetPath(enemyModel.GetInstanceID()); //e.g. assetPath = "Assets/Models/model.fbx //split folder structure for renaming the existing model name as prefab string[] folders = assetPath.Split('/'); //e.g. folders[0] = "Assets", folders[1] = "Models", folders[2] = "model.fbx" //then we replace the last part, the model name in folders[2], with the new prefab name assetPath = assetPath.Replace(folders[folders.Length - 1], enemyModel.name + ".prefab"); //new asset path: "Assets/Models/model.prefab" //instantiate, convert and setup model for new prefab ProcessModel(); //if TweenMove checkbox is checked, attach component if (attachTMove) { enemyModel.AddComponent <TweenMove>(); } Properties properties = null; //if Properties checkbox is checked if (attachProperties) { //attach and store Properties component for later use properties = enemyModel.AddComponent <Properties>(); } //if a HUD Bar prefab is set if (hudBar) { //instantiate HUD bar prefab hudBar = (GameObject)Instantiate(hudBar); //remove the "(Clone)" part of the name hudBar.name = hudBar.name.Replace("(Clone)", ""); //parent bars to enemy instance hudBar.transform.parent = enemyModel.transform; //reposition bars (Vector3.zero) relative to the enemy hudBar.transform.position = enemyModel.transform.position; if (!properties) { return; } //try to find and set sliders based on their name Transform healthbarTrans = hudBar.transform.FindChild("healthbar"); if (healthbarTrans) { Slider healthbar = healthbarTrans.GetComponent <Slider>(); properties.healthbar = healthbar; } Transform shieldbarTrans = hudBar.transform.FindChild("shieldbar"); if (shieldbarTrans) { Slider shieldbar = shieldbarTrans.GetComponent <Slider>(); properties.shield = new Shield(); properties.shield.bar = shieldbar; properties.shield.enabled = true; } } //if a shadow prefab is set if (shadow) { //instantiate shadow prefab shadow = (GameObject)Instantiate(shadow); //remove the "(Clone)" part of the name shadow.name = shadow.name.Replace("(Clone)", ""); //parent shadow to enemy instance shadow.transform.parent = enemyModel.transform; //reposition shadow (Vector3.zero) relative to the enemy shadow.transform.position = enemyModel.transform.position; } //if Rigidbody checkbox is checked if (attachRigidbody) { //attach and store Rigidbody component for later use Rigidbody rigidbody = enemyModel.AddComponent <Rigidbody>(); //disable gravity and kinematic rigidbody.useGravity = false; rigidbody.isKinematic = false; } //initialize prefab gameobject GameObject prefab = null; //perform check if we already have a prefab in our project (null if none) if (AssetDatabase.LoadAssetAtPath(assetPath, typeof(GameObject))) { //display custom dialog and wait for user input to overwrite prefab if (EditorUtility.DisplayDialog("Are you sure?", "The prefab already exists. Do you want to overwrite it?", "Yes", "No")) { //user clicked "Yes", create and overwrite existing prefab prefab = PrefabUtility.CreatePrefab(assetPath, enemyModel); } } else { //we haven't created a prefab before nor the project contains one, //create prefab next to the model at assetPath prefab = PrefabUtility.CreatePrefab(assetPath, enemyModel); } //destroy temporary instantiated enemy model in the editor DestroyImmediate(enemyModel); //if we created a prefab if (prefab) { //select it within the project panel Selection.activeGameObject = prefab; //close this editor window this.Close(); } } }
public BoxCollider CreateBoxCollider(Vector2 position, int width, int height, int mass, ColliderType type) { return(new BoxCollider(this, position, width, height, mass, type)); }
protected Collider(ColliderType type) { Collisions = new List <Collision>(); Intersections = new List <Intersection>(); Type = type; }
private async Task <IList <Asset> > LoadAssetsFromGLTF(AssetSource source, Guid containerId, ColliderType colliderType) { IList <Asset> assets = new List <Asset>(); DeterministicGuids guidGenerator = new DeterministicGuids(UtilMethods.StringToGuid( $"{containerId}:{source.ParsedUri.AbsoluteUri}")); // download file UtilMethods.GetUrlParts(source.ParsedUri.AbsoluteUri, out string rootUrl, out string filename); var loader = new WebRequestLoader(rootUrl); await loader.LoadStream(filename); // pre-parse glTF document so we can get a scene count // TODO: run this in thread GLTF.GLTFParser.ParseJson(loader.LoadedStream, out GLTF.Schema.GLTFRoot gltfRoot); GLTFSceneImporter importer = MREAPI.AppsAPI.GLTFImporterFactory.CreateImporter(gltfRoot, loader, _asyncHelper, loader.LoadedStream); importer.SceneParent = MREAPI.AppsAPI.AssetCache.CacheRootGO().transform; importer.Collider = colliderType.ToGLTFColliderType(); // load prefabs if (gltfRoot.Scenes != null) { for (var i = 0; i < gltfRoot.Scenes.Count; i++) { await importer.LoadSceneAsync(i); GameObject rootObject = importer.LastLoadedScene; rootObject.name = gltfRoot.Scenes[i].Name ?? $"scene:{i}"; MWGOTreeWalker.VisitTree(rootObject, (go) => { go.layer = UnityConstants.ActorLayerIndex; }); var def = GenerateAssetPatch(rootObject, guidGenerator.Next()); def.Name = rootObject.name; def.Source = new AssetSource(source.ContainerType, source.Uri, $"scene:{i}"); MREAPI.AppsAPI.AssetCache.CacheAsset(rootObject, def.Id, containerId, source); assets.Add(def); } } // load textures if (gltfRoot.Textures != null) { for (var i = 0; i < gltfRoot.Textures.Count; i++) { await importer.LoadTextureAsync(gltfRoot.Textures[i], i, true); var texture = importer.GetTexture(i); texture.name = gltfRoot.Textures[i].Name ?? $"texture:{i}"; var asset = GenerateAssetPatch(texture, guidGenerator.Next()); asset.Name = texture.name; asset.Source = new AssetSource(source.ContainerType, source.Uri, $"texture:{i}"); MREAPI.AppsAPI.AssetCache.CacheAsset(texture, asset.Id, containerId, source); assets.Add(asset); } } // load materials if (gltfRoot.Materials != null) { for (var i = 0; i < gltfRoot.Materials.Count; i++) { var matdef = gltfRoot.Materials[i]; var material = await importer.LoadMaterialAsync(i); material.name = matdef.Name ?? $"material:{i}"; var asset = GenerateAssetPatch(material, guidGenerator.Next()); asset.Name = material.name; asset.Source = new AssetSource(source.ContainerType, source.Uri, $"material:{i}"); MREAPI.AppsAPI.AssetCache.CacheAsset(material, asset.Id, containerId, source); assets.Add(asset); } } importer.Dispose(); return(assets); }
public void SetEnumToBodyType(JelloBody t) { if(t.GetComponent<JelloBody>().GetType().ToString() == "JelloBody") colliderType = ColliderType.Static; if(t.GetComponent<JelloBody>().GetType().ToString() == "JelloSpringBody") colliderType = ColliderType.Spring; if(t.GetComponent<JelloBody>().GetType().ToString() == "JelloPressureBody") colliderType = ColliderType.Pressure; }
public void CopyFrom(tk2dSpriteCollectionDefinition src) { this.name = src.name; this.disableTrimming = src.disableTrimming; this.additive = src.additive; this.scale = src.scale; this.texture = src.texture; this.materialId = src.materialId; this.anchor = src.anchor; this.anchorX = src.anchorX; this.anchorY = src.anchorY; this.overrideMesh = src.overrideMesh; this.doubleSidedSprite = src.doubleSidedSprite; this.customSpriteGeometry = src.customSpriteGeometry; this.geometryIslands = src.geometryIslands; this.dice = src.dice; this.diceUnitX = src.diceUnitX; this.diceUnitY = src.diceUnitY; this.diceFilter = src.diceFilter; this.pad = src.pad; this.source = src.source; this.fromSpriteSheet = src.fromSpriteSheet; this.hasSpriteSheetId = src.hasSpriteSheetId; this.spriteSheetX = src.spriteSheetX; this.spriteSheetY = src.spriteSheetY; this.spriteSheetId = src.spriteSheetId; this.extractRegion = src.extractRegion; this.regionX = src.regionX; this.regionY = src.regionY; this.regionW = src.regionW; this.regionH = src.regionH; this.regionId = src.regionId; this.colliderType = src.colliderType; this.boxColliderMin = src.boxColliderMin; this.boxColliderMax = src.boxColliderMax; this.polyColliderCap = src.polyColliderCap; this.colliderColor = src.colliderColor; this.colliderConvex = src.colliderConvex; this.colliderSmoothSphereCollisions = src.colliderSmoothSphereCollisions; this.extraPadding = src.extraPadding; this.colliderData = new List<ColliderData>(src.colliderData.Count); foreach (ColliderData data in src.colliderData) { ColliderData item = new ColliderData(); item.CopyFrom(data); this.colliderData.Add(item); } if (src.polyColliderIslands != null) { this.polyColliderIslands = new tk2dSpriteColliderIsland[src.polyColliderIslands.Length]; for (int i = 0; i < this.polyColliderIslands.Length; i++) { this.polyColliderIslands[i] = new tk2dSpriteColliderIsland(); this.polyColliderIslands[i].CopyFrom(src.polyColliderIslands[i]); } } else { this.polyColliderIslands = new tk2dSpriteColliderIsland[0]; } if (src.geometryIslands != null) { this.geometryIslands = new tk2dSpriteColliderIsland[src.geometryIslands.Length]; for (int j = 0; j < this.geometryIslands.Length; j++) { this.geometryIslands[j] = new tk2dSpriteColliderIsland(); this.geometryIslands[j].CopyFrom(src.geometryIslands[j]); } } else { this.geometryIslands = new tk2dSpriteColliderIsland[0]; } this.attachPoints = new List<tk2dSpriteDefinition.AttachPoint>(src.attachPoints.Count); foreach (tk2dSpriteDefinition.AttachPoint point in src.attachPoints) { tk2dSpriteDefinition.AttachPoint point2 = new tk2dSpriteDefinition.AttachPoint(); point2.CopyFrom(point); this.attachPoints.Add(point2); } }
/// <summary> /// Creates a single collider that wraps around the <param name="rootGameObject">GameObject</param> and its children. /// </summary> /// <param name="rootGameObject">Root GameObject containing the children to wrap.</param> /// <param name="colliderType">Type of the collider to wrap the GameObjects.</param> /// <param name="removeExistingColliders">Remove or keep the existing colliders?</param> public static void CreateCollider(GameObject rootGameObject, ColliderType colliderType, bool removeExistingColliders = true) { if (removeExistingColliders) { Collider[] colliders = rootGameObject.GetComponentsInChildren<Collider>(); foreach (Collider currentCollider in colliders) Object.DestroyImmediate(currentCollider); } if (colliderType == ColliderType.None) return; // Checks if the object has any child if (rootGameObject.GetComponentsInChildren<Transform>().Length > 1) { // Gets and saves the object's initial Transform and initializes it. // This is done to have a correct Transform for the combined mesh. Transform objectTransform = rootGameObject.transform; Vector3 initialPosition = objectTransform.position; Quaternion initialRotation = objectTransform.rotation; objectTransform.position = Vector3.zero; objectTransform.rotation = Quaternion.identity; // Combine the meshes MeshFilter[] meshFilters = rootGameObject.GetComponentsInChildren<MeshFilter>(); CombineInstance[] combine = new CombineInstance[meshFilters.Length]; for (int i = 0; i < meshFilters.Length; i++) { combine[i].mesh = meshFilters[i].sharedMesh; combine[i].transform = meshFilters[i].transform.localToWorldMatrix; } // If the root object has already a mesh filter, stores it to give it back later MeshFilter tempMeshFilter; Mesh intialMesh; if (tempMeshFilter = rootGameObject.GetComponent<MeshFilter>()) { intialMesh = tempMeshFilter.sharedMesh; } else { intialMesh = null; tempMeshFilter = rootGameObject.AddComponent<MeshFilter>() as MeshFilter; } tempMeshFilter.sharedMesh = new Mesh(); tempMeshFilter.sharedMesh.CombineMeshes(combine); AddCollider(rootGameObject, colliderType); Object.DestroyImmediate(tempMeshFilter); if (intialMesh != null) { MeshFilter meshFilter = rootGameObject.AddComponent<MeshFilter>() as MeshFilter; meshFilter.mesh = intialMesh; } objectTransform.position = initialPosition; objectTransform.rotation = initialRotation; } else { AddCollider(rootGameObject, colliderType); } }
static void LoadPrefs() { pbStripProBuilderOnBuild = pb_Preferences_Internal.GetBool(pb_Constant.pbStripProBuilderOnBuild); pbDisableAutoUV2Generation = pb_Preferences_Internal.GetBool(pb_Constant.pbDisableAutoUV2Generation); pbShowSceneInfo = pb_Preferences_Internal.GetBool(pb_Constant.pbShowSceneInfo); defaultOpenInDockableWindow = pb_Preferences_Internal.GetBool(pb_Constant.pbDefaultOpenInDockableWindow); pbDragCheckLimit = pb_Preferences_Internal.GetBool(pb_Constant.pbDragCheckLimit); pbForceConvex = pb_Preferences_Internal.GetBool(pb_Constant.pbForceConvex); pbForceGridPivot = pb_Preferences_Internal.GetBool(pb_Constant.pbForceGridPivot); pbForceVertexPivot = pb_Preferences_Internal.GetBool(pb_Constant.pbForceVertexPivot); pbPerimeterEdgeBridgeOnly = pb_Preferences_Internal.GetBool(pb_Constant.pbPerimeterEdgeBridgeOnly); pbPBOSelectionOnly = pb_Preferences_Internal.GetBool(pb_Constant.pbPBOSelectionOnly); pbCloseShapeWindow = pb_Preferences_Internal.GetBool(pb_Constant.pbCloseShapeWindow); pbUVEditorFloating = pb_Preferences_Internal.GetBool(pb_Constant.pbUVEditorFloating); // pbShowSceneToolbar = pb_Preferences_Internal.GetBool(pb_Constant.pbShowSceneToolbar); pbShowEditorNotifications = pb_Preferences_Internal.GetBool(pb_Constant.pbShowEditorNotifications); pbUniqueModeShortcuts = pb_Preferences_Internal.GetBool(pb_Constant.pbUniqueModeShortcuts); pbIconGUI = pb_Preferences_Internal.GetBool(pb_Constant.pbIconGUI); pbShiftOnlyTooltips = pb_Preferences_Internal.GetBool(pb_Constant.pbShiftOnlyTooltips); pbDrawAxisLines = pb_Preferences_Internal.GetBool(pb_Constant.pbDrawAxisLines); pbMeshesAreAssets = pb_Preferences_Internal.GetBool(pb_Constant.pbMeshesAreAssets); pbElementSelectIsHamFisted = pb_Preferences_Internal.GetBool(pb_Constant.pbElementSelectIsHamFisted); pbDragSelectWholeElement = pb_Preferences_Internal.GetBool(pb_Constant.pbDragSelectWholeElement); pbDefaultFaceColor = pb_Preferences_Internal.GetColor( pb_Constant.pbDefaultFaceColor ); pbDefaultEdgeColor = pb_Preferences_Internal.GetColor( pb_Constant.pbDefaultEdgeColor ); pbDefaultSelectedVertexColor = pb_Preferences_Internal.GetColor( pb_Constant.pbDefaultSelectedVertexColor ); pbDefaultVertexColor = pb_Preferences_Internal.GetColor( pb_Constant.pbDefaultVertexColor ); pbUVGridSnapValue = pb_Preferences_Internal.GetFloat(pb_Constant.pbUVGridSnapValue); pbVertexHandleSize = pb_Preferences_Internal.GetFloat(pb_Constant.pbVertexHandleSize); defaultColliderType = pb_Preferences_Internal.GetEnum<ColliderType>(pb_Constant.pbDefaultCollider); pbToolbarLocation = pb_Preferences_Internal.GetEnum<SceneToolbarLocation>(pb_Constant.pbToolbarLocation); pbDefaultEntity = pb_Preferences_Internal.GetEnum<EntityType>(pb_Constant.pbDefaultEntity); #if !UNITY_4_7 pbShadowCastingMode = pb_Preferences_Internal.GetEnum<ShadowCastingMode>(pb_Constant.pbShadowCastingMode); #endif pbDefaultMaterial = pb_Preferences_Internal.GetMaterial(pb_Constant.pbDefaultMaterial); defaultShortcuts = pb_Preferences_Internal.GetShortcuts().ToArray(); }
//draw custom editor window GUI void OnGUI() { //display label and object field for tower model slot EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Tower Model:"); towerModel = (GameObject)EditorGUILayout.ObjectField(towerModel, typeof(GameObject), false); EditorGUILayout.EndHorizontal(); //display label and object field for range indicator prefab slot EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("RangeIndicator Prefab:"); rangeIndicator = (GameObject)EditorGUILayout.ObjectField(rangeIndicator, typeof(GameObject), false); EditorGUILayout.EndHorizontal(); //display label and object field for range trigger prefab slot EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("RangeTrigger Prefab:"); rangeTrigger = (GameObject)EditorGUILayout.ObjectField(rangeTrigger, typeof(GameObject), false); EditorGUILayout.EndHorizontal(); //display label and enum list for collider type EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Collider Type:"); colliderType = (ColliderType)EditorGUILayout.EnumPopup(colliderType); EditorGUILayout.EndHorizontal(); //display label and layer field for tower layer EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Tower Layer:"); layer = EditorGUILayout.LayerField(layer); EditorGUILayout.EndHorizontal(); //display label and checkbox for TowerBase component EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Attach TowerBase:"); attachTowerBase = EditorGUILayout.Toggle(attachTowerBase); EditorGUILayout.EndHorizontal(); //display label and checkbox for Upgrade component EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Attach Upgrade:"); attachUpgrade = EditorGUILayout.Toggle(attachUpgrade); EditorGUILayout.EndHorizontal(); //display info box below all settings EditorGUILayout.Space(); EditorGUILayout.HelpBox("By clicking on 'Apply!' all chosen components are added and a prefab will be created next to your tower model.", MessageType.Info); EditorGUILayout.Space(); //apply button if (GUILayout.Button("Apply!")) { //cancel further execution if no tower model is set if (towerModel == null) { Debug.LogWarning("No tower model chosen. Aborting Tower Setup execution."); return; } //get model's asset path in this project to place the new prefab next to it string assetPath = AssetDatabase.GetAssetPath(towerModel.GetInstanceID()); //e.g. assetPath = "Assets/Models/model.fbx //split folder structure for renaming the existing model name as prefab string[] folders = assetPath.Split('/'); //e.g. folders[0] = "Assets", folders[1] = "Models", folders[2] = "model.fbx" //then we replace the last part, the model name in folders[2], with the new prefab name assetPath = assetPath.Replace(folders[folders.Length - 1], towerModel.name + ".prefab"); //new asset path: "Assets/Models/model.prefab" //create new tower container gameobject Transform towerContainer = new GameObject(towerModel.name).transform; //instantiate, convert and setup model to new prefab ProcessModel(); //parent tower instance to container gameobject and reposition it (relative Vector3.zero) towerModel.transform.parent = towerContainer; towerModel.transform.position = towerContainer.position; //if range indicator checkbox is checked if (rangeIndicator) { //instantiate range indicator prefab rangeIndicator = (GameObject)Instantiate(rangeIndicator); //rename prefab clone to match naming conventions of Upgrade.cs //remove the "(Clone)" part of the name rangeIndicator.name = rangeIndicator.name.Replace("(Clone)", ""); //parent range indicator to tower container rangeIndicator.transform.parent = towerContainer; //relatively reposition the range indicator slightly above to the tower container rangeIndicator.transform.position = towerContainer.position + new Vector3(0, 0.2f, 0); } //if range trigger checkbox is checked if (rangeTrigger) { //instantiate range trigger prefab rangeTrigger = (GameObject)Instantiate(rangeTrigger); //rename prefab clone to match naming conventions of Upgrade.cs //remove the "(Clone)" part of the name rangeTrigger.name = rangeTrigger.name.Replace("(Clone)", ""); //parent range trigger to tower container rangeTrigger.transform.parent = towerContainer; //relatively reposition the range trigger in the middle of the tower container rangeTrigger.transform.position = towerContainer.position + new Vector3(0, totalBounds.extents.y, 0); } //if TowerBase checkbox is checked if (attachTowerBase) { //create new gameobject used as shoot position and call it 'shotPos' GameObject shotPosObj = new GameObject("shotPos"); //parent shotPosObj directly to the tower instance shotPosObj.transform.parent = towerModel.transform; //reposition shotPosObj shotPosObj.transform.position = towerModel.transform.position; //set shotPos object's layer to built-in layer 2 : ignore raycast shotPosObj.layer = 2; //attach and store TowerBase component TowerBase towerBase = towerModel.AddComponent<TowerBase>(); //set shotPos transform to this component towerBase.shotPos = shotPosObj.transform; //disable the script, it only gets activated at runtime towerBase.enabled = false; //if we instantiated a range indicator, set it to this component if (rangeIndicator) towerBase.rangeInd = rangeIndicator; } //if Upgrade checkbox is checked, add component if (attachUpgrade) towerModel.AddComponent<Upgrade>(); //parent model to container towerModel.transform.parent = towerContainer; //initialize prefab gameobject GameObject prefab = null; //perform check if we already have a prefab in our project (null if none) if (AssetDatabase.LoadAssetAtPath(assetPath, typeof(GameObject))) { //display custom dialog and wait for user input to overwrite prefab if (EditorUtility.DisplayDialog("Are you sure?", "The prefab already exists. Do you want to overwrite it?", "Yes", "No")) { //user clicked "Yes", create and overwrite existing prefab prefab = PrefabUtility.CreatePrefab(assetPath, towerContainer.gameObject); } } else //we haven't created a prefab before nor the project contains one, //create prefab next to the model at assetPath prefab = PrefabUtility.CreatePrefab(assetPath, towerContainer.gameObject); //destroy temporary instantiated tower model in the editor DestroyImmediate(towerContainer.gameObject); //if we created a prefab if (prefab) { //select it within the project panel Selection.activeGameObject = prefab; //close this editor window this.Close(); } } }
public virtual void DrawEditorGUITwo() { serializedObject.Update(); if(tar.GetComponent<MeshLink>() != null) hasMeshLink = true; else hasMeshLink = false; EditorGUILayout.BeginHorizontal(); SerializedProperty eMeshLink = serializedObject.FindProperty("meshLink"); GUIStyle meshStyle = new GUIStyle(EditorStyles.popup); if(eMeshLink.prefabOverride) meshStyle.fontStyle = FontStyle.Bold; meshLinkType = (MeshLink.MeshLinkType)EditorGUILayout.EnumPopup(meshLinkTypeContent, meshLinkType, meshStyle); bool showChangeButton = false; if(hasMeshLink) { if(tar.GetComponent<MeshLink>().meshLinkType != meshLinkType) showChangeButton = true; } else if(meshLinkType != MeshLink.MeshLinkType.None) { showChangeButton = true; } if(showChangeButton) { if(GUILayout.Button(changeTypeContent, EditorStyles.miniButton)) { for(int i = 0; i < serializedObject.targetObjects.Length; i++) ChangeMeshLink((JelloBody)serializedObject.targetObjects[i]); } } EditorGUILayout.EndHorizontal(); colliderType = (ColliderType)EditorGUILayout.EnumPopup(bodyTypeContent, colliderType, EditorStyles.miniButton); EditorGUILayout.BeginHorizontal(); if(CompareEnumStateWithType(tar)) { EditorGUI.indentLevel++; if(GUILayout.Button(new GUIContent(changeTypeContent), EditorStyles.miniButton )) //todo make this change all targets { JelloBody[] oldTargets = new JelloBody[targets.Length]; for(int i = 0; i < serializedObject.targetObjects.Length; i++) { JelloBody t = (JelloBody)serializedObject.targetObjects[i]; ChangeBodyType(t, retainBodyInformation); oldTargets[i] = t; } for(int i = 0; i < oldTargets.Length; i++) { Undo.DestroyObjectImmediate (oldTargets[i]); } return; } retainBodyInformation = EditorGUILayout.Toggle(keepInfoContent, retainBodyInformation); EditorGUI.indentLevel--; } EditorGUILayout.EndHorizontal(); EditorGUILayout.Separator(); EditorGUILayout.Separator(); EditorGUILayout.BeginHorizontal(); string[] options = new string[subEditors.Count]; for(int i = 0; i < options.Length; i++) options[i] = subEditors[i].name; currentSubEditor = EditorGUILayout.Popup("SubComponent", currentSubEditor, options); EditorGUILayout.EndHorizontal(); subEditors[currentSubEditor].DrawEditorGUI(); serializedObject.ApplyModifiedProperties(); }
public void CopyFrom(tk2dSpriteCollectionDefinition src) { name = src.name; disableTrimming = src.disableTrimming; additive = src.additive; scale = src.scale; texture = src.texture; materialId = src.materialId; anchor = src.anchor; anchorX = src.anchorX; anchorY = src.anchorY; overrideMesh = src.overrideMesh; doubleSidedSprite = src.doubleSidedSprite; customSpriteGeometry = src.customSpriteGeometry; geometryIslands = src.geometryIslands; dice = src.dice; diceUnitX = src.diceUnitX; diceUnitY = src.diceUnitY; diceFilter = src.diceFilter; pad = src.pad; source = src.source; fromSpriteSheet = src.fromSpriteSheet; hasSpriteSheetId = src.hasSpriteSheetId; spriteSheetX = src.spriteSheetX; spriteSheetY = src.spriteSheetY; spriteSheetId = src.spriteSheetId; extractRegion = src.extractRegion; regionX = src.regionX; regionY = src.regionY; regionW = src.regionW; regionH = src.regionH; regionId = src.regionId; colliderType = src.colliderType; boxColliderMin = src.boxColliderMin; boxColliderMax = src.boxColliderMax; polyColliderCap = src.polyColliderCap; colliderColor = src.colliderColor; colliderConvex = src.colliderConvex; colliderSmoothSphereCollisions = src.colliderSmoothSphereCollisions; extraPadding = src.extraPadding; colliderData = new List<ColliderData>( src.colliderData.Count ); foreach ( ColliderData srcCollider in src.colliderData ) { ColliderData data = new ColliderData(); data.CopyFrom(srcCollider); colliderData.Add(data); } if (src.polyColliderIslands != null) { polyColliderIslands = new tk2dSpriteColliderIsland[src.polyColliderIslands.Length]; for (int i = 0; i < polyColliderIslands.Length; ++i) { polyColliderIslands[i] = new tk2dSpriteColliderIsland(); polyColliderIslands[i].CopyFrom(src.polyColliderIslands[i]); } } else { polyColliderIslands = new tk2dSpriteColliderIsland[0]; } if (src.geometryIslands != null) { geometryIslands = new tk2dSpriteColliderIsland[src.geometryIslands.Length]; for (int i = 0; i < geometryIslands.Length; ++i) { geometryIslands[i] = new tk2dSpriteColliderIsland(); geometryIslands[i].CopyFrom(src.geometryIslands[i]); } } else { geometryIslands = new tk2dSpriteColliderIsland[0]; } attachPoints = new List<tk2dSpriteDefinition.AttachPoint>(src.attachPoints.Count); foreach (tk2dSpriteDefinition.AttachPoint srcAp in src.attachPoints) { tk2dSpriteDefinition.AttachPoint ap = new tk2dSpriteDefinition.AttachPoint(); ap.CopyFrom(srcAp); attachPoints.Add(ap); } }
/// <summary> /// Clones from another CubedObjectBehavior. This can be helpful for generators that need to run in threads and /// combine their results later. /// </summary> /// <param name='other'> /// The CubedObjectBehavior to clone from. /// </param> public void CloneFrom(CubedObjectBehaviour other) { allCubes = new Cube[other.TotalDimensions.x, other.TotalDimensions.y, other.TotalDimensions.z]; System.Array.Copy(other.allCubes, allCubes, other.allCubes.Length); material = other.material; chunkDimensions = other.chunkDimensions.Clone(); dimensionsInChunks = other.dimensionsInChunks.Clone(); colliderType = other.colliderType; cubeLegend = other.cubeLegend.Clone(); cubeSize = other.cubeSize; // TODO: Add more things to copy over. }
public OneToManyCollisionController() : base() { _targetObjectType = ColliderType.None; }
public override void OnInspectorGUI() { if (Application.isPlaying == false) { EditorGUI.BeginChangeCheck(); if (GUILayout.Button("Reset Transforms")) { for (int i = 0; i < targets.Length; i++) { SerializedObject ser = new SerializedObject(targets [i]); ser.FindProperty("_positionalTransform").objectReferenceValue = ((LSBody)targets [i]).transform; ser.FindProperty("_rotationalTransform").objectReferenceValue = ((LSBody)targets [i]).transform; ser.ApplyModifiedProperties(); } so.Update(); } if (targets.Length == 1) { PositionalTransform.Draw(); RotationalTransform.Draw(); } Shape.Draw(); ColliderType shape = (ColliderType)Shape.intValue; if (shape != ColliderType.None) { EditorGUILayout.Space(); EditorGUILayout.LabelField("General Collider Settings", EditorStyles.boldLabel); Layer.Draw(); IsTrigger.Draw(); if (IsTrigger.boolValue == false) { Immovable.Draw(); } Height.Draw(); EditorGUILayout.Space(); EditorGUILayout.LabelField("Collider Settings", EditorStyles.boldLabel); if (shape == ColliderType.Circle) { Radius.Draw(); } else if (shape == ColliderType.AABox) { HalfWidth.Draw(); HalfHeight.Draw(); } else if (shape == ColliderType.Polygon) { EditorGUIUtility.LookLikeControls(); Vertices.Draw(); } } SceneView.RepaintAll(); if (true)//EditorGUI.EndChangeCheck()) { so.ApplyModifiedProperties(); } } else { //Debug view when playing EditorGUILayout.LabelField("Runtime Debugging", EditorStyles.boldLabel); base.OnInspectorGUI(); } }
public void Init(World world, int wx, int wy, int wz, ColliderType colliderType) { _world = world; _x = wx * WIDTH; _y = wy * HEIGHT; _z = wz * LENGTH; _width = Mathf.Min(WIDTH, world.width - _x); _height = Mathf.Min(HEIGHT, world.height - _y); _length = Mathf.Min(LENGTH, world.length - _z); _colliderType = colliderType; if (_colliderType == ColliderType.MESH) _meshCollider = gameObject.AddComponent<MeshCollider>(); // signal that we need a rebuild _invalid = true; }
public void Initialize() { defaultFont = m_defaultFont; defaultMaterial = m_defaultMaterial; defaultColor = m_defaultColor; defaultResolution = m_defaultResolution; defaultSize = m_defaultSize; defaultDepth = m_defaultDepth; defaultLetterSpacing = m_defaultLetterSpacing; defaultLineSpacing = m_defaultLineSpacing; defaultJustification = m_defaultJustification; includeBackface = m_includeBackface; texturePerLetter = m_texturePerLetter; anchor = m_anchor; zAnchor = m_zAnchor; colliderType = m_colliderType; addRigidbodies = m_addRigidbodies; physicsMaterial = m_physicsMaterial; smoothingAngle = m_smoothingAngle; if (defaultMaterial == null) { var mat = Resources.Load ("VertexColored") as Material; if (mat) { defaultMaterial = mat; } else { var shader = Shader.Find ("Diffuse"); if (shader) { defaultMaterial = new Material(shader); } } } if (m_fontData.Count == 0) { _initialized = false; return; } _fontInfo = new TTFFontInfo[m_fontData.Count]; _fontNames = new string[m_fontData.Count]; for (int i = 0; i < m_fontData.Count; i++) { if (m_fontData[i].ttfFile != null) { _fontInfo[i] = new TTFFontInfo (m_fontData[i].ttfFile.bytes); var name = _fontInfo[i].name; name = name.Replace(" ", ""); name = name.ToLower(); _fontNames[i] = name; } } _colorDictionary = new Dictionary<string, Color>(){{"red", Color.red}, {"green", Color.green}, {"blue", Color.blue}, {"white", Color.white}, {"black", Color.black}, {"yellow", Color.yellow}, {"cyan", Color.cyan}, {"magenta", Color.magenta}, {"gray", Color.gray}, {"grey", Color.grey}}; DontDestroyOnLoad (this); _initialized = true; }
//draw custom editor window GUI void OnGUI() { //display label and object field for projectile model slot EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Projectile Model:"); projectileModel = (GameObject)EditorGUILayout.ObjectField(projectileModel, typeof(GameObject), false); EditorGUILayout.EndHorizontal(); //display label and enum list for collider type EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Collider Type:"); colliderType = (ColliderType)EditorGUILayout.EnumPopup(colliderType); EditorGUILayout.EndHorizontal(); //display label and layer field for projectile layer EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Projectile Layer:"); layer = EditorGUILayout.LayerField(layer); EditorGUILayout.EndHorizontal(); //display label and checkbox for Projectile component EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Attach Projectile:"); attachProjectile = EditorGUILayout.Toggle(attachProjectile); EditorGUILayout.EndHorizontal(); //display label and checkbox for Rigidbody component EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Attach Rigidbody:"); attachRigidbody = EditorGUILayout.Toggle(attachRigidbody); EditorGUILayout.EndHorizontal(); //display info box below all settings EditorGUILayout.Space(); EditorGUILayout.HelpBox("By clicking on 'Apply!' all chosen components are added and a prefab will be created next to your projectile model.", MessageType.Info); EditorGUILayout.Space(); //apply button if (GUILayout.Button("Apply!")) { //cancel further execution if no tower model is set if (projectileModel == null) { Debug.LogWarning("No projectile model chosen. Aborting Projectile Setup execution."); return; } //get model's asset path in this project to place the new prefab next to it string assetPath = AssetDatabase.GetAssetPath(projectileModel.GetInstanceID()); //e.g. assetPath = "Assets/Models/model.fbx //split folder structure for renaming the existing model name as prefab string[] folders = assetPath.Split('/'); //e.g. folders[0] = "Assets", folders[1] = "Models", folders[2] = "model.fbx" //then we replace the last part, the model name in folders[2], with the new prefab name assetPath = assetPath.Replace(folders[folders.Length - 1], projectileModel.name + ".prefab"); //new asset path: "Assets/Models/model.prefab" //instantiate, convert and setup model to new prefab ProcessModel(); //if Projectile checkbox is checked if (attachProjectile) { //attach Projectile component projectileModel.AddComponent<Projectile>(); } //if Rigidbody checkbox is checked, add component if (attachRigidbody) { //attach and store rigidbody component Rigidbody rigid = projectileModel.AddComponent<Rigidbody>(); //make rigidbody kinematic rigid.isKinematic = true; //disable gravity rigid.useGravity = false; } //initialize prefab gameobject GameObject prefab = null; //perform check if we already have a prefab in our project (null if none) if (AssetDatabase.LoadAssetAtPath(assetPath, typeof(GameObject))) { //display custom dialog and wait for user input to overwrite prefab if (EditorUtility.DisplayDialog("Are you sure?", "The prefab already exists. Do you want to overwrite it?", "Yes", "No")) { //user clicked "Yes", create and overwrite existing prefab prefab = PrefabUtility.CreatePrefab(assetPath, projectileModel.gameObject); } } else //we haven't created a prefab before nor the project contains one, //create prefab next to the model at assetPath prefab = PrefabUtility.CreatePrefab(assetPath, projectileModel.gameObject); //destroy temporary instantiated projectile model in the editor DestroyImmediate(projectileModel.gameObject); //if we created a prefab if (prefab) { //select it within the project panel Selection.activeGameObject = prefab; //close this editor window this.Close(); } } }
public void CopyFrom(tk2dSpriteCollectionDefinition src) { name = src.name; additive = src.additive; scale = src.scale; texture = src.texture; anchor = src.anchor; anchorX = src.anchorX; anchorY = src.anchorY; overrideMesh = src.overrideMesh; dice = src.dice; diceUnitX = src.diceUnitX; diceUnitY = src.diceUnitY; pad = src.pad; fromSpriteSheet = src.fromSpriteSheet; extractRegion = src.extractRegion; regionX = src.regionX; regionY = src.regionY; regionW = src.regionW; regionH = src.regionH; regionId = src.regionId; colliderType = src.colliderType; boxColliderMin = src.boxColliderMin; boxColliderMax = src.boxColliderMax; polyColliderCap = src.polyColliderCap; colliderColor = src.colliderColor; colliderConvex = src.colliderConvex; colliderSmoothSphereCollisions = src.colliderSmoothSphereCollisions; if (src.polyColliderIslands != null) { polyColliderIslands = new tk2dSpriteColliderIsland[src.polyColliderIslands.Length]; for (int i = 0; i < polyColliderIslands.Length; ++i) { polyColliderIslands[i] = new tk2dSpriteColliderIsland(); polyColliderIslands[i].CopyFrom(src.polyColliderIslands[i]); } } else { polyColliderIslands = null; } }
// ==== Voxel updates ===================================================================================== public void RebuildMesh() { if (!initialized) { Initialize(); } // destroy additional mesh containers foreach (Transform child in transform) { Destroy(child.gameObject); } int x = 0, y = 0, z = 0; // Refresh neighbor chunks chunk.GetNeighbors(); // for each voxel in Voxels, check if any of the voxel's faces are exposed, and if so, add their faces to the main mesh arrays (named Vertices and Faces) while (x < SideLength) { while (y < SideLength) { while (z < SideLength) { ushort voxel = chunk.GetVoxel(x, y, z); // the current voxel data if (voxel != 0) { // don't render empty blocks. Voxel voxelType = Engine.GetVoxelType(voxel); if (voxelType.VCustomMesh == false && voxelType.VCustomPrefab == false) { // if cube //Transparency transparency = Engine.GetVoxelType (chunk.GetVoxel(x,y,z)).VTransparency; Transparency transparency = voxelType.VTransparency; ColliderType colliderType = voxelType.VColliderType; if (CheckAdjacent(x, y, z, Direction.forward, transparency) == true) { CreateFace(voxel, Facing.forward, colliderType, x, y, z); } if (CheckAdjacent(x, y, z, Direction.back, transparency) == true) { CreateFace(voxel, Facing.back, colliderType, x, y, z); } if (CheckAdjacent(x, y, z, Direction.up, transparency) == true) { CreateFace(voxel, Facing.up, colliderType, x, y, z); } if (CheckAdjacent(x, y, z, Direction.down, transparency) == true) { CreateFace(voxel, Facing.down, colliderType, x, y, z); } if (CheckAdjacent(x, y, z, Direction.right, transparency) == true) { CreateFace(voxel, Facing.right, colliderType, x, y, z); } if (CheckAdjacent(x, y, z, Direction.left, transparency) == true) { CreateFace(voxel, Facing.left, colliderType, x, y, z); } // if no collider, create a trigger cube collider if (colliderType == ColliderType.none && Engine.GenerateColliders) { AddCubeMesh(x, y, z, false); } } else { // if not cube if (voxelType.VCustomMesh == true) { if (CheckAllAdjacent(x, y, z) == false) { // if any adjacent voxel isn't opaque, we render the mesh CreateCustomMesh(voxel, x, y, z, voxelType.VMesh); } } else if (voxelType.VCustomPrefab == true) { CreateCustomPrefab(voxel, x, y, z, voxelType.VPrefab); } } } z += 1; } z = 0; y += 1; } y = 0; x += 1; } // update mesh using the values from the arrays UpdateMesh(GetComponent <MeshFilter>().mesh); }
public void DeserializeSettings ( GraphSerializationContext ctx ) { type = (ColliderType)ctx.reader.ReadInt32(); diameter = ctx.reader.ReadSingle (); height = ctx.reader.ReadSingle (); collisionOffset = ctx.reader.ReadSingle (); rayDirection = (RayDirection)ctx.reader.ReadInt32 (); mask = (LayerMask)ctx.reader.ReadInt32 (); heightMask = (LayerMask)ctx.reader.ReadInt32 (); fromHeight = ctx.reader.ReadSingle (); thickRaycast = ctx.reader.ReadBoolean (); thickRaycastDiameter = ctx.reader.ReadSingle (); unwalkableWhenNoGround = ctx.reader.ReadBoolean(); use2D = ctx.reader.ReadBoolean(); collisionCheck = ctx.reader.ReadBoolean(); heightCheck = ctx.reader.ReadBoolean(); }
/// <summary> /// body初始化参数,初始化CapsuleCollider /// </summary> /// <param name="boneTrans">父节点</param> /// <param name="parentIndex">CharacterJoint连接点</param> /// <param name="axis">轴向</param> /// <param name="radius">半径</param> /// <param name="height">长度</param> private void InitBones(Transform boneTrans, ColliderType colliderType, int parentIndex, int axis, float radius, float height, Vector3 size) { var gameObj = boneTrans.gameObject; //Collider var collider = gameObj.GetComponent <Collider>(); if (collider == null) { if (colliderType == ColliderType.SPHERE) { collider = gameObj.AddComponent <SphereCollider>(); } if (colliderType == ColliderType.BOX) { collider = gameObj.AddComponent <BoxCollider>(); } if (colliderType == ColliderType.CAPSULE) { collider = gameObj.AddComponent <CapsuleCollider>(); } } if (colliderType == ColliderType.CAPSULE) { var tempCollider = collider as CapsuleCollider; tempCollider.direction = axis; tempCollider.radius = radius; tempCollider.height = height; } else if (colliderType == ColliderType.BOX) { var tempCollider = collider as BoxCollider; tempCollider.size = size; } else { var tempCollider = collider as SphereCollider; tempCollider.radius = 0.1f; } collider.enabled = false; //RigidBody var rigid = gameObj.GetComponent <Rigidbody>(); if (rigid == null) { rigid = gameObj.AddComponent <Rigidbody>(); } rigid.useGravity = false; rigid.isKinematic = true; //Joint if (parentIndex >= 0) { var joint = gameObj.GetComponent <CharacterJoint>(); if (joint == null) { joint = gameObj.AddComponent <CharacterJoint>(); } { joint.connectedBody = RagdollBones[parentIndex].GetComponent <Rigidbody>(); } } }
static void LoadPrefs() { pbStripProBuilderOnBuild = pb_Preferences_Internal.GetBool(pb_Constant.pbStripProBuilderOnBuild); pbDisableAutoUV2Generation = pb_Preferences_Internal.GetBool(pb_Constant.pbDisableAutoUV2Generation); pbShowSceneInfo = pb_Preferences_Internal.GetBool(pb_Constant.pbShowSceneInfo); pbEnableBackfaceSelection = pb_Preferences_Internal.GetBool(pb_Constant.pbEnableBackfaceSelection); defaultOpenInDockableWindow = pb_Preferences_Internal.GetBool(pb_Constant.pbDefaultOpenInDockableWindow); pbDragCheckLimit = pb_Preferences_Internal.GetBool(pb_Constant.pbDragCheckLimit); pbForceConvex = pb_Preferences_Internal.GetBool(pb_Constant.pbForceConvex); pbForceGridPivot = pb_Preferences_Internal.GetBool(pb_Constant.pbForceGridPivot); pbForceVertexPivot = pb_Preferences_Internal.GetBool(pb_Constant.pbForceVertexPivot); pbManifoldEdgeExtrusion = pb_Preferences_Internal.GetBool(pb_Constant.pbManifoldEdgeExtrusion); pbPerimeterEdgeBridgeOnly = pb_Preferences_Internal.GetBool(pb_Constant.pbPerimeterEdgeBridgeOnly); pbPBOSelectionOnly = pb_Preferences_Internal.GetBool(pb_Constant.pbPBOSelectionOnly); pbCloseShapeWindow = pb_Preferences_Internal.GetBool(pb_Constant.pbCloseShapeWindow); pbUVEditorFloating = pb_Preferences_Internal.GetBool(pb_Constant.pbUVEditorFloating); pbShowSceneToolbar = pb_Preferences_Internal.GetBool(pb_Constant.pbShowSceneToolbar); pbShowEditorNotifications = pb_Preferences_Internal.GetBool(pb_Constant.pbShowEditorNotifications); pbDefaultFaceColor = pb_Preferences_Internal.GetColor( pb_Constant.pbDefaultFaceColor ); pbDefaultEdgeColor = pb_Preferences_Internal.GetColor( pb_Constant.pbDefaultEdgeColor ); pbDefaultSelectedVertexColor = pb_Preferences_Internal.GetColor( pb_Constant.pbDefaultSelectedVertexColor ); pbDefaultVertexColor = pb_Preferences_Internal.GetColor( pb_Constant.pbDefaultVertexColor ); pbUVGridSnapValue = pb_Preferences_Internal.GetFloat(pb_Constant.pbUVGridSnapValue); pbVertexHandleSize = pb_Preferences_Internal.GetFloat(pb_Constant.pbVertexHandleSize); defaultColliderType = pb_Preferences_Internal.GetEnum<ColliderType>(pb_Constant.pbDefaultCollider); pbToolbarLocation = pb_Preferences_Internal.GetEnum<SceneToolbarLocation>(pb_Constant.pbToolbarLocation); pbDefaultMaterial = pb_Preferences_Internal.GetMaterial(pb_Constant.pbDefaultMaterial); defaultShortcuts = EditorPrefs.HasKey(pb_Constant.pbDefaultShortcuts) ? pb_Shortcut.ParseShortcuts(EditorPrefs.GetString(pb_Constant.pbDefaultShortcuts)) : pb_Shortcut.DefaultShortcuts(); }
public static BlobAssetReference <Collider> CreateCollider(UnityEngine.Mesh mesh, ColliderType type) { switch (type) { case ColliderType.Sphere: { Bounds bounds = mesh.bounds; return(SphereCollider.Create(new SphereGeometry { Center = bounds.center, Radius = math.cmax(bounds.extents) })); } case ColliderType.Triangle: { return(PolygonCollider.CreateTriangle(mesh.vertices[0], mesh.vertices[1], mesh.vertices[2])); } case ColliderType.Quad: { // We assume the first 2 triangles of the mesh are a quad with a shared edge // Work out a correct ordering for the triangle int[] orderedIndices = new int[4]; // Find the vertex in first triangle that is not on the shared edge for (int i = 0; i < 3; i++) { if ((mesh.triangles[i] != mesh.triangles[3]) && (mesh.triangles[i] != mesh.triangles[4]) && (mesh.triangles[i] != mesh.triangles[5])) { // Push in order or prev, unique, next orderedIndices[0] = mesh.triangles[(i - 1 + 3) % 3]; orderedIndices[1] = mesh.triangles[i]; orderedIndices[2] = mesh.triangles[(i + 1) % 3]; break; } } // Find the vertex in second triangle that is not on a shared edge for (int i = 3; i < 6; i++) { if ((mesh.triangles[i] != orderedIndices[0]) && (mesh.triangles[i] != orderedIndices[1]) && (mesh.triangles[i] != orderedIndices[2])) { orderedIndices[3] = mesh.triangles[i]; break; } } return(PolygonCollider.CreateQuad( mesh.vertices[orderedIndices[0]], mesh.vertices[orderedIndices[1]], mesh.vertices[orderedIndices[2]], mesh.vertices[orderedIndices[3]])); } case ColliderType.Box: { Bounds bounds = mesh.bounds; return(BoxCollider.Create(new BoxGeometry { Center = bounds.center, Orientation = quaternion.identity, Size = 2.0f * bounds.extents, BevelRadius = 0.0f })); } case ColliderType.Capsule: { Bounds bounds = mesh.bounds; float min = math.cmin(bounds.extents); float max = math.cmax(bounds.extents); int x = math.select(math.select(2, 1, min == bounds.extents.y), 0, min == bounds.extents.x); int z = math.select(math.select(2, 1, max == bounds.extents.y), 0, max == bounds.extents.x); int y = math.select(math.select(2, 1, (1 != x) && (1 != z)), 0, (0 != x) && (0 != z)); float radius = bounds.extents[y]; float3 vertex0 = bounds.center; vertex0[z] = -(max - radius); float3 vertex1 = bounds.center; vertex1[z] = (max - radius); return(CapsuleCollider.Create(new CapsuleGeometry { Vertex0 = vertex0, Vertex1 = vertex1, Radius = radius })); } case ColliderType.Cylinder: // TODO: need someone to add throw new NotImplementedException(); case ColliderType.Convex: { NativeArray <float3> points = new NativeArray <float3>(mesh.vertices.Length, Allocator.TempJob); for (int i = 0; i < mesh.vertices.Length; i++) { points[i] = mesh.vertices[i]; } BlobAssetReference <Collider> collider = ConvexCollider.Create(points, default, CollisionFilter.Default); points.Dispose(); return(collider); }
private async Task <IList <UnityEngine.Object> > LoadGltfFromStream(WebRequestLoader loader, Stream stream, ColliderType colliderType) { var assets = new List <UnityEngine.Object>(30); // pre-parse glTF document so we can get a scene count // run this on a threadpool thread so that the Unity main thread is not blocked GLTF.Schema.GLTFRoot gltfRoot = null; try { await Task.Run(() => { GLTF.GLTFParser.ParseJson(stream, out gltfRoot); }); } catch (Exception e) { Debug.LogError(e); } if (gltfRoot == null) { throw new GLTFLoadException("Failed to parse glTF"); } stream.Position = 0; using (GLTFSceneImporter importer = MREAPI.AppsAPI.GLTFImporterFactory.CreateImporter(gltfRoot, loader, _asyncHelper, stream)) { importer.SceneParent = MREAPI.AppsAPI.AssetCache.CacheRootGO.transform; importer.Collider = colliderType.ToGLTFColliderType(); // load textures if (gltfRoot.Textures != null) { for (var i = 0; i < gltfRoot.Textures.Count; i++) { await importer.LoadTextureAsync(gltfRoot.Textures[i], i, true); var texture = importer.GetTexture(i); texture.name = gltfRoot.Textures[i].Name ?? $"texture:{i}"; assets.Add(texture); } } // load meshes if (gltfRoot.Meshes != null) { var cancellationSource = new System.Threading.CancellationTokenSource(); for (var i = 0; i < gltfRoot.Meshes.Count; i++) { var mesh = await importer.LoadMeshAsync(i, cancellationSource.Token); mesh.name = gltfRoot.Meshes[i].Name ?? $"mesh:{i}"; assets.Add(mesh); } } // load materials if (gltfRoot.Materials != null) { for (var i = 0; i < gltfRoot.Materials.Count; i++) { var matdef = gltfRoot.Materials[i]; var material = await importer.LoadMaterialAsync(i); material.name = matdef.Name ?? $"material:{i}"; assets.Add(material); } } // load prefabs if (gltfRoot.Scenes != null) { for (var i = 0; i < gltfRoot.Scenes.Count; i++) { await importer.LoadSceneAsync(i).ConfigureAwait(true); GameObject rootObject = importer.LastLoadedScene; rootObject.name = gltfRoot.Scenes[i].Name ?? $"scene:{i}"; var animation = rootObject.GetComponent <UnityEngine.Animation>(); if (animation != null) { animation.playAutomatically = false; // initialize mapping so we know which gameobjects are targeted by which animation clips var mapping = rootObject.AddComponent <PrefabAnimationTargets>(); mapping.Initialize(gltfRoot, i); } MWGOTreeWalker.VisitTree(rootObject, (go) => { go.layer = MREAPI.AppsAPI.LayerApplicator.DefaultLayer; }); assets.Add(rootObject); } } } return(assets); }
public void Draw(int x, int y, int width, int height, TileImg tileImg) { int layer = 0; this.width = 0; this.height = 0; string imageName = null; Texture2D texture = null; Color color = Color.white; ColliderType colliderType = ColliderType.None; TileType tileType = TileType.None; // 타일 이미지의 정보를 받아옴 if (tileImg != null && tileImg.texture != null) { tileType = tileImg.tileType; colliderType = tileImg.colliderType; color = tileImg.color; this.width = (int)tileImg.sprite.textureRect.width; this.height = (int)tileImg.sprite.textureRect.height; imageName = tileImg.sprite.name; texture = tileImg.texture; } GUILayout.BeginArea(new Rect(x, y, width, height), EditorStyles.textField); #region 이미지의 사이즈 출력 GUILayout.BeginHorizontal(); GUILayout.Box("Width: " + this.width); //EditorGUILayout.IntField("", this.width, EditorStyles.numberField, // GUILayout.MinWidth(30), GUILayout.MaxWidth(40), GUILayout.MinHeight(22)); GUILayout.Box("Height: " + this.height); //EditorGUILayout.IntField("", this.height, EditorStyles.numberField, // GUILayout.MinWidth(30), GUILayout.MaxWidth(40), GUILayout.MinHeight(22)); GUILayout.EndHorizontal(); #endregion #region 이미지 출력 GUILayout.BeginHorizontal(); GUILayout.Label("Image :"); GUILayout.Button(texture, GUILayout.Width(100), GUILayout.Height(100)); GUILayout.EndHorizontal(); #endregion GUILayout.Label("Image Name: " + imageName); layer = tileImg != null ? tileImg.layerOrder : 0; GUILayout.Label("Layer Order: " + layer); GUILayout.BeginHorizontal(); if (GUILayout.Button("<", GUILayout.Width(93))) { if (tileImg != null) { tileImg.layerOrder--; } } if (GUILayout.Button(">", GUILayout.Width(93))) { if (tileImg != null) { tileImg.layerOrder++; } } GUILayout.EndHorizontal(); color = EditorGUILayout.ColorField(color); GUILayout.Label("Collider Type"); colliderType = (ColliderType)EditorGUILayout.EnumPopup(colliderType); GUILayout.Label("Tile Type"); tileType = (TileType)EditorGUILayout.EnumPopup(tileType); if (tileImg != null) { tileImg.color = color; tileImg.colliderType = colliderType; tileImg.tileType = tileType; } GUILayout.EndArea(); }
public static bool IsLandLike(this ColliderType t) => t == ColliderType.Land || t == ColliderType.NeedleLike || t == ColliderType.PoisonLike;
/// <summary> /// Gets the default sub layer properties for the chosen preset type. /// </summary> /// <returns>The sub layer properties.</returns> /// <param name="type">Type.</param> public static VectorSubLayerProperties GetSubLayerProperties(PresetFeatureType type) { //CoreOptions properties VectorPrimitiveType geometryType = VectorPrimitiveType.Polygon; string layerName = "building"; string sublayerName = "Untitled"; //Line Geometry Options float lineWidth = 1.0f; //Geometry Extrusion Options ExtrusionType extrusionType = ExtrusionType.None; ExtrusionGeometryType extrusionGeometryType = ExtrusionGeometryType.RoofAndSide; string propertyName = "height"; float extrusionScaleFactor = 1.0f; float extrusionHeight = 1.0f; //Filter Options LayerFilterCombinerOperationType combinerType = LayerFilterCombinerOperationType.Any; List <LayerFilter> filters = new List <LayerFilter>(); // Material Options StyleTypes style = StyleTypes.Realistic; //Misc options bool buildingsWithUniqueIds = true; PositionTargetType positionTargetType = PositionTargetType.TileCenter; //Modifiers List <MeshModifier> meshModifiers = new List <MeshModifier>(); List <GameObjectModifier> gameObjectModifiers = new List <GameObjectModifier>(); ColliderType colliderType = ColliderType.None; switch (type) { case PresetFeatureType.Buildings: layerName = "building"; geometryType = VectorPrimitiveType.Polygon; extrusionType = ExtrusionType.PropertyHeight; extrusionGeometryType = ExtrusionGeometryType.RoofAndSide; propertyName = "height"; style = StyleTypes.Realistic; break; case PresetFeatureType.Roads: layerName = "road"; geometryType = VectorPrimitiveType.Line; lineWidth = 1.0f; style = StyleTypes.Dark; extrusionType = ExtrusionType.AbsoluteHeight; extrusionGeometryType = ExtrusionGeometryType.RoofAndSide; break; case PresetFeatureType.Points: layerName = "poi_label"; geometryType = VectorPrimitiveType.Point; break; case PresetFeatureType.Landuse: layerName = "landuse"; geometryType = VectorPrimitiveType.Polygon; style = StyleTypes.Color; break; case PresetFeatureType.Custom: layerName = ""; geometryType = VectorPrimitiveType.Custom; style = StyleTypes.Custom; break; default: break; } VectorSubLayerProperties _properties = new VectorSubLayerProperties(); _properties.presetFeatureType = type; _properties.coreOptions = new CoreVectorLayerProperties { isActive = true, layerName = layerName, geometryType = geometryType, snapToTerrain = true, combineMeshes = false, sublayerName = sublayerName }; _properties.lineGeometryOptions = new LineGeometryOptions { Width = lineWidth }; _properties.extrusionOptions = new GeometryExtrusionOptions { extrusionType = extrusionType, extrusionGeometryType = extrusionGeometryType, propertyName = propertyName, extrusionScaleFactor = extrusionScaleFactor, maximumHeight = extrusionHeight }; _properties.filterOptions = new VectorFilterOptions { combinerType = combinerType, filters = filters }; _properties.materialOptions = new GeometryMaterialOptions { style = style, colorStyleColor = Constants.GUI.Colors.EDITOR_FEATURE_DEFAULT_COLOR }; _properties.materialOptions.SetDefaultMaterialOptions(); _properties.buildingsWithUniqueIds = buildingsWithUniqueIds; _properties.moveFeaturePositionTo = positionTargetType; _properties.MeshModifiers = meshModifiers; _properties.GoModifiers = gameObjectModifiers; _properties.colliderOptions = new ColliderOptions { colliderType = colliderType }; return(_properties); }
public static void Create(BlobBuilder builder, HitCircle src, ref BlobPtr <Collider> dest, ColliderType type = ColliderType.Circle) { ref var ptr = ref UnsafeUtilityEx.As <BlobPtr <Collider>, BlobPtr <CircleCollider> >(ref dest);
public virtual void DrawEditorGUITwo() { serializedObject.Update(); if (tar.GetComponent <MeshLink>() != null) { hasMeshLink = true; } else { hasMeshLink = false; } EditorGUILayout.BeginHorizontal(); SerializedProperty eMeshLink = serializedObject.FindProperty("meshLink"); GUIStyle meshStyle = new GUIStyle(EditorStyles.popup); if (eMeshLink.prefabOverride) { meshStyle.fontStyle = FontStyle.Bold; } meshLinkType = (MeshLink.MeshLinkType)EditorGUILayout.EnumPopup(meshLinkTypeContent, meshLinkType, meshStyle); bool showChangeButton = false; if (hasMeshLink) { if (tar.GetComponent <MeshLink>().meshLinkType != meshLinkType) { showChangeButton = true; } } else if (meshLinkType != MeshLink.MeshLinkType.None) { showChangeButton = true; } if (showChangeButton) { if (GUILayout.Button(changeTypeContent, EditorStyles.miniButton)) { for (int i = 0; i < serializedObject.targetObjects.Length; i++) { ChangeMeshLink((JelloBody)serializedObject.targetObjects[i]); } } } EditorGUILayout.EndHorizontal(); colliderType = (ColliderType)EditorGUILayout.EnumPopup(bodyTypeContent, colliderType, EditorStyles.miniButton); EditorGUILayout.BeginHorizontal(); if (CompareEnumStateWithType(tar)) { EditorGUI.indentLevel++; if (GUILayout.Button(new GUIContent(changeTypeContent), EditorStyles.miniButton)) //todo make this change all targets { JelloBody[] oldTargets = new JelloBody[targets.Length]; for (int i = 0; i < serializedObject.targetObjects.Length; i++) { JelloBody t = (JelloBody)serializedObject.targetObjects[i]; ChangeBodyType(t, retainBodyInformation); oldTargets[i] = t; } for (int i = 0; i < oldTargets.Length; i++) { Undo.DestroyObjectImmediate(oldTargets[i]); } return; } retainBodyInformation = EditorGUILayout.Toggle(keepInfoContent, retainBodyInformation); EditorGUI.indentLevel--; } EditorGUILayout.EndHorizontal(); EditorGUILayout.Separator(); EditorGUILayout.Separator(); EditorGUILayout.BeginHorizontal(); string[] options = new string[subEditors.Count]; for (int i = 0; i < options.Length; i++) { options[i] = subEditors[i].name; } currentSubEditor = EditorGUILayout.Popup("SubComponent", currentSubEditor, options); EditorGUILayout.EndHorizontal(); subEditors[currentSubEditor].DrawEditorGUI(); serializedObject.ApplyModifiedProperties(); }
internal async Task <IList <Actor> > CreateFromGLTF(string resourceUrl, string assetName, Guid?parentId, ColliderType colliderType) { UtilMethods.GetUrlParts(resourceUrl, out string rootUrl, out string filename); var loader = new WebRequestLoader(rootUrl); var importer = MREAPI.AppsAPI.GLTFImporterFactory.CreateImporter(filename, loader, _asyncHelper); var parent = _app.FindActor(parentId ?? Guid.Empty) as Actor; importer.SceneParent = parent?.transform ?? _app.SceneRoot.transform; importer.Collider = colliderType.ToGLTFColliderType(); await importer.LoadSceneAsync().ConfigureAwait(true); // note: actor properties are set in App#ProcessCreatedActors IList <Actor> actors = new List <Actor>(); importer.LastLoadedScene.name = assetName; MWGOTreeWalker.VisitTree(importer.LastLoadedScene, (go) => { go.layer = UnityConstants.ActorLayerIndex; actors.Add(go.AddComponent <Actor>()); }); importer.Dispose(); return(actors); }
// Slower CreateFromCollider public static List <Polygon2D> CreateFromGameObject(GameObject gameObject) { ColliderType colliderType = GetColliderType(gameObject); return(CreateFromGameObject(gameObject, colliderType)); }
public BoxCollider CreateBoxCollider(int width, int height, int mass, ColliderType type) { return(new BoxCollider(this, Vector2.Zero, width, height, mass, type)); }
public static GameObject CreateChildCollider(GameObject forObject, bool forPosition, Vector3?newPivotPos, Quaternion?newPivotRot) { string colliderName = ""; var colliders = forObject.GetComponents <Collider>(); if (colliders == null || colliders.Length == 0) { return(null); } #region Setting name of the child collider and disabling original colliders ColliderType lastType = ColliderType.None; foreach (Collider collider in colliders) { ColliderType currentType; //collider.enabled = false; if (collider is BoxCollider) { currentType = ColliderType.BoxCollider; colliderName = forObject.name + "_" + Enum.GetName(typeof(ColliderType), currentType); if (lastType != ColliderType.None) { if (lastType != currentType) { colliderName = forObject.name + "_MixedColliders"; break; } else { colliderName = forObject.name + "_" + Enum.GetName(typeof(ColliderType), currentType) + "s"; } } lastType = currentType; } else if (collider is CapsuleCollider) { currentType = ColliderType.CapsuleCollider; colliderName = forObject.name + "_" + Enum.GetName(typeof(ColliderType), currentType); if (lastType != ColliderType.None) { if (lastType != currentType) { colliderName = forObject.name + "_MixedColliders"; break; } else { colliderName = forObject.name + "_" + Enum.GetName(typeof(ColliderType), currentType) + "s"; } } lastType = currentType; } else if (collider is SphereCollider) { currentType = ColliderType.SphereCollider; colliderName = forObject.name + "_" + Enum.GetName(typeof(ColliderType), currentType); if (lastType != ColliderType.None) { if (lastType != currentType) { colliderName = forObject.name + "_MixedColliders"; break; } else { colliderName = forObject.name + "_" + Enum.GetName(typeof(ColliderType), currentType) + "s"; } } lastType = currentType; } else if (collider is MeshCollider) { currentType = ColliderType.MeshCollider; colliderName = forObject.name + "_" + Enum.GetName(typeof(ColliderType), currentType); if (lastType != ColliderType.None) { if (lastType != currentType) { colliderName = forObject.name + "_MixedColliders"; break; } else { colliderName = forObject.name + "_" + Enum.GetName(typeof(ColliderType), currentType) + "s"; } } lastType = currentType; } } #endregion Setting name of the child collider and disabling original colliders colliderName = "**" + colliderName + "_DON'T DELETE**"; GameObject childCollider = UtilityServices.DuplicateGameObject(forObject, colliderName, false, false); foreach (Component component in childCollider.GetComponents <Component>()) { if (component is Transform || component is Collider) { continue; } DestroyImmediate(component); } foreach (Collider collider in forObject.GetComponents <Collider>()) { if (collider.enabled && forPosition) { collider.enabled = true; } else { collider.enabled = false; } } childCollider.transform.parent = forObject.transform; childCollider.AddComponent <CollRecognize>(); Collider coll = forObject.GetComponent <Collider>(); if (coll && coll is MeshCollider) { if (newPivotPos != null) { //childCollider.transform.position = (Vector3)newPivotPos; } else if (newPivotRot != null) { //childCollider.transform.rotation = (Quaternion)newPivotRot; } } return(childCollider); }
public CircleCollider CreateCircleCollider(Vector2 position, int radius, int mass, ColliderType type) { return(new CircleCollider(this, position, radius, mass, type)); }
public static SuicideObject CreatePhysics2DSuicideObject(GameObject origin, float suicideT = 15f, ColliderType collider = ColliderType.Capsule2D) { SuicideObject so = new SuicideObject(); so.gameObject = CreateSuicideObject(origin, suicideT); so.rigidbody2D = so.gameObject.AddComponent <Rigidbody2D>(); switch (collider) { case ColliderType.Box2D: so.collider2D = so.gameObject.AddComponent <BoxCollider2D>(); break; case ColliderType.Capsule2D: so.collider2D = so.gameObject.AddComponent <CapsuleCollider2D>(); break; } return(so); }
void OnSceneGUI() { if (MoreThanOne) { return; } //Have to reinitialize everything because can't apply modified properties on base.serializedObject SerializedObject so = new SerializedObject(target); so.Update(); SerializedProperty Shape = so.FindProperty("_shape"); SerializedProperty IsTrigger = so.FindProperty("_isTrigger"); SerializedProperty Layer = so.FindProperty("_layer"); SerializedProperty HalfWidth = so.FindProperty("_halfWidth"); SerializedProperty HalfHeight = so.FindProperty("_halfHeight"); SerializedProperty Radius = so.FindProperty("_radius"); SerializedProperty Immovable = so.FindProperty("_immovable"); SerializedProperty Vertices = so.FindProperty("_vertices"); SerializedProperty Height = so.FindProperty("_height"); SerializedProperty PositionalTransform = so.FindProperty("_positionalTransform"); SerializedProperty RotationalTransform = so.FindProperty("_rotationalTransform"); ColliderType shape = (ColliderType)Shape.intValue; if (shape == ColliderType.None) { return; } Handles.color = Color.blue; LSBody Body = (LSBody)target; Vector3 targetPos = Body.transform.position; const int ImprecisionLimit = 100000; if (Mathf.Abs(targetPos.x) >= ImprecisionLimit || Mathf.Abs(targetPos.y) >= ImprecisionLimit || Mathf.Abs(targetPos.z) >= ImprecisionLimit) { return; } const float spread = .02f; int spreadMin = -1; int spreadMax = 1; Handles.DrawCapFunction dragCap = Handles.SphereCap; float height = targetPos.y; float xModifier = 0f; if (shape == ColliderType.Circle) { //Minus so the move handle doesn't end up on the same axis as the transform.position move handle float oldRadius = Radius.longValue.ToFloat(); float newRadius = Mathf.Abs( (Handles.FreeMoveHandle( new Vector3(targetPos.x - Radius.longValue.ToFloat(), targetPos.y, targetPos.z) , Quaternion.identity, MoveHandleSize, Vector3.zero, Handles.SphereCap)) .x - targetPos.x); if (Mathf.Abs(oldRadius - newRadius) >= .02f) { Radius.longValue = FixedMath.Create(newRadius); } Handles.DrawLine(targetPos, new Vector3(targetPos.x + Radius.longValue.ToFloat(), targetPos.y, targetPos.z)); float baseHeight = targetPos.y; for (int i = spreadMin; i <= spreadMax; i++) { Handles.CircleCap( 1, new Vector3(targetPos.x, baseHeight + (float)i * spread, targetPos.z) , Quaternion.Euler(90, 0, 0), Radius.longValue.ToFloat()); } baseHeight = targetPos.y + Height.longValue.ToFloat(); for (int i = spreadMin; i <= spreadMax; i++) { Handles.CircleCap( 1, new Vector3(targetPos.x, baseHeight + (float)i * spread, targetPos.z) , Quaternion.Euler(90, 0, 0), Radius.longValue.ToFloat()); } xModifier = 0;//Radius.longValue.ToFloat(); } else if (shape == ColliderType.AABox) { float oldWidth = HalfWidth.longValue.ToFloat(); float newWidth = Mathf.Abs( Handles.FreeMoveHandle( new Vector3(targetPos.x - (float)HalfWidth.longValue.ToFormattedDouble(), targetPos.y, targetPos.z), Quaternion.identity, MoveHandleSize, Vector3.zero, dragCap) .x - targetPos.x); if (Mathf.Abs(newWidth - oldWidth) >= .02f) { HalfWidth.longValue = FixedMath.Create(newWidth); } float oldHeight = HalfHeight.longValue.ToFloat(); float newHeight = System.Math.Abs( Handles.FreeMoveHandle( new Vector3(targetPos.x, targetPos.y, targetPos.z - (float)HalfHeight.longValue.ToFormattedDouble()), Quaternion.identity, MoveHandleSize, Vector3.zero, dragCap) .z - targetPos.z); if (Mathf.Abs(newHeight - oldHeight) >= .02f) { HalfHeight.longValue = FixedMath.Create(newHeight); } float halfWidth = HalfWidth.longValue.ToFloat(); float halfHeight = HalfHeight.longValue.ToFloat(); for (int i = 0; i < 1; i++) { height = targetPos.y + (float)i * spread; Vector3[] lines = new Vector3[] { new Vector3(targetPos.x + halfWidth, height, targetPos.z + halfHeight), new Vector3(targetPos.x + halfWidth, height, targetPos.z - halfHeight), new Vector3(targetPos.x + halfWidth, height, targetPos.z - halfHeight), new Vector3(targetPos.x - halfWidth, height, targetPos.z - halfHeight), new Vector3(targetPos.x - halfWidth, height, targetPos.z - halfHeight), new Vector3(targetPos.x - halfWidth, height, targetPos.z + halfHeight), new Vector3(targetPos.x - halfWidth, height, targetPos.z + halfHeight), new Vector3(targetPos.x + halfWidth, height, targetPos.z + halfHeight) }; Handles.DrawPolyLine(lines); } for (int i = 0; i < 1; i++) { height = targetPos.y + (float)i * spread + Height.longValue.ToFloat(); Vector3[] lines = new Vector3[] { new Vector3(targetPos.x + halfWidth, height, targetPos.z + halfHeight), new Vector3(targetPos.x + halfWidth, height, targetPos.z - halfHeight), new Vector3(targetPos.x + halfWidth, height, targetPos.z - halfHeight), new Vector3(targetPos.x - halfWidth, height, targetPos.z - halfHeight), new Vector3(targetPos.x - halfWidth, height, targetPos.z - halfHeight), new Vector3(targetPos.x - halfWidth, height, targetPos.z + halfHeight), new Vector3(targetPos.x - halfWidth, height, targetPos.z + halfHeight), new Vector3(targetPos.x + halfWidth, height, targetPos.z + halfHeight) }; Handles.DrawPolyLine(lines); } xModifier = 0;//halfWidth; } else if (shape == ColliderType.Polygon) { float yRot = Body.transform.eulerAngles.y * Mathf.Deg2Rad; Vector2d rotation = Vector2d.CreateRotation(yRot); bool changed = false; Vector3[] draws = new Vector3[Body.Vertices.Length + 1]; for (int i = 0; i < Body.Vertices.Length; i++) { Vector2d vertex = Body.Vertices [i]; vertex.Rotate(rotation.x, rotation.y); Vector3 drawPos = vertex.ToVector3() + targetPos; Vector3 newDrawPos = Handles.FreeMoveHandle(drawPos, Quaternion.identity, MoveHandleSize, new Vector3(0, float.PositiveInfinity, 0), Handles.SphereCap); if ((newDrawPos - (drawPos)).magnitude >= .01f) { newDrawPos -= targetPos; vertex = new Vector2d(newDrawPos); vertex.RotateInverse(rotation.x, rotation.y); Body.Vertices [i] = vertex; changed = true; } draws[i] = drawPos; Handles.Label(drawPos, "V: " + i.ToString(), LabelStyle); } if (Body.Vertices.Length > 0) { draws[draws.Length - 1] = draws[0]; Handles.DrawPolyLine(draws); for (int i = 0; i < draws.Length; i++) { Vector3 highPos = draws[i]; highPos.y += Body.Height.ToFloat(); Handles.DrawLine(draws[i], highPos); draws[i] = highPos; } Handles.DrawPolyLine(draws); } if (changed) { so.Update(); } } Handles.DrawLine( new Vector3(targetPos.x + xModifier, targetPos.y, targetPos.z), new Vector3(targetPos.x + xModifier, targetPos.y + Height.longValue.ToFloat(), targetPos.z)); Vector3 movePos = targetPos; movePos.x += xModifier; movePos.y += (float)Height.longValue.ToFormattedDouble(); Vector3 lastMovePos = movePos; movePos = Handles.FreeMoveHandle( movePos, Quaternion.identity, MoveHandleSize, Vector3.zero, dragCap ); if ((lastMovePos - movePos).sqrMagnitude >= .1f) { Height.longValue = FixedMath.Create(Mathf.Max(Mathf.Abs(movePos.y - targetPos.y))); } so.ApplyModifiedProperties(); }
private BlobAssetReference <Collider> CreateCollider(UnityEngine.Mesh mesh, ColliderType type) { switch (type) { case ColliderType.Sphere: { Bounds bounds = mesh.bounds; return(SphereCollider.Create(bounds.center, math.cmax(bounds.extents))); } case ColliderType.Triangle: { return(PolygonCollider.CreateTriangle(mesh.vertices[0], mesh.vertices[1], mesh.vertices[2])); } case ColliderType.Quad: { // We assume the first 2 triangles of the mesh are a quad with a shared edge // Work out a correct ordering for the triangle int[] orderedIndices = new int[4]; // Find the vertex in first triangle that is not on the shared edge for (int i = 0; i < 3; i++) { if ((mesh.triangles[i] != mesh.triangles[3]) && (mesh.triangles[i] != mesh.triangles[4]) && (mesh.triangles[i] != mesh.triangles[5])) { // Push in order or prev, unique, next orderedIndices[0] = mesh.triangles[(i - 1 + 3) % 3]; orderedIndices[1] = mesh.triangles[i]; orderedIndices[2] = mesh.triangles[(i + 1) % 3]; break; } } // Find the vertex in second triangle that is not on a shared edge for (int i = 3; i < 6; i++) { if ((mesh.triangles[i] != orderedIndices[0]) && (mesh.triangles[i] != orderedIndices[1]) && (mesh.triangles[i] != orderedIndices[2])) { orderedIndices[3] = mesh.triangles[i]; break; } } return(PolygonCollider.CreateQuad( mesh.vertices[orderedIndices[0]], mesh.vertices[orderedIndices[1]], mesh.vertices[orderedIndices[2]], mesh.vertices[orderedIndices[3]])); } case ColliderType.Box: { Bounds bounds = mesh.bounds; return(BoxCollider.Create(bounds.center, quaternion.identity, 2.0f * bounds.extents, 0.0f)); } case ColliderType.Capsule: { Bounds bounds = mesh.bounds; float min = math.cmin(bounds.extents); float max = math.cmax(bounds.extents); int x = math.select(math.select(2, 1, min == bounds.extents.y), 0, min == bounds.extents.x); int z = math.select(math.select(2, 1, max == bounds.extents.y), 0, max == bounds.extents.x); int y = math.select(math.select(2, 1, (1 != x) && (1 != z)), 0, (0 != x) && (0 != z)); float radius = bounds.extents[y]; float3 vertex0 = bounds.center; vertex0[z] = -(max - radius); float3 vertex1 = bounds.center; vertex1[z] = (max - radius); return(CapsuleCollider.Create(vertex0, vertex1, radius)); } case ColliderType.Convex: { NativeArray <float3> points = new NativeArray <float3>(mesh.vertices.Length, Allocator.Temp); for (int i = 0; i < mesh.vertices.Length; i++) { points[i] = mesh.vertices[i]; } return(ConvexCollider.Create(points, 0.0f)); } default: throw new System.NotImplementedException(); } }
public void setCollider(ColliderType t) { this.m_type = t; }
/// <summary> /// Step 5: Process the collider section /// </summary> /// <param name="raw"></param> internal void ProcessColliders(Section raw) { if (raw.ID != SectionType.STL_ATTRIBUTE) { throw new ArgumentException("ERROR: Non-collider section passed to ProcessColliders", "raw"); } using (var reader = new BinaryReader(new MemoryStream(raw.Data))) { uint ColliderCount = reader.ReadUInt32(); for (uint i = 0; i < ColliderCount; i++) { uint tempID = reader.ReadUInt32(); ColliderType ct = (ColliderType)reader.ReadUInt16(); switch (ct) { case ColliderType.BOX_COLLIDER: var box = new BoxCollider { Meta = new ColliderMeta(ct, tempID), Scale = new Other.Vec3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()), Friction = reader.ReadSingle(), IsDynamic = reader.ReadBoolean() }; if (box.IsDynamic) { box.Mass = reader.ReadSingle(); } Field.Colliders.Add(box); break; case ColliderType.SPHERE_COLLIDER: var sphere = new SphereCollider { Meta = new ColliderMeta(ct, tempID), Scale = reader.ReadSingle(), Friction = reader.ReadSingle(), IsDynamic = reader.ReadBoolean() }; if (sphere.IsDynamic) { sphere.Mass = reader.ReadSingle(); } Field.Colliders.Add(sphere); break; case ColliderType.MESH_COLLIDER: var mesh = new MeshCollider { Meta = new ColliderMeta(ct, tempID), Friction = reader.ReadSingle(), IsDynamic = reader.ReadBoolean() }; if (mesh.IsDynamic) { mesh.Mass = reader.ReadSingle(); } Field.Colliders.Add(mesh); break; default: throw new Exception("ERROR: Unknown or bad collider type"); } } } }
public static void PreferencesGUI() { // Load the preferences if (!prefsLoaded) { LoadPrefs(); prefsLoaded = true; OnWindowResize(); } settingsScroll = EditorGUILayout.BeginScrollView(settingsScroll, GUILayout.MaxHeight(200)); EditorGUI.BeginChangeCheck(); /** * GENERAL SETTINGS */ GUILayout.Label("General Settings", EditorStyles.boldLabel); pbStripProBuilderOnBuild = EditorGUILayout.Toggle(new GUIContent("Strip PB Scripts on Build", "If true, when building an executable all ProBuilder scripts will be stripped from your built product."), pbStripProBuilderOnBuild); pbDisableAutoUV2Generation = EditorGUILayout.Toggle(new GUIContent("Disable Auto UV2 Generation", "Disables automatic generation of UV2 channel. If Unity is sluggish when working with large ProBuilder objects, disabling UV2 generation will improve performance. Use `Actions/Generate UV2` or `Actions/Generate Scene UV2` to build lightmap UVs prior to baking."), pbDisableAutoUV2Generation); pbShowSceneInfo = EditorGUILayout.Toggle(new GUIContent("Show Scene Info", "Displays the selected object vertex and triangle counts in the scene view."), pbShowSceneInfo); pbShowEditorNotifications = EditorGUILayout.Toggle("Show Editor Notifications", pbShowEditorNotifications); pbEnableBackfaceSelection = EditorGUILayout.Toggle(new GUIContent("Enable Back-face Selection", "If enabled, you may select faces that have been culled by their back face."), pbEnableBackfaceSelection); /** * TOOLBAR SETTINGS */ GUILayout.Label("Toolbar Settings", EditorStyles.boldLabel); pbIconGUI = EditorGUILayout.Toggle(new GUIContent("Use Icon GUI", "Toggles the ProBuilder window interface between text and icon versions."), pbIconGUI); pbShiftOnlyTooltips = EditorGUILayout.Toggle(new GUIContent("Shift Key Tooltips", "Tooltips will only show when the Shift key is held"), pbShiftOnlyTooltips); pbToolbarLocation = (SceneToolbarLocation)EditorGUILayout.EnumPopup("Toolbar Location", pbToolbarLocation); pbUniqueModeShortcuts = EditorGUILayout.Toggle(new GUIContent("Unique Mode Shortcuts", "When off, the G key toggles between Object and Element modes and H enumerates the element modes. If on, G, H, J, and K are shortcuts to Object, Vertex, Edge, and Face modes respectively."), pbUniqueModeShortcuts); defaultOpenInDockableWindow = EditorGUILayout.Toggle("Open in Dockable Window", defaultOpenInDockableWindow); /** * DEFAULT SETTINGS */ GUILayout.Label("Defaults", EditorStyles.boldLabel); pbDefaultMaterial = (Material)EditorGUILayout.ObjectField("Default Material", pbDefaultMaterial, typeof(Material), false); GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Default Entity"); pbDefaultEntity = ((EntityType)EditorGUILayout.EnumPopup((EntityType)pbDefaultEntity)); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Default Collider"); defaultColliderType = ((ColliderType)EditorGUILayout.EnumPopup((ColliderType)defaultColliderType)); GUILayout.EndHorizontal(); if ((ColliderType)defaultColliderType == ColliderType.MeshCollider) { pbForceConvex = EditorGUILayout.Toggle("Force Convex Mesh Collider", pbForceConvex); } /** * MISC. SETTINGS */ GUILayout.Label("Misc. Settings", EditorStyles.boldLabel); pbDragCheckLimit = EditorGUILayout.Toggle(new GUIContent("Limit Drag Check to Selection", "If true, when drag selecting faces, only currently selected pb-Objects will be tested for matching faces. If false, all pb_Objects in the scene will be checked. The latter may be slower in large scenes."), pbDragCheckLimit); pbPBOSelectionOnly = EditorGUILayout.Toggle(new GUIContent("Only PBO are Selectable", "If true, you will not be able to select non probuilder objects in Geometry and Texture mode"), pbPBOSelectionOnly); pbCloseShapeWindow = EditorGUILayout.Toggle(new GUIContent("Close shape window after building", "If true the shape window will close after hitting the build button"), pbCloseShapeWindow); pbDrawAxisLines = EditorGUILayout.Toggle(new GUIContent("Dimension Overlay Lines", "When the Dimensions Overlay is on, this toggle shows or hides the axis lines."), pbDrawAxisLines); GUILayout.Space(4); /** * GEOMETRY EDITING SETTINGS */ GUILayout.Label("Geometry Editing Settings", EditorStyles.boldLabel); pbDefaultFaceColor = EditorGUILayout.ColorField("Selected Face Color", pbDefaultFaceColor); pbDefaultEdgeColor = EditorGUILayout.ColorField("Edge Wireframe Color", pbDefaultEdgeColor); pbDefaultVertexColor = EditorGUILayout.ColorField("Vertex Color", pbDefaultVertexColor); pbDefaultSelectedVertexColor = EditorGUILayout.ColorField("Selected Vertex Color", pbDefaultSelectedVertexColor); pbVertexHandleSize = EditorGUILayout.Slider("Vertex Handle Size", pbVertexHandleSize, 0f, 1f); pbForceVertexPivot = EditorGUILayout.Toggle(new GUIContent("Force Pivot to Vertex Point", "If true, new objects will automatically have their pivot point set to a vertex instead of the center."), pbForceVertexPivot); pbForceGridPivot = EditorGUILayout.Toggle(new GUIContent("Force Pivot to Grid", "If true, newly instantiated pb_Objects will be snapped to the nearest point on grid. If ProGrids is present, the snap value will be used, otherwise decimals are simply rounded to whole numbers."), pbForceGridPivot); pbManifoldEdgeExtrusion = EditorGUILayout.Toggle(new GUIContent("Manifold Edge Extrusion", "If false, only edges non-manifold edges may be extruded. If true, you may extrude any edge you like (for those who like to live dangerously)."), pbManifoldEdgeExtrusion); pbPerimeterEdgeBridgeOnly = EditorGUILayout.Toggle(new GUIContent("Bridge Perimeter Edges Only", "If true, only edges on the perimeters of an object may be bridged. If false, you may bridge any between any two edges you like."), pbPerimeterEdgeBridgeOnly); GUILayout.Space(4); /** * UV EDITOR SETTINGS */ GUILayout.Label("UV Editing Settings", EditorStyles.boldLabel); pbUVGridSnapValue = EditorGUILayout.FloatField("UV Snap Increment", pbUVGridSnapValue); pbUVGridSnapValue = Mathf.Clamp(pbUVGridSnapValue, .015625f, 2f); pbUVEditorFloating = EditorGUILayout.Toggle(new GUIContent("Editor window floating", "If true UV Editor window will open as a floating window"), pbUVEditorFloating); EditorGUILayout.EndScrollView(); GUILayout.Space(4); GUILayout.Label("Shortcut Settings", EditorStyles.boldLabel); if (GUI.Button(resetRect, "Use defaults")) { ResetToDefaults(); } ShortcutSelectPanel(); ShortcutEditPanel(); // Save the preferences if (EditorGUI.EndChangeCheck()) { SetPrefs(); } }
protected static void CreateCollider(Transform t, Vector3 startPoint, Vector3 endPoint, ColliderType colliderType, float lengthOverlap, float width) { Vector3 direction = endPoint - startPoint; float height = direction.magnitude * (1f + lengthOverlap); Vector3 heightAxis = AxisTools.GetAxisVectorToDirection(t, direction); t.gameObject.AddComponent <Rigidbody>(); float scaleF = GetScaleF(t); switch (colliderType) { case ColliderType.Capsule: CapsuleCollider capsule = t.gameObject.AddComponent <CapsuleCollider>(); capsule.height = Mathf.Abs(height / scaleF); capsule.radius = Mathf.Abs((width * 0.75f) / scaleF); capsule.direction = DirectionVector3ToInt(heightAxis); capsule.center = t.InverseTransformPoint(Vector3.Lerp(startPoint, endPoint, 0.5f)); break; case ColliderType.Box: Vector3 size = Vector3.Scale(heightAxis, new Vector3(height, height, height)); if (size.x == 0f) { size.x = width; } if (size.y == 0f) { size.y = width; } if (size.z == 0f) { size.z = width; } BoxCollider box = t.gameObject.AddComponent <BoxCollider>(); box.size = size / scaleF; box.size = new Vector3(Mathf.Abs(box.size.x), Mathf.Abs(box.size.y), Mathf.Abs(box.size.z)); box.center = t.InverseTransformPoint(Vector3.Lerp(startPoint, endPoint, 0.5f)); break; } }
/** \copydoc Pathfinding::ISerializableObject::DeSerializeSettings */ public void DeSerializeSettings(AstarSerializer serializer) { mask.value = (int)serializer.GetValue ("Mask",typeof (int)); diameter = (float)serializer.GetValue ("Diameter",typeof (float)); height = (float)serializer.GetValue ("Height",typeof (float)); type = (ColliderType)serializer.GetValue ("Type",typeof(int)); rayDirection = (RayDirection)serializer.GetValue ("RayDirection",typeof(int)); heightMask.value = (int)serializer.GetValue ("heightMask",typeof (int),-1); fromHeight = (float)serializer.GetValue ("fromHeight",typeof (float), 100.0F); thickRaycastDiameter = (float)serializer.GetValue ("thickRaycastDiameter",typeof (float)); thickRaycast = (bool)serializer.GetValue ("thickRaycast",typeof (bool)); collisionCheck = (bool)serializer.GetValue ("collisionCheck",typeof(bool),true); heightCheck = (bool)serializer.GetValue ("heightCheck",typeof(bool),true); unwalkableWhenNoGround = (bool)serializer.GetValue ("unwalkableWhenNoGround",typeof(bool),true); collisionOffset = (float)serializer.GetValue ("collisionOffset",typeof(float),0.0F); if (fromHeight == 0) fromHeight = 100; }
protected static void CreateCollider(Transform t, Vector3 startPoint, Vector3 endPoint, ColliderType colliderType, float lengthOverlap, float width, float proportionAspect, Vector3 widthDirection) { if (colliderType == ColliderType.Capsule) { CreateCollider(t, startPoint, endPoint, colliderType, lengthOverlap, width * proportionAspect); return; } Vector3 direction = endPoint - startPoint; float height = direction.magnitude * (1f + lengthOverlap); Vector3 heightAxis = AxisTools.GetAxisVectorToDirection(t, direction); Vector3 widthAxis = AxisTools.GetAxisVectorToDirection(t, widthDirection); if (widthAxis == heightAxis) { Debug.LogWarning("Width axis = height axis on " + t.name, t); widthAxis = new Vector3(heightAxis.y, heightAxis.z, heightAxis.x); } t.gameObject.AddComponent <Rigidbody>(); Vector3 heightAdd = Vector3.Scale(heightAxis, new Vector3(height, height, height)); Vector3 widthAdd = Vector3.Scale(widthAxis, new Vector3(width, width, width)); Vector3 size = heightAdd + widthAdd; if (size.x == 0f) { size.x = width * proportionAspect; } if (size.y == 0f) { size.y = width * proportionAspect; } if (size.z == 0f) { size.z = width * proportionAspect; } BoxCollider box = t.gameObject.AddComponent <BoxCollider>(); box.size = size / GetScaleF(t); box.center = t.InverseTransformPoint(Vector3.Lerp(startPoint, endPoint, 0.5f)); }
private static void AddCollider(GameObject selectedObject, ColliderType colliderType) { switch (colliderType) { case ColliderType.Box: selectedObject.AddComponent<BoxCollider>(); break; case ColliderType.Sphere: selectedObject.AddComponent<SphereCollider>(); break; case ColliderType.Capsule: selectedObject.AddComponent<CapsuleCollider>(); break; case ColliderType.Mesh: selectedObject.AddComponent<MeshCollider>(); break; default: break; } }
private void AddRagdollCollider(Transform target, ColliderType collisionType, Vector3 colliderCentre, Vector3 coliderSize, float colliderRadius, float colliderHeight, ColliderDirection direction) { Collider collider = target.GetComponent <Collider>(); if (collider == null) { switch (collisionType) { case ColliderType.BoxCollider: collider = target.gameObject.AddComponent <BoxCollider>(); break; case ColliderType.SphereCollider: collider = target.gameObject.AddComponent <SphereCollider>(); break; case ColliderType.CapsuleCollider: collider = target.gameObject.AddComponent <CapsuleCollider>(); break; default: break; } } else { if (overridePreExistingComponentValues == false) { return; } } collider.isTrigger = false; switch (collisionType) { case ColliderType.BoxCollider: BoxCollider boxCollision = collider as BoxCollider; boxCollision.center = colliderCentre; boxCollision.size = coliderSize; break; case ColliderType.SphereCollider: SphereCollider sphereCollision = collider as SphereCollider; sphereCollision.center = colliderCentre; sphereCollision.radius = colliderRadius; break; case ColliderType.CapsuleCollider: CapsuleCollider capsuleCollision = collider as CapsuleCollider; capsuleCollision.center = colliderCentre; capsuleCollision.radius = colliderRadius; capsuleCollision.height = colliderHeight; switch (direction) { case ColliderDirection.X: capsuleCollision.direction = 0; break; case ColliderDirection.Y: capsuleCollision.direction = 1; break; case ColliderDirection.Z: capsuleCollision.direction = 2; break; default: break; } break; } collider.gameObject.layer = 9; }
public Collider(Collidable owner, Rectangle bounds, ColliderType type) { this.owner = owner; this.bounds = new DoubleRect(bounds.X, bounds.Y, bounds.Width, bounds.Height); this.type = type; }
public void CopyFrom(tk2dSpriteCollectionDefinition src) { name = src.name; disableTrimming = src.disableTrimming; additive = src.additive; scale = src.scale; texture = src.texture; materialId = src.materialId; anchor = src.anchor; anchorX = src.anchorX; anchorY = src.anchorY; overrideMesh = src.overrideMesh; customSpriteGeometry = src.customSpriteGeometry; geometryIslands = src.geometryIslands; dice = src.dice; diceUnitX = src.diceUnitX; diceUnitY = src.diceUnitY; pad = src.pad; source = src.source; fromSpriteSheet = src.fromSpriteSheet; hasSpriteSheetId = src.hasSpriteSheetId; spriteSheetX = src.spriteSheetX; spriteSheetY = src.spriteSheetY; spriteSheetId = src.spriteSheetId; extractRegion = src.extractRegion; regionX = src.regionX; regionY = src.regionY; regionW = src.regionW; regionH = src.regionH; regionId = src.regionId; colliderType = src.colliderType; boxColliderMin = src.boxColliderMin; boxColliderMax = src.boxColliderMax; polyColliderCap = src.polyColliderCap; colliderColor = src.colliderColor; colliderConvex = src.colliderConvex; colliderSmoothSphereCollisions = src.colliderSmoothSphereCollisions; extraPadding = src.extraPadding; if (src.polyColliderIslands != null) { polyColliderIslands = new tk2dSpriteColliderIsland[src.polyColliderIslands.Length]; for (int i = 0; i < polyColliderIslands.Length; ++i) { polyColliderIslands[i] = new tk2dSpriteColliderIsland(); polyColliderIslands[i].CopyFrom(src.polyColliderIslands[i]); } } else { polyColliderIslands = new tk2dSpriteColliderIsland[0]; } if (src.geometryIslands != null) { geometryIslands = new tk2dSpriteColliderIsland[src.geometryIslands.Length]; for (int i = 0; i < geometryIslands.Length; ++i) { geometryIslands[i] = new tk2dSpriteColliderIsland(); geometryIslands[i].CopyFrom(src.geometryIslands[i]); } } else { geometryIslands = new tk2dSpriteColliderIsland[0]; } }
//draw custom editor window GUI void OnGUI() { //display label and object field for enemy model slot EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Enemy Model:"); enemyModel = (GameObject)EditorGUILayout.ObjectField(enemyModel, typeof(GameObject), false); EditorGUILayout.EndHorizontal(); //display label and objectfield for HUD bar prefab slot EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("HUD Bar Prefab:"); hudBar = (GameObject)EditorGUILayout.ObjectField(hudBar, typeof(GameObject), false); EditorGUILayout.EndHorizontal(); //display label and objectfield for shadow prefab slot EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Shadow Prefab:"); shadow = (GameObject)EditorGUILayout.ObjectField(shadow, typeof(GameObject), false); EditorGUILayout.EndHorizontal(); //display label and enum list for collider type EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Collider Type:"); colliderType = (ColliderType)EditorGUILayout.EnumPopup(colliderType); EditorGUILayout.EndHorizontal(); //display label and tag field for enemy tag EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Enemy Tag:"); tag = EditorGUILayout.TagField(tag); EditorGUILayout.EndHorizontal(); //display label and layer field for enemy layer EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Enemy Layer:"); layer = EditorGUILayout.LayerField(layer); EditorGUILayout.EndHorizontal(); //display label and checkbox for TweenMove component EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Attach TweenMove:"); attachTMove = EditorGUILayout.Toggle(attachTMove); EditorGUILayout.EndHorizontal(); //display label and checkbox for Properties component EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Attach Properties:"); attachProperties = EditorGUILayout.Toggle(attachProperties); EditorGUILayout.EndHorizontal(); //display label and checkbox for Rigidbody component EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Attach Rigidbody:"); attachRigidbody = EditorGUILayout.Toggle(attachRigidbody); EditorGUILayout.EndHorizontal(); //display info box below all settings EditorGUILayout.Space(); EditorGUILayout.HelpBox("By clicking on 'Apply!' all chosen components are added and a prefab will be created next to your enemy model.", MessageType.Info); EditorGUILayout.Space(); //apply button if (GUILayout.Button("Apply!")) { //cancel further execution if no enemy model is set if (enemyModel == null) { Debug.LogWarning("No enemy model chosen. Aborting Enemy Setup execution."); return; } //get model's asset path in this project to place the new prefab next to it string assetPath = AssetDatabase.GetAssetPath(enemyModel.GetInstanceID()); //e.g. assetPath = "Assets/Models/model.fbx //split folder structure for renaming the existing model name as prefab string[] folders = assetPath.Split('/'); //e.g. folders[0] = "Assets", folders[1] = "Models", folders[2] = "model.fbx" //then we replace the last part, the model name in folders[2], with the new prefab name assetPath = assetPath.Replace(folders[folders.Length-1], enemyModel.name + ".prefab"); //new asset path: "Assets/Models/model.prefab" //instantiate, convert and setup model for new prefab ProcessModel(); //if TweenMove checkbox is checked, attach component if (attachTMove) enemyModel.AddComponent<TweenMove>(); Properties properties = null; //if Properties checkbox is checked if (attachProperties) { //attach and store Properties component for later use properties = enemyModel.AddComponent<Properties>(); } //if a HUD Bar prefab is set if (hudBar) { //instantiate HUD bar prefab hudBar = (GameObject)Instantiate(hudBar); //remove the "(Clone)" part of the name hudBar.name = hudBar.name.Replace("(Clone)", ""); //parent bars to enemy instance hudBar.transform.parent = enemyModel.transform; //reposition bars (Vector3.zero) relative to the enemy hudBar.transform.position = enemyModel.transform.position; if(!properties) return; //try to find and set sliders based on their name Transform healthbarTrans = hudBar.transform.FindChild("healthbar"); if (healthbarTrans) { UISlider healthbar = healthbarTrans.GetComponent<UISlider>(); properties.healthbar = healthbar; } Transform shieldbarTrans = hudBar.transform.FindChild("shieldbar"); if (shieldbarTrans) { UISlider shieldbar = shieldbarTrans.GetComponent<UISlider>(); properties.shield = new Shield(); properties.shield.bar = shieldbar; properties.shield.enabled = true; } } //if a shadow prefab is set if (shadow) { //instantiate shadow prefab shadow = (GameObject)Instantiate(shadow); //remove the "(Clone)" part of the name shadow.name = shadow.name.Replace("(Clone)", ""); //parent shadow to enemy instance shadow.transform.parent = enemyModel.transform; //reposition shadow (Vector3.zero) relative to the enemy shadow.transform.position = enemyModel.transform.position; } //if Rigidbody checkbox is checked if (attachRigidbody) { //attach and store Rigidbody component for later use Rigidbody rigidbody = enemyModel.AddComponent<Rigidbody>(); //disable gravity and kinematic rigidbody.useGravity = false; rigidbody.isKinematic = false; } //initialize prefab gameobject GameObject prefab = null; //perform check if we already have a prefab in our project (null if none) if (AssetDatabase.LoadAssetAtPath(assetPath, typeof(GameObject))) { //display custom dialog and wait for user input to overwrite prefab if (EditorUtility.DisplayDialog("Are you sure?", "The prefab already exists. Do you want to overwrite it?", "Yes", "No")) { //user clicked "Yes", create and overwrite existing prefab prefab = PrefabUtility.CreatePrefab(assetPath, enemyModel); } } else //we haven't created a prefab before nor the project contains one, //create prefab next to the model at assetPath prefab = PrefabUtility.CreatePrefab(assetPath, enemyModel); //destroy temporary instantiated enemy model in the editor DestroyImmediate(enemyModel); //if we created a prefab if (prefab) { //select it within the project panel Selection.activeGameObject = prefab; //close this editor window this.Close(); } } }
public Collider(ColliderType type, bool isTrigger, Vector3 center) { Type = type; IsTrigger = isTrigger; Center = center; }
public static void PreferencesGUI() { // Load the preferences if (!prefsLoaded) { LoadPrefs(); prefsLoaded = true; OnWindowResize(); } settingsScroll = EditorGUILayout.BeginScrollView(settingsScroll, GUILayout.MaxHeight(200)); EditorGUI.BeginChangeCheck(); /** * GENERAL SETTINGS */ GUILayout.Label("General Settings", EditorStyles.boldLabel); pbStripProBuilderOnBuild = EditorGUILayout.Toggle(new GUIContent("Strip PB Scripts on Build", "If true, when building an executable all ProBuilder scripts will be stripped from your built product."), pbStripProBuilderOnBuild); pbDisableAutoUV2Generation = EditorGUILayout.Toggle(new GUIContent("Disable Auto UV2 Generation", "Disables automatic generation of UV2 channel. If Unity is sluggish when working with large ProBuilder objects, disabling UV2 generation will improve performance. Use `Actions/Generate UV2` or `Actions/Generate Scene UV2` to build lightmap UVs prior to baking."), pbDisableAutoUV2Generation); pbShowSceneInfo = EditorGUILayout.Toggle(new GUIContent("Show Scene Info", "Displays the selected object vertex and triangle counts in the scene view."), pbShowSceneInfo); pbShowEditorNotifications = EditorGUILayout.Toggle("Show Editor Notifications", pbShowEditorNotifications); /** * TOOLBAR SETTINGS */ GUILayout.Label("Toolbar Settings", EditorStyles.boldLabel); pbIconGUI = EditorGUILayout.Toggle(new GUIContent("Use Icon GUI", "Toggles the ProBuilder window interface between text and icon versions."), pbIconGUI); pbShiftOnlyTooltips = EditorGUILayout.Toggle(new GUIContent("Shift Key Tooltips", "Tooltips will only show when the Shift key is held"), pbShiftOnlyTooltips); pbToolbarLocation = (SceneToolbarLocation) EditorGUILayout.EnumPopup("Toolbar Location", pbToolbarLocation); pbUniqueModeShortcuts = EditorGUILayout.Toggle(new GUIContent("Unique Mode Shortcuts", "When off, the G key toggles between Object and Element modes and H enumerates the element modes. If on, G, H, J, and K are shortcuts to Object, Vertex, Edge, and Face modes respectively."), pbUniqueModeShortcuts); defaultOpenInDockableWindow = EditorGUILayout.Toggle("Open in Dockable Window", defaultOpenInDockableWindow); /** * DEFAULT SETTINGS */ GUILayout.Label("Defaults", EditorStyles.boldLabel); pbDefaultMaterial = (Material) EditorGUILayout.ObjectField("Default Material", pbDefaultMaterial, typeof(Material), false); GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Default Entity"); pbDefaultEntity = ((EntityType)EditorGUILayout.EnumPopup( (EntityType)pbDefaultEntity )); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Default Collider"); defaultColliderType = ((ColliderType)EditorGUILayout.EnumPopup( (ColliderType)defaultColliderType )); GUILayout.EndHorizontal(); if((ColliderType)defaultColliderType == ColliderType.MeshCollider) pbForceConvex = EditorGUILayout.Toggle("Force Convex Mesh Collider", pbForceConvex); #if !UNITY_4_7 GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Shadow Casting Mode"); pbShadowCastingMode = (ShadowCastingMode) EditorGUILayout.EnumPopup(pbShadowCastingMode); GUILayout.EndHorizontal(); #endif /** * MISC. SETTINGS */ GUILayout.Label("Misc. Settings", EditorStyles.boldLabel); pbDragCheckLimit = EditorGUILayout.Toggle(new GUIContent("Limit Drag Check to Selection", "If true, when drag selecting faces, only currently selected pb-Objects will be tested for matching faces. If false, all pb_Objects in the scene will be checked. The latter may be slower in large scenes."), pbDragCheckLimit); pbPBOSelectionOnly = EditorGUILayout.Toggle(new GUIContent("Only PBO are Selectable", "If true, you will not be able to select non probuilder objects in Geometry and Texture mode"), pbPBOSelectionOnly); pbCloseShapeWindow = EditorGUILayout.Toggle(new GUIContent("Close shape window after building", "If true the shape window will close after hitting the build button"), pbCloseShapeWindow); pbDrawAxisLines = EditorGUILayout.Toggle(new GUIContent("Dimension Overlay Lines", "When the Dimensions Overlay is on, this toggle shows or hides the axis lines."), pbDrawAxisLines); GUILayout.Space(4); /** * GEOMETRY EDITING SETTINGS */ GUILayout.Label("Geometry Editing Settings", EditorStyles.boldLabel); pbElementSelectIsHamFisted = !EditorGUILayout.Toggle(new GUIContent("Precise Element Selection", "When enabled you will be able to select object faces when in Vertex of Edge mode by clicking the center of a face. When disabled, edge and vertex selection will always be restricted to the nearest element."), !pbElementSelectIsHamFisted); pbDragSelectWholeElement = EditorGUILayout.Toggle("Precise Drag Select", pbDragSelectWholeElement); pbDefaultFaceColor = EditorGUILayout.ColorField("Selected Face Color", pbDefaultFaceColor); pbDefaultEdgeColor = EditorGUILayout.ColorField("Edge Wireframe Color", pbDefaultEdgeColor); pbDefaultVertexColor = EditorGUILayout.ColorField("Vertex Color", pbDefaultVertexColor); pbDefaultSelectedVertexColor = EditorGUILayout.ColorField("Selected Vertex Color", pbDefaultSelectedVertexColor); pbVertexHandleSize = EditorGUILayout.Slider("Vertex Handle Size", pbVertexHandleSize, 0f, 3f); pbForceVertexPivot = EditorGUILayout.Toggle(new GUIContent("Force Pivot to Vertex Point", "If true, new objects will automatically have their pivot point set to a vertex instead of the center."), pbForceVertexPivot); pbForceGridPivot = EditorGUILayout.Toggle(new GUIContent("Force Pivot to Grid", "If true, newly instantiated pb_Objects will be snapped to the nearest point on grid. If ProGrids is present, the snap value will be used, otherwise decimals are simply rounded to whole numbers."), pbForceGridPivot); pbPerimeterEdgeBridgeOnly = EditorGUILayout.Toggle(new GUIContent("Bridge Perimeter Edges Only", "If true, only edges on the perimeters of an object may be bridged. If false, you may bridge any between any two edges you like."), pbPerimeterEdgeBridgeOnly); GUILayout.Space(4); GUILayout.Label("Experimental", EditorStyles.boldLabel); pbMeshesAreAssets = EditorGUILayout.Toggle(new GUIContent("Meshes Are Assets", "Experimental! Instead of storing mesh data in the scene, this toggle creates a Mesh cache in the Project that ProBuilder will use."), pbMeshesAreAssets); GUILayout.Space(4); /** * UV EDITOR SETTINGS */ GUILayout.Label("UV Editing Settings", EditorStyles.boldLabel); pbUVGridSnapValue = EditorGUILayout.FloatField("UV Snap Increment", pbUVGridSnapValue); pbUVGridSnapValue = Mathf.Clamp(pbUVGridSnapValue, .015625f, 2f); pbUVEditorFloating = EditorGUILayout.Toggle(new GUIContent("Editor window floating", "If true UV Editor window will open as a floating window"), pbUVEditorFloating); EditorGUILayout.EndScrollView(); GUILayout.Space(4); GUILayout.Label("Shortcut Settings", EditorStyles.boldLabel); if(GUI.Button(resetRect, "Use defaults")) ResetToDefaults(); ShortcutSelectPanel(); ShortcutEditPanel(); // Save the preferences if (EditorGUI.EndChangeCheck()) SetPrefs(); }
private async Task <IList <Asset> > LoadAssetsFromGLTF(AssetSource source, Guid containerId, ColliderType colliderType) { WebRequestLoader loader = null; Stream stream = null; source.ParsedUri = new Uri(_app.ServerAssetUri, source.ParsedUri); var rootUri = URIHelper.GetDirectoryName(source.ParsedUri.AbsoluteUri); // acquire the exclusive right to load this asset if (!await MREAPI.AppsAPI.AssetCache.AcquireLoadingLock(source.ParsedUri)) { throw new TimeoutException("Failed to acquire exclusive loading rights for " + source.ParsedUri); } var cachedVersion = MREAPI.AppsAPI.AssetCache.SupportsSync ? MREAPI.AppsAPI.AssetCache.TryGetVersionSync(source.ParsedUri) : await MREAPI.AppsAPI.AssetCache.TryGetVersion(source.ParsedUri); // Wait asynchronously until the load throttler lets us through. using (var scope = await AssetLoadThrottling.AcquireLoadScope()) { // set up loader loader = new WebRequestLoader(rootUri); if (cachedVersion != Constants.UnversionedAssetVersion && !string.IsNullOrEmpty(cachedVersion)) { loader.BeforeRequestCallback += (msg) => { if (msg.RequestUri == source.ParsedUri) { msg.Headers.Add("If-None-Match", cachedVersion); } }; } // download root gltf file, check for cache hit try { stream = await loader.LoadStreamAsync(URIHelper.GetFileFromUri(source.ParsedUri)); source.Version = loader.LastResponse.Headers.ETag?.Tag ?? Constants.UnversionedAssetVersion; } catch (HttpRequestException) { if (loader.LastResponse != null && loader.LastResponse.StatusCode == System.Net.HttpStatusCode.NotModified) { source.Version = cachedVersion; } else { throw; } } } IList <Asset> assetDefs = new List <Asset>(30); DeterministicGuids guidGenerator = new DeterministicGuids(UtilMethods.StringToGuid( $"{containerId}:{source.ParsedUri.AbsoluteUri}")); IList <UnityEngine.Object> assets; // fetch assets from glTF stream or cache if (source.Version != cachedVersion) { assets = await LoadGltfFromStream(loader, stream, colliderType); MREAPI.AppsAPI.AssetCache.StoreAssets(source.ParsedUri, assets, source.Version); } else { var assetsEnum = MREAPI.AppsAPI.AssetCache.SupportsSync ? MREAPI.AppsAPI.AssetCache.LeaseAssetsSync(source.ParsedUri) : await MREAPI.AppsAPI.AssetCache.LeaseAssets(source.ParsedUri); assets = assetsEnum.ToList(); } // the cache is updated, release the lock MREAPI.AppsAPI.AssetCache.ReleaseLoadingLock(source.ParsedUri); // catalog assets int textureIndex = 0, meshIndex = 0, materialIndex = 0, prefabIndex = 0; foreach (var asset in assets) { var assetDef = GenerateAssetPatch(asset, guidGenerator.Next()); assetDef.Name = asset.name; string internalId = null; if (asset is UnityEngine.Texture) { internalId = $"texture:{textureIndex++}"; } else if (asset is UnityEngine.Mesh) { internalId = $"mesh:{meshIndex++}"; } else if (asset is UnityEngine.Material) { internalId = $"material:{materialIndex++}"; } else if (asset is GameObject) { internalId = $"scene:{prefabIndex++}"; } assetDef.Source = new AssetSource(source.ContainerType, source.ParsedUri.AbsoluteUri, internalId, source.Version); ColliderGeometry colliderGeo = null; if (asset is UnityEngine.Mesh mesh) { colliderGeo = colliderType == ColliderType.Mesh ? (ColliderGeometry) new MeshColliderGeometry() { MeshId = assetDef.Id } : (ColliderGeometry) new BoxColliderGeometry() { Size = (mesh.bounds.size * 0.8f).CreateMWVector3(), Center = mesh.bounds.center.CreateMWVector3() }; } _app.AssetManager.Set(assetDef.Id, containerId, asset, colliderGeo, assetDef.Source); assetDefs.Add(assetDef); } return(assetDefs); }
public static void PreferencesGUI () { // Load the preferences if (!prefsLoaded) { LoadPrefs(); prefsLoaded = true; OnWindowResize(); } settingsScroll = EditorGUILayout.BeginScrollView(settingsScroll, GUILayout.MaxHeight(200)); EditorGUI.BeginChangeCheck(); /** * GENERAL SETTINGS */ GUILayout.Label("General Settings", EditorStyles.boldLabel); pbStripProBuilderOnBuild = EditorGUILayout.Toggle(new GUIContent("Strip PB Scripts on Build", "If true, when building an executable all ProBuilder scripts will be stripped from your built product."), pbStripProBuilderOnBuild); pbDisableAutoUV2Generation = EditorGUILayout.Toggle(new GUIContent("Disable Auto UV2 Generation", "Disables automatic generation of UV2 channel. If Unity is sluggish when working with large ProBuilder objects, disabling UV2 generation will improve performance. Use `Actions/Generate UV2` or `Actions/Generate Scene UV2` to build lightmap UVs prior to baking."), pbDisableAutoUV2Generation); pbShowSceneInfo = EditorGUILayout.Toggle(new GUIContent("Show Scene Info", "Displays the selected object vertex and triangle counts in the scene view."), pbShowSceneInfo); pbEnableBackfaceSelection = EditorGUILayout.Toggle(new GUIContent("Enable Back-face Selection", "If enabled, you may select faces that have been culled by their back face."), pbEnableBackfaceSelection); pbDefaultMaterial = (Material) EditorGUILayout.ObjectField("Default Material", pbDefaultMaterial, typeof(Material), false); defaultOpenInDockableWindow = EditorGUILayout.Toggle("Open in Dockable Window", defaultOpenInDockableWindow); GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Default Collider"); defaultColliderType = ((ColliderType)EditorGUILayout.EnumPopup( (ColliderType)defaultColliderType )); GUILayout.EndHorizontal(); if((ColliderType)defaultColliderType == ColliderType.MeshCollider) pbForceConvex = EditorGUILayout.Toggle("Force Convex Mesh Collider", pbForceConvex); pbShowEditorNotifications = EditorGUILayout.Toggle("Show Editor Notifications", pbShowEditorNotifications); pbDragCheckLimit = EditorGUILayout.Toggle(new GUIContent("Limit Drag Check to Selection", "If true, when drag selecting faces, only currently selected pb-Objects will be tested for matching faces. If false, all pb_Objects in the scene will be checked. The latter may be slower in large scenes."), pbDragCheckLimit); pbPBOSelectionOnly = EditorGUILayout.Toggle(new GUIContent("Only PBO are Selectable", "If true, you will not be able to select non probuilder objects in Geometry and Texture mode"), pbPBOSelectionOnly); pbCloseShapeWindow = EditorGUILayout.Toggle(new GUIContent("Close shape window after building", "If true the shape window will close after hitting the build button"), pbCloseShapeWindow); pbShowSceneToolbar = EditorGUILayout.Toggle(new GUIContent("Show Scene Toolbar", "Hide or show the SceneView mode toolbar."), pbShowSceneToolbar); GUI.enabled = pbShowSceneToolbar; pbToolbarLocation = (SceneToolbarLocation) EditorGUILayout.EnumPopup("Toolbar Location", pbToolbarLocation); GUI.enabled = true; GUILayout.Space(4); /** * GEOMETRY EDITING SETTINGS */ GUILayout.Label("Geometry Editing Settings", EditorStyles.boldLabel); pbDefaultFaceColor = EditorGUILayout.ColorField("Selected Face Color", pbDefaultFaceColor); pbDefaultEdgeColor = EditorGUILayout.ColorField("Edge Wireframe Color", pbDefaultEdgeColor); pbDefaultVertexColor = EditorGUILayout.ColorField("Vertex Color", pbDefaultVertexColor); pbDefaultSelectedVertexColor = EditorGUILayout.ColorField("Selected Vertex Color", pbDefaultSelectedVertexColor); pbVertexHandleSize = EditorGUILayout.Slider("Vertex Handle Size", pbVertexHandleSize, 0f, 1f); pbForceVertexPivot = EditorGUILayout.Toggle(new GUIContent("Force Pivot to Vertex Point", "If true, new objects will automatically have their pivot point set to a vertex instead of the center."), pbForceVertexPivot); pbForceGridPivot = EditorGUILayout.Toggle(new GUIContent("Force Pivot to Grid", "If true, newly instantiated pb_Objects will be snapped to the nearest point on grid. If ProGrids is present, the snap value will be used, otherwise decimals are simply rounded to whole numbers."), pbForceGridPivot); pbManifoldEdgeExtrusion = EditorGUILayout.Toggle(new GUIContent("Manifold Edge Extrusion", "If false, only edges non-manifold edges may be extruded. If true, you may extrude any edge you like (for those who like to live dangerously)."), pbManifoldEdgeExtrusion); pbPerimeterEdgeBridgeOnly = EditorGUILayout.Toggle(new GUIContent("Bridge Perimeter Edges Only", "If true, only edges on the perimeters of an object may be bridged. If false, you may bridge any between any two edges you like."), pbPerimeterEdgeBridgeOnly); GUILayout.Space(4); /** * UV EDITOR SETTINGS */ GUILayout.Label("UV Editing Settings", EditorStyles.boldLabel); pbUVGridSnapValue = EditorGUILayout.FloatField("UV Snap Increment", pbUVGridSnapValue); pbUVGridSnapValue = Mathf.Clamp(pbUVGridSnapValue, .015625f, 2f); pbUVEditorFloating = EditorGUILayout.Toggle(new GUIContent("Editor window floating", "If true UV Editor window will open as a floating window"), pbUVEditorFloating); EditorGUILayout.EndScrollView(); GUILayout.Space(4); GUILayout.Label("Shortcut Settings", EditorStyles.boldLabel); if(GUI.Button(resetRect, "Use defaults")) ResetToDefaults(); ShortcutSelectPanel(); ShortcutEditPanel(); // Save the preferences if (EditorGUI.EndChangeCheck()) SetPrefs(); }
public static SpriteBehavior CreateSpriteBehavior(ColliderType collider_type, string sprite_path = "", float x = 0, float y = 0) { return InitializeSpriteBehavior(new GameObject().AddComponent<SpriteBehavior>(), collider_type, sprite_path, x, y); }