void Awake() { BoxRef = this.gameObject.AddComponent<BoxCollider>(); ScriptRef = this.gameObject.GetComponent<CartoonExplosionFX>(); ParentRef = this.gameObject.GetComponent<GameObject>(); }
void Awake() { Debug.Log ("Zombie instantiated!"); moveSpeed = 250f; isIdle = true; ChaseTarget = null; transforming = false; idleCounter = 0; idleCounterMax = 3f; idleMoveSpeed = 50f; targetContact = false; zombieSlowBy = 20; transforming = false; maxTransformTime = 1.5f; transformTime = maxTransformTime; idleSoundIndex = Random.Range(0, idle.Length); alertSoundIndex = Random.Range(0, alert.Length); zombieDeathIndex = Random.Range(0,zombieDeath.Length); //Enables idle zombies to 'see' humans and the player BoxOfSight = (BoxCollider)transform.GetComponent(typeof(BoxCollider)); BoxOfSight.enabled = true; /* BUG * Player.laser will collide with BoxOfSight. * Attempted to assign BoxOfSight.layer = 2 (ignore raycast) * Could not assign layer to component, assigned to gameobject instead * Effect: player.laser will not collide with zombies (including BoxOfSight) */ BoxOfSight.gameObject.layer = 2; gameManager = (GameManager)GameObject.Find ("GameManager").GetComponent("GameManager"); }
// Use this for initialization void Start() { door = transform.FindChild("Inside"); doorPanelCollider = door.FindChild("panel").GetComponent<BoxCollider>(); doorRotation = 0; interactionEnabled = true; }
// Use this for initialization void Start() { bcollider = GetComponent<BoxCollider>(); ColliderScale = transform.localScale; s = new Vector3(bcollider.size.x*ColliderScale.x,bcollider.size.y*ColliderScale.y,bcollider.size.z*ColliderScale.z); c = new Vector3(bcollider.center.x*ColliderScale.x,bcollider.center.y*ColliderScale.y,bcollider.center.z); }
// Use this for initialization public void setValues(GameObject sel, MeleeWeapon ownerWeap) { self = sel; wepCol = GetComponent<BoxCollider>(); this.ownerWeap = ownerWeap; curTeam = sel.GetComponent<PlayerController>().team; }
// Use this for initialization void Start() { oCol = GetComponent<BoxCollider>(); t = transform; normColSize = oCol.size.x; float hori = oCol.size.x * t.localScale.x; float vert = oCol.size.y * t.localScale.y; float hMargin = Mathf.Min(margin, hori / minMarginDividor); float vMargin = Mathf.Min(margin, vert / minMarginDividor); topCol = Instantiate(Resources.Load("colliders/top"), t.position + new Vector3(hMargin, vert - vMargin, 0), t.rotation) as GameObject; botCol = Instantiate(Resources.Load("colliders/bot"), t.position + new Vector3(hMargin, 0, 0), t.rotation) as GameObject; rightCol = Instantiate(Resources.Load("colliders/right"), t.position + new Vector3(hori - hMargin, 0, 0), t.rotation) as GameObject; leftCol = Instantiate(Resources.Load("colliders/left"), t.position, t.rotation) as GameObject; topCol.transform.localScale = new Vector3(t.localScale.x - hMargin*2/normColSize, vMargin/normColSize, t.localScale.z); botCol.transform.localScale = new Vector3(t.localScale.x - hMargin*2/normColSize, vMargin/normColSize, t.localScale.z); rightCol.transform.localScale = new Vector3(hMargin/normColSize, t.localScale.y, t.localScale.z); leftCol.transform.localScale = new Vector3(hMargin/normColSize, t.localScale.y, t.localScale.z); Destroy(gameObject); }
// Use this for initialization void OnEnable() { if (isInverted) { Vector3 theScale = transform.localScale; theScale.x *= -1; transform.localScale = theScale; } collider = gameObject.GetComponent<BoxCollider>(); //gameObject.GetComponent<Animator>().SetBool("Open", opened); if (opened) { gameObject.GetComponent<Animator>().Play("AlreadyOpenHor"); gameObject.GetComponent<Animator>().Play("AlreadyOpenVer"); collider.enabled = false; } else { gameObject.GetComponent<Animator>().Play("AlreadyCloseHor"); gameObject.GetComponent<Animator>().Play("AlreadyCloseVer"); collider.enabled = true; } if (chronometer) { this.open(); currentChronometerTime = chronometerTime; } }
void Awake() { // Set up references. playerRigidbody = GetComponent <Rigidbody> (); Physics.IgnoreLayerCollision(8, 15, true); boxCol = GetComponent<BoxCollider>(); }
// Use this for initialization void Start() { anim = gameObject.GetComponent<Animation> (); sc = gameObject.GetComponent<SphereCollider> (); bc = gameObject.GetComponent<BoxCollider> (); initSound (); }
public static Vector3 ClosestPointOnSurface(BoxCollider collider, Vector3 to) { // Cache the collider transform var ct = collider.transform; // Firstly, transform the point into the space of the collider var local = ct.InverseTransformPoint(to); // Now, shift it to be in the center of the box local -= collider.center; // Clamp the points to the collider's extents var localNorm = new Vector3( Mathf.Clamp(local.x, -collider.size.x * 0.5f, collider.size.x * 0.5f), Mathf.Clamp(local.y, -collider.size.y * 0.5f, collider.size.y * 0.5f), Mathf.Clamp(local.z, -collider.size.z * 0.5f, collider.size.z * 0.5f) ); // Select a face to project on if (Mathf.Abs(localNorm.x) > Mathf.Abs(localNorm.y) && Mathf.Abs(localNorm.x) > Mathf.Abs(localNorm.z)) localNorm.x = Mathf.Sign(localNorm.x) * collider.size.x * 0.5f; else if (Mathf.Abs(localNorm.y) > Mathf.Abs(localNorm.x) && Mathf.Abs(localNorm.y) > Mathf.Abs(localNorm.z)) localNorm.y = Mathf.Sign(localNorm.y) * collider.size.y * 0.5f; else if (Mathf.Abs(localNorm.z) > Mathf.Abs(localNorm.x) && Mathf.Abs(localNorm.z) > Mathf.Abs(localNorm.y)) localNorm.z = Mathf.Sign(localNorm.z) * collider.size.z * 0.5f; // Now we undo our transformations localNorm += collider.center; // Return resulting point return ct.TransformPoint(localNorm); }
void Awake() { timeLastEnemyHitted = Time.time; trigger = GetComponentInChildren<BoxCollider>(); sprite = transform.GetComponentInChildren<SpriteRenderer>(); glitchPartPool = new ObjectPool(glitchPart); lives = 3; items = 0; //Instantiate the glitch fragments to avoid lag later in the game GameObject[] parts = new GameObject[100]; for (int i = 0; i < 100; i++) { parts[i] = glitchPartPool.getObject(); } for (int i = 0; i < 100; i++) { parts[i].SetActive(false); } boxUIActivatedRectTransform = boxUIActivated.GetComponent<RectTransform>(); exclamationSize = boxUIActivatedRectTransform.sizeDelta; boxUIActivated.SetActive(false); guiRectTrans = gui.GetComponent<RectTransform>(); slowFPSScript = transform.FindChild("Powers").GetComponentInChildren<SlowFPS>(); }
private void Start() { this.rb = base.GetComponent<Rigidbody>(); this.col = base.GetComponent<BoxCollider>(); base.StartCoroutine("doMove"); this.val = UnityEngine.Random.Range(-50f, 50f); }
void Start() { if(isInverted) { Vector3 theScale = transform.localScale; theScale.x *= -1; transform.localScale = theScale; } collider = gameObject.GetComponent<BoxCollider>(); gameObject.GetComponent<Animator>().SetBool("Open",opened); if (opened){ gameObject.GetComponent<Animator>().Play("AlreadyOpenHor"); gameObject.GetComponent<Animator>().Play("AlreadyOpenVer"); collider.enabled = false; } else { gameObject.GetComponent<Animator>().Play("AlreadyCloseHor"); gameObject.GetComponent<Animator>().Play("AlreadyCloseVer"); collider.enabled = true; } }
void Awake() { laserRender = GetComponent<Renderer> (); laserLight = GetComponent<Light> (); laserCollider = GetComponent<BoxCollider> (); time = 0f; }
// OnStateEnter is called when a transition starts and the state machine starts to evaluate this state //override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { // //} // OnStateUpdate is called on each Update frame between OnStateEnter and OnStateExit callbacks //override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { // //} // OnStateExit is called when a transition ends and the state machine finishes evaluating this state public override void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { myBoxCollider = animator.GetComponent<PlayerController>().mySwordBoxCollider; myBoxCollider.enabled = false; animator.SetBool("Whirlwinding", false); }
void Start() { print( "Start Box spawn area" ); spawnArea = GetComponent<BoxCollider>(); spawnArea.isTrigger = true; base.Start(); }
void OnDisable() { print( "Awake Box spawn area" ); spawnArea = GetComponent<BoxCollider>(); spawnArea.isTrigger = true; base.OnDisable(); }
// Use this for initialization void Start() { col = transform.parent.parent.GetComponent(typeof(BoxCollider)) as BoxCollider; switch(pointing) { case DIRECTION.up: Vector3 upPosition = new Vector3(transform.parent.position.x, 1f,transform.parent.position.z); upPosition.z += col.size.y/2f +0.4f; newPosition = upPosition; break; case DIRECTION.down: Vector3 downPosition = new Vector3(transform.parent.position.x, 1f,transform.parent.position.z); downPosition.z -= col.size.y/2 + 0.8f; newPosition = downPosition; break; case DIRECTION.left: Vector3 leftPosition = new Vector3(transform.parent.position.x - 0.8f, 1f,col.transform.position.z); leftPosition.x -= col.size.x/2; newPosition = leftPosition; //newPosition = new Vector3(col.transform.position.x - 2f, 1f, col.transform.position.z); break; case DIRECTION.right: Vector3 rightPosition = new Vector3(transform.parent.position.x + 0.8f, 1f,col.transform.position.z); rightPosition.x += col.size.x/2; newPosition = rightPosition; //newPosition = new Vector3(col.transform.position.x + 2f, 1f, col.transform.position.z); break; default: newPosition = Vector3.zero; break; } transform.position = newPosition; }
void Awake() { gameObject.AddComponent<MogoFakeClick>().ReletedClassType = ReleadClassType.Type_InsetUI; m_relatedCollider = transform.GetComponentInChildren<BoxCollider>(); m_rayHit = new RaycastHit(); }
public void Build() { if (this.ThisMeshFilter.sharedMesh == null) { Mesh mesh = new Mesh(); mesh.hideFlags = HideFlags.DontSave; this.ThisMeshFilter.mesh = this.FillMesh(mesh); } else { this.FillMesh(this.ThisMeshFilter.sharedMesh); } if (this.createBoxCollider) { if (this.ThisBoxCollider == null) { this._thisBoxCollider = base.gameObject.AddComponent<BoxCollider>(); } Bounds bounds = this.ThisMeshFilter.sharedMesh.bounds; this.ThisBoxCollider.center = new Vector3(bounds.center.x, bounds.center.y, -this.depth); this.ThisBoxCollider.size = new Vector3(bounds.size.x, bounds.size.y, 0.0002f); } else if (this.ThisBoxCollider != null) { UnityEngine.Object.Destroy(this.ThisBoxCollider); } }
void Start() { RangeBox = GetComponent<BoxCollider>(); EnemyOnRange = new ArrayList(); scoreManager = GameObject.Find("Score Manager").GetComponent<ScoreManager>(); PlayerAnim = gameObject.GetComponent<Animator>(); }
private void Awake () { if (transform.parent == null) { Debug.LogError("BoxColliderGenerator ERROR: this GO is not parented"); } else { MeshCollider meshCollider = GetComponentInParent<MeshCollider>(); boxCollider = GetComponent<BoxCollider>(); if (meshCollider == null || boxCollider == null) { Debug.Log("BoxColliderGenerator ERROR: mesh or box collider not defined"); } else { } // meshCollider = GetComponent<MeshCollider>(); // logCollider = gameObject.AddComponent<BoxCollider>(); // logCollider.isTrigger = true; //insideOffsetMultiplier = -insideOffsetMultiplier; size = meshCollider.bounds.size; boxCollider.size = new Vector3(size.x * insideOffsetMultiplier.x, size.y * insideOffsetMultiplier.y, size.z * insideOffsetMultiplier.z); transform.localPosition = Vector3.zero; transform.eulerAngles = rotationOffset; } }
public virtual void Initialize(int i_Health_Max_, float f_FireTimer_Max_, GameObject go_ParentBoxCollider_, BoxCollider col_BaseCollider_ = null, CapsuleCollider col_RadiusCollider_ = null) { i_Health = i_Health_Max_; i_Health_Max = i_Health_Max_; go_GridObject_Parent = go_ParentBoxCollider_; b_IsDead = false; // Material newMat = Resources.Load("DEV_Orange", typeof(Material)) as Material; SetMaterialElements(); SetNewMaterialColor(Colors.Default); f_FireTimer = 0; f_FireTimer_Max = f_FireTimer_Max_; if (col_BaseCollider_ != null) col_BaseCollider = col_BaseCollider_; else { if (gameObject.transform.Find("Col_BaseCollider")) col_BaseCollider = gameObject.transform.Find("Col_BaseCollider").GetComponent<BoxCollider>(); } if(col_RadiusCollider_ != null) col_RadiusCollider = col_RadiusCollider_; else { if (gameObject.transform.Find("Col_Radius")) col_RadiusCollider = gameObject.transform.Find("Col_Radius").GetComponent<CapsuleCollider>(); } EnemyList = new List<GameObject>(); }
static Vector3 closestPointOnOBB(BoxCollider collider, Vector3 to) { // Cache the collider transform var ct = collider.transform; // Firstly, transform the point into the space of the collider var local = ct.worldToLocalMatrix.MultiplyPoint3x4(to); // Now, shift it to be in the center of the box local -= collider.center; // Inverse scale it by the colliders scale var localNorm = new Vector3( Mathf.Clamp(local.x, -collider.extents.x, collider.extents.x), Mathf.Clamp(local.y, -collider.extents.y, collider.extents.y), Mathf.Clamp(local.z, -collider.extents.z, collider.extents.z) ); // Now we undo our transformations localNorm += collider.center; // Return resulting point return ct.localToWorldMatrix.MultiplyPoint3x4(localNorm); }
/// <summary> /// Spawns random objects within the box collider bounds. /// </summary> public void SpawnObjects() { CurrentSpawnedObjects = new GameObject[NumberToSpawn]; Bounds = GetComponent<BoxCollider>(); for (int i = 0; i < NumberToSpawn; i++) { // Get random position within this transform. Vector3 rndPosWithin = new Vector3(Random.Range(-1f, 1f) * Bounds.size.x / 2, Random.Range(-1f, 1f) * Bounds.size.x / 2, Random.Range(-1f, 1f) * Bounds.size.z / 2); rndPosWithin += transform.position; if (!isObjectTooClose(rndPosWithin)) { GameObject spawnedObject = (GameObject)Instantiate(ObjectSpawnPrefabs[Random.Range(0, ObjectSpawnPrefabs.Length)], rndPosWithin, Quaternion.identity); CurrentSpawnedObjects[i] = spawnedObject; CurrentSpawnedObjects[i].transform.parent = transform; // Create a child game object, which we will attach the culling sphere to. GameObject cullingSphere = new GameObject("Culling Sphere"); cullingSphere.transform.position = rndPosWithin; cullingSphere.transform.parent = spawnedObject.transform; // We use a sphere collider to determine whether the object should be rendered. SphereCollider spawnCollider = cullingSphere.AddComponent<SphereCollider>(); spawnCollider.radius = hideSpawnedObjectDistance; // The CullObject script determines whether to show or hide the object. CullObject spawnCuller = cullingSphere.AddComponent<CullObject>(); spawnCuller.CullingTarget = CullingTarget; } } }
new void Start() { base.Start (); AOECollider = muzzlePoint.GetComponent<BoxCollider> (); AOECollider.size = colliderDisableSize; }
// Use this for initialization void Start() { // Reference objects this.pickUp = gameObject.GetComponent<AudioSource>(); this._renderer = gameObject.GetComponent<Renderer>(); this.boxCollider = gameObject.GetComponent<BoxCollider>(); }
public void Awake() { _characterCollider = GetComponent<BoxCollider>(); _characterRigidbody = GetComponent<Rigidbody>(); _slothSnapper = GetComponent<Snapper>(); _slothController = GetComponent<SlothController>(); ragdolled = false; }
// Use this for initialization void Start() { _camera = Camera.main; amountToMove = Vector3.zero; _stats = new playerStats(); _collider = transform.GetComponent<BoxCollider>(); }
void Awake() { m_relatedCam = GameObject.Find("MogoMainUI").transform.GetChild(0).GetComponentInChildren<Camera>(); m_relatedCollider = transform.GetComponentInChildren<BoxCollider>(); m_rayHit = new RaycastHit(); }
private static void SetRightTopCollider(BoxCollider collider) { collider.center = new Vector3(3.6f, 3.13f, -13.55f); collider.size = new Vector3(1.4f, 0.14f, 0.1f); }
private static void SetLeftBottomCollider(BoxCollider collider) { collider.center = new Vector3(1.85f, -1.45f, -13.55f); collider.size = new Vector3(1.4f, 0.14f, 0.1f); }
private static void SetLeftTopCollider(BoxCollider collider) { collider.center = new Vector3(0.43f, 1.7f, -13.55f); collider.size = new Vector3(0.14f, 1.4f, 0.1f); }
private void Awake() { if (Application.isPlaying) { //color setups: if (colorRendererTarget != null) { if (colorRendererTarget.material.HasProperty("_Color")) { _normalColorRenderer = colorRendererTarget.material.color; } } if (colorImageTarget != null) { _normalColorImage = colorImageTarget.color; } } //scale setup: scaleTarget = transform; normalScale = transform.localScale; selectedScale = transform.localScale * 1.15f; pressedScale = transform.localScale * 1.25f; //set initial size on gui collider: _rectTransform = GetComponent <RectTransform>(); _boxCollider = GetComponent <BoxCollider>(); if (_rectTransform != null && _boxCollider != null) { ResizeGUIBoxCollider(_boxCollider); } //set up rigidbody: GetComponent <Rigidbody>().isKinematic = true; //refs: _rectTransform = GetComponent <RectTransform>(); _boxCollider = GetComponent <BoxCollider>(); if (!Application.isPlaying) { return; } //rect and event triggers: _rectTransform = GetComponent <RectTransform>(); if (_rectTransform != null) { _eventTrigger = gameObject.AddComponent <EventTrigger>(); _pressedEventTrigger = new EventTrigger.Entry(); _pressedEventTrigger.eventID = EventTriggerType.PointerDown; _releasedEventTrigger = new EventTrigger.Entry(); _releasedEventTrigger.eventID = EventTriggerType.PointerUp; _enterEventTrigger = new EventTrigger.Entry(); _enterEventTrigger.eventID = EventTriggerType.PointerEnter; _exitEventTrigger = new EventTrigger.Entry(); _exitEventTrigger.eventID = EventTriggerType.PointerExit; } //events: if (_rectTransform != null) { //event registrations: _pressedEventTrigger.callback.AddListener((data) => { OnPointerDownDelegate((PointerEventData)data); }); _eventTrigger.triggers.Add(_pressedEventTrigger); _releasedEventTrigger.callback.AddListener((data) => { OnPointerUpDelegate((PointerEventData)data); }); _eventTrigger.triggers.Add(_releasedEventTrigger); _enterEventTrigger.callback.AddListener((data) => { OnPointerEnterDelegate((PointerEventData)data); }); _eventTrigger.triggers.Add(_enterEventTrigger); _exitEventTrigger.callback.AddListener((data) => { OnPointerExitDelegate((PointerEventData)data); }); _eventTrigger.triggers.Add(_exitEventTrigger); } }
void GenerateBounds(Mesh me, List <Transform> bo) { GameObject meshTrace = new GameObject("Trace"); string[] bonesBatch = new string[] { "bau_L_Hand", "bau_R_Hand" }; //子节点作为AABB盒合并的 string[] bonesIgnore = new string[] { "bad_Pelvis", "bau_Neck", "bau_L_Clavicle", "bau_R_Clavicle" }; //忽略的 List <Transform> tr = new List <Transform>(); List <Transform> ig = new List <Transform>(); for (int i = 0; i < bonesBatch.Length; i++) { tr.Add(Global.Control(bonesBatch[i], bo[0].gameObject).transform); } for (int i = 0; i < bonesIgnore.Length; i++) { ig.Add(Global.Control(bonesIgnore[i], bo[0].gameObject).transform); } meshTrace.transform.position = Vector3.zero; meshTrace.transform.rotation = Quaternion.identity; //MeshFilter meTrace = meshTrace.AddComponent<MeshFilter>(); //Mesh me2 = new Mesh(); //List<Vector3> vert = new List<Vector3>(); //List<int> triangle = new List<int>(); Dictionary <Transform, AABBVector> bounds = new Dictionary <Transform, AABBVector>(); for (int i = 0; i < me.vertexCount; i++) { float weightMax = 0.0f; int boneIdx = -1; if (weightMax < me.boneWeights[i].weight0) { weightMax = me.boneWeights[i].weight0; boneIdx = me.boneWeights[i].boneIndex0; } if (weightMax < me.boneWeights[i].weight1) { weightMax = me.boneWeights[i].weight1; boneIdx = me.boneWeights[i].boneIndex1; } if (weightMax < me.boneWeights[i].weight2) { weightMax = me.boneWeights[i].weight2; boneIdx = me.boneWeights[i].boneIndex2; } if (weightMax < me.boneWeights[i].weight3) { weightMax = me.boneWeights[i].weight3; boneIdx = me.boneWeights[i].boneIndex3; } if (bounds.ContainsKey(bo[boneIdx])) { AABBVector b = bounds[bo[boneIdx]]; Vector3 p = bo[boneIdx].worldToLocalMatrix * me.vertices[i]; if (b.min.x > p.x) { b.min.x = p.x; } if (b.min.y > p.y) { b.min.y = p.y; } if (b.min.z > p.z) { b.min.z = p.z; } if (b.max.x < p.x) { b.max.x = p.x; } if (b.max.y < p.y) { b.max.y = p.y; } if (b.max.z < p.z) { b.max.z = p.z; } //vert.Add(me.vertices[i]); } else { //如果忽略了该骨骼,就不要执行下面的 if (ig.Contains(bo[boneIdx])) { continue; } //如果被父级合并,则用父级骨骼 bool batched = false; for (int j = 0; j < tr.Count; j++) { GameObject obj = Global.Control(bo[boneIdx].name, tr[j].gameObject); if (obj != null) { if (bounds.ContainsKey(tr[j])) { AABBVector b = bounds[tr[j]]; Vector3 p = tr[j].worldToLocalMatrix * me.vertices[i]; if (b.min.x > p.x) { b.min.x = p.x; } if (b.min.y > p.y) { b.min.y = p.y; } if (b.min.z > p.z) { b.min.z = p.z; } if (b.max.x < p.x) { b.max.x = p.x; } if (b.max.y < p.y) { b.max.y = p.y; } if (b.max.z < p.z) { b.max.z = p.z; } } else { AABBVector b = new AABBVector(); Vector3 p = tr[j].worldToLocalMatrix * me.vertices[i]; b.min.x = p.x; b.min.y = p.y; b.min.z = p.z; b.max.x = p.x; b.max.y = p.y; b.max.z = p.z; bounds.Add(tr[j], b); //vert.Add(me.vertices[i]); } batched = true; break; } } if (batched) { continue; } else { AABBVector b = new AABBVector(); Vector3 p = bo[boneIdx].worldToLocalMatrix * me.vertices[i]; b.min.x = p.x; b.min.y = p.y; b.min.z = p.z; b.max.x = p.x; b.max.y = p.y; b.max.z = p.z; bounds.Add(bo[boneIdx], b); //vert.Add(me.vertices[i]); } } } //for (int i = 0; i < me.triangles.Length; i++) // triangle.Add(me.triangles[i]); //me2.vertices = vert.ToArray(); //me2.triangles = triangle.ToArray(); //meTrace.mesh = me2; //meTrace.gameObject.AddComponent<MeshRenderer>(); foreach (var each in bounds) { BoxCollider b = each.Key.gameObject.AddComponent <BoxCollider>(); Vector3 v = ((each.Value.max + each.Value.min) / 2); b.center = Vector3.zero; b.size = each.Value.max - each.Value.min; b.enabled = true; b.isTrigger = true; //int idx = WsGlobal.AddDebugLine(each.Value.max, each.Value.min, Color.red); //BoxCollider box = WsGlobal.DebugLine[idx].AddComponent<BoxCollider>(); //box.center = Vector3.zero; //box.size = each.Value.max - each.Value.min; } }
//IMPORTANT INFO!// //The prefab MUST have a Bounding Box with zeroed out transform, rotation, and 1, 1, 1 scale //All adjustments to the Bounding Box must be done on the collider only using the //"Edit Collider" button if you need to change the size //this assumes that the BoundingBox transform is zeroed out according to the root transform of the prefab public bool CheckSpawnArea(SimObjPhysics simObj, Vector3 position, Quaternion rotation, bool spawningInHand) { int layermask; //first do a check to see if the area is clear //if spawning in the agent's hand, ignore collisions with the Agent if (spawningInHand) { layermask = 1 << 8; } //oh we are spawning it somehwere in the environment, we do need to make sure not to spawn inside the agent or the environment else { layermask = (1 << 8) | (1 << 10); } //get list of all active colliders of sim object, then toggle them off for now //disable all colliders of the object being placed List <Collider> colsToDisable = new List <Collider>(); foreach (Collider g in simObj.MyColliders) { //only track this collider if it's enabled by default //some objects, like houseplants, might have colliders in their simObj.MyColliders that are disabled if (g.enabled) { colsToDisable.Add(g); } } //disable collision before moving to check the spawn area foreach (Collider c in colsToDisable) { c.enabled = false; } //track original position and rotation in case we need to reset Vector3 originalPos = simObj.transform.position; Quaternion originalRot = simObj.transform.rotation; //move it into place so the bouding box is in the right spot to generate the overlap box later simObj.transform.position = position; simObj.transform.rotation = rotation; //now let's get the BoundingBox of the simObj as reference cause we need it to create the overlapbox GameObject bb = simObj.BoundingBox.transform.gameObject; BoxCollider bbcol = bb.GetComponent <BoxCollider>(); Vector3 bbCenter = bbcol.center; Vector3 bbCenterTransformPoint = bb.transform.TransformPoint(bbCenter); //keep track of all 8 corners of the OverlapBox List <Vector3> corners = new List <Vector3>(); //bottom forward right corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(bbcol.size.x, -bbcol.size.y, bbcol.size.z) * 0.5f)); //bottom forward left corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(-bbcol.size.x, -bbcol.size.y, bbcol.size.z) * 0.5f)); //bottom back left corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(-bbcol.size.x, -bbcol.size.y, -bbcol.size.z) * 0.5f)); //bottom back right corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(bbcol.size.x, -bbcol.size.y, -bbcol.size.z) * 0.5f)); //top forward right corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(bbcol.size.x, bbcol.size.y, bbcol.size.z) * 0.5f)); //top forward left corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(-bbcol.size.x, bbcol.size.y, bbcol.size.z) * 0.5f)); //top back left corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(-bbcol.size.x, bbcol.size.y, -bbcol.size.z) * 0.5f)); //top back right corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(bbcol.size.x, bbcol.size.y, -bbcol.size.z) * 0.5f)); SpawnCorners = corners; #if UNITY_EDITOR m_Started = true; gizmopos = bb.transform.TransformPoint(bbCenter); //gizmopos = inst.transform.position; gizmoscale = bbcol.size; //gizmoscale = simObj.BoundingBox.GetComponent<BoxCollider>().size; gizmoquaternion = rotation; #endif //move sim object back to it's original spot back so the overlap box doesn't hit it simObj.transform.position = originalPos; simObj.transform.rotation = originalRot; //re-enable the collision after returning in place foreach (Collider c in colsToDisable) { c.enabled = true; } //spawn overlap box Collider[] hitColliders = Physics.OverlapBox(bbCenterTransformPoint, bbcol.size / 2.0f, rotation, layermask, QueryTriggerInteraction.Collide); int colliderCount = 0; //if a collider was hit, then the space is not clear to spawn if (hitColliders.Length > 0) { //filter out any AgentTriggerBoxes because those should be ignored now foreach (Collider c in hitColliders) { if (c.isTrigger && c.GetComponentInParent <PhysicsRemoteFPSAgentController>()) { continue; } else { colliderCount++; } } if (colliderCount > 0) { return(false); } } //nothing was hit, we are good! return(true); }
public bool PlaceObject(SimObjPhysics sop, ReceptacleSpawnPoint rsp, bool PlaceStationary, int degreeIncrement, bool AlwaysPlaceUpright) { if (rsp.ParentSimObjPhys == sop) { #if UNITY_EDITOR Debug.Log("Can't place object inside itself!"); #endif return(false); } //remember the original rotation of the sim object if we need to reset it //Quaternion originalRot = sop.transform.rotation; Vector3 originalPos = sop.transform.position; Quaternion originalRot = sop.transform.rotation; //get the bounding box of the sim object we are trying to place BoxCollider oabb = sop.BoundingBox.GetComponent <BoxCollider>(); //zero out rotation and velocity/angular velocity, then match the target receptacle's rotation sop.transform.rotation = rsp.ReceptacleBox.transform.rotation; Rigidbody sopRB = sop.GetComponent <Rigidbody>(); sopRB.velocity = Vector3.zero; sopRB.angularVelocity = Vector3.zero; //set 360 degree increment to only check one angle, set smaller increments to check more angles when trying to place (warning THIS WILL GET SLOWER) int HowManyRotationsToCheck = 360 / degreeIncrement; Plane BoxBottom; float DistanceFromBoxBottomTosop; List <RotationAndDistanceValues> ToCheck = new List <RotationAndDistanceValues>(); //we'll check 8 rotations for now, replace the 45 later if we want to adjust the amount of checks //get rotations and distance values for 360/increment number of rotations around just the Y axis //we want to check all of these first so that the object is prioritized to be placed "upright" for (int i = 0; i < HowManyRotationsToCheck; i++) { oabb.enabled = true; if (i > 0) { sop.transform.Rotate(new Vector3(0, degreeIncrement, 0), Space.Self); //ToCheck[i].rotation = sop.transform.rotation; Vector3 Offset = oabb.ClosestPoint(oabb.transform.TransformPoint(oabb.center) + -rsp.ReceptacleBox.transform.up * 10); BoxBottom = new Plane(rsp.ReceptacleBox.transform.up, Offset); DistanceFromBoxBottomTosop = Math.Abs(BoxBottom.GetDistanceToPoint(sop.transform.position)); ToCheck.Add(new RotationAndDistanceValues(DistanceFromBoxBottomTosop, sop.transform.rotation)); } else { //no rotate change just yet, check the first position Vector3 Offset = oabb.ClosestPoint(oabb.transform.TransformPoint(oabb.center) + -rsp.ReceptacleBox.transform.up * 10); //was using rsp.point BoxBottom = new Plane(rsp.ReceptacleBox.transform.up, Offset); DistanceFromBoxBottomTosop = BoxBottom.GetDistanceToPoint(sop.transform.position); ToCheck.Add(new RotationAndDistanceValues(DistanceFromBoxBottomTosop, sop.transform.rotation)); } oabb.enabled = false; } //continue to check rotations about the X and Z axes if the object doesn't have to be placed upright if (!AlwaysPlaceUpright) { //ok now try if the X and Z local axis are rotated if it'll fit //these values can cause the object to be placed at crazy angles, so we'll check these last for (int i = 0; i < HowManyRotationsToCheck; i++) { oabb.enabled = true; if (i > 0) { sop.transform.Rotate(new Vector3(0, degreeIncrement, 0), Space.Self); Quaternion oldRotation = sop.transform.rotation; //now add more points by rotating the x axis at this current y rotation for (int j = 0; j < HowManyRotationsToCheck; j++) { sop.transform.Rotate(new Vector3(degreeIncrement, 0, 0), Space.Self); Vector3 Offset = oabb.ClosestPoint(oabb.transform.TransformPoint(oabb.center) + -rsp.ReceptacleBox.transform.up * 10); BoxBottom = new Plane(rsp.ReceptacleBox.transform.up, Offset); DistanceFromBoxBottomTosop = Math.Abs(BoxBottom.GetDistanceToPoint(sop.transform.position)); ToCheck.Add(new RotationAndDistanceValues(DistanceFromBoxBottomTosop, sop.transform.rotation)); } sop.transform.rotation = oldRotation; //now add EVEN more points by rotating the z axis at this current y rotation for (int j = 0; j < HowManyRotationsToCheck; j++) { sop.transform.Rotate(new Vector3(0, 0, degreeIncrement), Space.Self); Vector3 Offset = oabb.ClosestPoint(oabb.transform.TransformPoint(oabb.center) + -rsp.ReceptacleBox.transform.up * 10); BoxBottom = new Plane(rsp.ReceptacleBox.transform.up, Offset); DistanceFromBoxBottomTosop = Math.Abs(BoxBottom.GetDistanceToPoint(sop.transform.position)); ToCheck.Add(new RotationAndDistanceValues(DistanceFromBoxBottomTosop, sop.transform.rotation)); } sop.transform.rotation = oldRotation; } oabb.enabled = false; } } foreach (RotationAndDistanceValues quat in ToCheck) { //if spawn area is clear, spawn it and return true that we spawned it if (CheckSpawnArea(sop, rsp.Point + rsp.ParentSimObjPhys.transform.up * (quat.distance + yoffset), quat.rotation, false)) { //translate position of the target sim object to the rsp.Point and offset in local y up sop.transform.position = rsp.Point + rsp.ReceptacleBox.transform.up * (quat.distance + yoffset);//rsp.Point + sop.transform.up * DistanceFromBottomOfBoxToTransform; sop.transform.rotation = quat.rotation; //now to do a check to make sure the sim object is contained within the Receptacle box, and doesn't have //bits of it hanging out //Check the ReceptacleBox's Sim Object component to see what Type it is. Then check to //see if the type is the kind where the Object placed must be completely contained or just the bottom 4 corners contained int HowManyCornersToCheck = 0; if (ReceptacleRestrictions.OnReceptacles.Contains(rsp.ParentSimObjPhys.ObjType)) { //check that only the bottom 4 corners are in bounds HowManyCornersToCheck = 4; } if (ReceptacleRestrictions.InReceptacles.Contains(rsp.ParentSimObjPhys.ObjType)) { //check that all 8 corners are within bounds HowManyCornersToCheck = 8; } if (ReceptacleRestrictions.InReceptaclesThatOnlyCheckBottomFourCorners.Contains(rsp.ParentSimObjPhys.ObjType)) { //only check bottom 4 corners even though the action is PlaceIn HowManyCornersToCheck = 4; } int CornerCount = 0; //Plane rspPlane = new Plane(rsp.Point, rsp.ParentSimObjPhys.transform.up); //now check the corner count for either the 4 lowest corners, or all 8 corners depending on Corner Count //attmpt to sort corners so that first four corners are the corners closest to the spawn point we are checking against SpawnCorners.Sort(delegate(Vector3 p1, Vector3 p2) { //sort by making a plane where rsp.point is, find the four corners closest to that point //return rspPlane.GetDistanceToPoint(p1).CompareTo(rspPlane.GetDistanceToPoint(p2)); //^ this ended up not working because if something is placed at an angle this no longer makes sense... return(Vector3.Distance(p1, rsp.Point).CompareTo(Vector3.Distance(p2, rsp.Point))); // return Vector3.Distance(new Vector3(0, p1.y, 0), new Vector3(0, rsp.Point.y, 0)).CompareTo( // Vector3.Distance(new Vector3(0, p2.y, 0), new Vector3(0, rsp.Point.y, 0))); }); //ok so this is just checking if there are enough corners in the Receptacle Zone to consider it placed correctly. //originally this looped up to i < HowManyCornersToCheck, but if we just check all the corners, regardless of //sort order, it seems to bypass the issue above of how to sort the corners to find the "bottom" 4 corners, so uh // i guess this might just work without fancy sorting to determine the bottom 4 corners... especially since the "bottom corners" starts to lose meaning as objects are rotated for (int i = 0; i < 8; i++) { if (rsp.Script.CheckIfPointIsInsideReceptacleTriggerBox(SpawnCorners[i])) { CornerCount++; } } //if not enough corners are inside the receptacle, abort if (CornerCount < HowManyCornersToCheck) { sop.transform.rotation = originalRot; sop.transform.position = originalPos; return(false); } //one final check, make sure all corners of object are "above" the receptacle box in question, so we //dont spawn stuff half on a table and it falls over foreach (Vector3 v in SpawnCorners) { if (!rsp.Script.CheckIfPointIsAboveReceptacleTriggerBox(v)) { sop.transform.rotation = originalRot; sop.transform.position = originalPos; return(false); } } //set true if we want objects to be stationary when placed. (if placed on uneven surface, object remains stationary) //if false, once placed the object will resolve with physics (if placed on uneven surface object might slide or roll) if (PlaceStationary == true) { //make object being placed kinematic true sop.GetComponent <Rigidbody>().collisionDetectionMode = CollisionDetectionMode.Discrete; sop.GetComponent <Rigidbody>().isKinematic = true; //check if the parent sim object is one that moves like a drawer - and would require this to be parented //if(rsp.ParentSimObjPhys.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanOpen)) sop.transform.SetParent(rsp.ParentSimObjPhys.transform); //if this object is a receptacle and it has other objects inside it, drop them all together if (sop.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.Receptacle)) { PhysicsRemoteFPSAgentController agent = GameObject.Find("FPSController").GetComponent <PhysicsRemoteFPSAgentController>(); agent.DropContainedObjectsStationary(sop);//use stationary version so that colliders are turned back on, but kinematics remain true } //if the target receptacle is a pickupable receptacle, set it to kinematic true as will sence we are placing stationary if (rsp.ParentSimObjPhys.PrimaryProperty == SimObjPrimaryProperty.CanPickup) { rsp.ParentSimObjPhys.GetComponent <Rigidbody>().isKinematic = true; } } //place stationary false, let physics drop everything too else { //if not placing stationary, put all objects under Objects game object GameObject topObject = GameObject.Find("Objects"); //parent to the Objects transform sop.transform.SetParent(topObject.transform); Rigidbody rb = sop.GetComponent <Rigidbody>(); rb.isKinematic = false; rb.collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic; //if this object is a receptacle and it has other objects inside it, drop them all together if (sop.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.Receptacle)) { PhysicsRemoteFPSAgentController agent = GameObject.Find("FPSController").GetComponent <PhysicsRemoteFPSAgentController>(); agent.DropContainedObjects(sop); } } sop.isInAgentHand = false;//set agent hand flag // #if UNITY_EDITOR // Debug.Log(sop.name + " succesfully spawned in " +rsp.ParentSimObjPhys.name + " at coordinate " + rsp.Point); // #endif return(true); } } //reset rotation if no valid spawns found //oh now we couldn't spawn it, all the spawn areas were not clear sop.transform.rotation = originalRot; sop.transform.position = originalPos; return(false); }
void Start() { _collider = GetComponent <BoxCollider>(); _audioSource = GetComponent <AudioSource>(); }
void Start() { referenceCollider = GetComponent <BoxCollider>(); moveAction = ActionHandler.instance.GetAction(ActionHandler.actions.StreetView.Move); ActionHandler.actions.StreetView.Enable(); }
// Start is called before the first frame update void Start() { this.boxCollider = GetComponent <BoxCollider>(); }
void InitStateMachine() { m_stateMachine = new AStateMachine <HeroState, LogicEvents>(HeroState.None); m_stateMachine.BlindStateEventHandler(HeroState.Strategy, delegate(object obj) { LogicArg arg = (LogicArg)obj; Block block = (Block)arg.GetMessage(M_Event.BLOCK); Debug.Log("Get event" + arg.type); if (arg.type == LogicEvents.ConfirmHero) { Debug.Log("Get Confirm Hero" + block.SimpleBlock + " " + TemBlock.SimpleBlock); if (TemBlock != null && TemBlock.Equals(block)) { m_stateMachine.State = HeroState.StrategyMove; } else { m_stateMachine.State = HeroState.Strategy; } } else if (arg.type == LogicEvents.SelectBlock) { m_stateMachine.State = HeroState.Strategy; } }); m_stateMachine.BlindStateEventHandler(HeroState.StrategyMove, delegate(object obj) { LogicArg arg = (LogicArg)obj; Block block = (Block)arg.GetMessage(M_Event.BLOCK); if (arg.type == LogicEvents.ConfirmHero) { if (TemBlock != null && TemBlock.Equals(block)) { m_stateMachine.State = HeroState.StrategyAttack; } else { m_stateMachine.State = HeroState.Strategy; } } else if (arg.type == LogicEvents.SelectBlock) { m_stateMachine.State = HeroState.Strategy; } }); m_stateMachine.BlindStateEventHandler(HeroState.StrategyAttack, delegate(object obj) { LogicArg arg = (LogicArg)obj; Block block = (Block)arg.GetMessage(M_Event.BLOCK); if (arg.type == LogicEvents.ConfirmHero) { if (TemBlock != null && TemBlock.Equals(block)) { m_stateMachine.State = HeroState.StrategyMove; } else { m_stateMachine.State = HeroState.Strategy; } } else if (arg.type == LogicEvents.SelectBlock) { m_stateMachine.State = HeroState.Strategy; } }); m_stateMachine.AddEnter(HeroState.Strategy, delegate { if (m_collider == null) { m_collider = GetComponent <BoxCollider>(); } if (m_collider != null) { m_collider.size = new Vector3(2.56f, 2.56f, 1f); } if (m_collider != null) { m_collider.enabled = false; } }); m_stateMachine.AddEnter(HeroState.StrategyMove, delegate() { BattleField.ShowBlock(m_move.GetMoveRange(), BattleBlock.BlockVisualType.MoveRangeEnermy); }); m_stateMachine.AddEnter(HeroState.StrategyAttack, delegate() { BattleField.ShowBlock(m_attack.GetAttackRange(), BattleBlock.BlockVisualType.AttackRangeEnermy); }); m_stateMachine.BlindFromEveryState(LogicEvents.StrategyPhase, HeroState.Strategy); m_stateMachine.State = HeroState.Strategy; }
protected void Start() { m_Collider = GetComponent <BoxCollider>(); m_Audio = GetComponent <AudioSource>(); m_StartingColliderHeight = m_Collider.bounds.size.y; }
/*private void CreateColliders () { * AddBoxCollider(xSize, ySize - roundness * 2, zSize - roundness * 2); * AddBoxCollider(xSize - roundness * 2, ySize, zSize - roundness * 2); * AddBoxCollider(xSize - roundness * 2, ySize - roundness * 2, zSize); * * Vector3 min = Vector3.one * roundness; * Vector3 half = new Vector3(xSize, ySize, zSize) * 0.5f; * Vector3 max = new Vector3(xSize, ySize, zSize) - min; * * AddCapsuleCollider(0, half.x, min.y, min.z); * AddCapsuleCollider(0, half.x, min.y, max.z); * AddCapsuleCollider(0, half.x, max.y, min.z); * AddCapsuleCollider(0, half.x, max.y, max.z); * * AddCapsuleCollider(1, min.x, half.y, min.z); * AddCapsuleCollider(1, min.x, half.y, max.z); * AddCapsuleCollider(1, max.x, half.y, min.z); * AddCapsuleCollider(1, max.x, half.y, max.z); * * AddCapsuleCollider(2, min.x, min.y, half.z); * AddCapsuleCollider(2, min.x, max.y, half.z); * AddCapsuleCollider(2, max.x, min.y, half.z); * AddCapsuleCollider(2, max.x, max.y, half.z); * }*/ private void AddBoxCollider(float x, float y, float z) { BoxCollider c = gameObject.AddComponent <BoxCollider>(); c.size = new Vector3(x, y, z); }
private void AddCollider() { boxCollider = gameObject.AddComponent <BoxCollider>(); }
public abstract void Collide(BoxCollider otherObject);
public abstract void Land(BoxCollider boxCollider);
// Use this for initialization void Start() { collider = GetComponent <BoxCollider>(); startPos = transform.position; touchId = Include.Input.RegisterTouchable(gameObject); }
public static Grid GenerateSquareGrid(int width = 5, int length = 5, float gridSize = 1, float GridToTileRatio = 1, float unwalkableRate = 0, GridManager._GridColliderType colType = GridManager._GridColliderType.Master) { string loadText = ""; if (colType == GridManager._GridColliderType.Individual) { loadText = "ScenePrefab/SquareTile_Collider"; } else if (colType == GridManager._GridColliderType.Master) { loadText = "ScenePrefab/SquareTile"; } Transform tilePrefab = Resources.Load(loadText, typeof(Transform)) as Transform; List <Transform> tileTransformList = new List <Transform>(); int unwalkableCount = 0; Vector3 pos = Vector3.zero; Transform parentT = new GameObject("GridTemp").transform; float spaceX = gridSize * GridToTileRatio; float spaceZ = gridSize * GridToTileRatio; Grid grid = new Grid(_TileType.Square, width, length, gridSize, GridToTileRatio); for (int i = 0; i < width; i++) { for (int n = 0; n < length; n++) { pos = new Vector3(i * spaceX, 0, n * spaceZ); Transform tileT = (Transform)Instantiate(tilePrefab, pos, rot); tileTransformList.Add(tileT); tileT.localScale *= gridSize; tileT.parent = parentT; #if UNITY_EDITOR tileT.name = "Tile_" + i + "x" + n; #endif tileT.gameObject.layer = TBTK.GetLayerTile(); Tile tile = tileT.gameObject.AddComponent <Tile>(); tile.type = _TileType.Square; tile.x = i; tile.y = 0; tile.z = n; grid.tileList.Add(tile); } } grid.AssignIndex(); if (unwalkableRate > 0) { unwalkableCount = (int)(grid.tileList.Count * unwalkableRate); for (int i = 0; i < unwalkableCount; i++) { int rand = Random.Range(0, grid.tileList.Count); grid.tileList[rand].walkable = false; grid.tileList[rand].gameObject.SetActive(false); //grid.tileList[rand].SetState(_TileState.Default); } } float x = (width - 1) * spaceX; float z = (length - 1) * spaceZ; parentT.position -= new Vector3(x / 2, 0, z / 2); Transform newParentT = new GameObject("SquareGrid").transform; for (int i = 0; i < tileTransformList.Count; i++) { tileTransformList[i].parent = newParentT; } DestroyImmediate(parentT.gameObject); grid.gridObj = newParentT.gameObject; newParentT.gameObject.layer = TBTK.GetLayerTile(); if (colType == GridManager._GridColliderType.Master) { BoxCollider boxCol = newParentT.gameObject.AddComponent <BoxCollider>(); boxCol.size = new Vector3(spaceX * width, 0, spaceZ * length); } //CombineMesh(newParentT); FitGridToTerrain(grid.tileList); return(grid); }
private void Start() { boxCollider = GetComponent <BoxCollider>(); actionText = FindObjectOfType <ActionText>(); notebook = FindObjectOfType <Notebook>(); }
private void Awake() { Detector = GetComponent <BoxCollider>(); }
/// <summary>Manages slider knob with snapped, target positions.</summary> /// <param name="indexReturn">Outputs the index at which the slider knob snaps. Use same variable as index</param> /// <param name="index">Input of current index, use same variable as indexReturn.</param> /// <param name="inMoveReturn">Outputs whether the player is currently sliding. Use same variable as inMove.</param> /// <param name="inMove">Input of current moving status, use same variable as inMoveReturn.</param> /// <param name="targetPositions">List of all snappable positions.</param> /// <param name="clampValues">The left and right clamp values for the knob, when unsnapped.</param> /// <param name="hitbox">Hitbox of the slider knob.</param> /// <param name="totalHitbox">Hitbox of the total area that will detect sliding.</param> public static void SliderPositionLock(this Transform _transform, out int indexReturn, int index, out bool inMoveReturn, bool inMove, Vector2[] targetPositions, Vector2 clampValues, BoxCollider hitbox, BoxCollider totalHitbox) { bool holdingDown = false; bool pressedFrame = false; Vector3 touchPos = Vector2.zero; DetectTouchesHeld(out holdingDown, out pressedFrame, out touchPos); if (pressedFrame && TouchedHitbox(totalHitbox, touchPos) && !TouchedHitbox(hitbox, touchPos)) { int bestIndex = 0; float bestDistance = 999; for (int i = 0; i < targetPositions.Length; i++) { touchPos.y = _transform.position.y; float distance = Vector2.Distance(touchPos, targetPositions[i]); if (distance < bestDistance) { bestIndex = i; bestDistance = distance; } } indexReturn = bestIndex; inMove = true; inMoveReturn = inMove; } else if (holdingDown && TouchedHitbox(totalHitbox, touchPos)) { Vector2 newPos = _transform.position; touchPos.z = 0; newPos.x = Mathf.Clamp(touchPos.x, clampValues.x, clampValues.y); _transform.position = newPos; int bestIndex = 0; float bestDistance = 999; for (int i = 0; i < targetPositions.Length; i++) { float distance = Vector2.Distance(touchPos, targetPositions[i]); if (distance < bestDistance) { bestIndex = i; bestDistance = distance; } } indexReturn = bestIndex; inMove = true; inMoveReturn = inMove; } else { int bestIndex = 0; float bestDistance = 999; for (int i = 0; i < targetPositions.Length; i++) { float distance = Vector2.Distance(_transform.position, targetPositions[i]); if (distance < bestDistance) { bestIndex = i; bestDistance = distance; } } int indexStore = bestIndex; if (inMove) { if (bestIndex == index) { inMove = false; inMoveReturn = false; //AudioManager.main.PlaySelectSound(AudioManager.SelectionSound.HighSharp, .8f, .1f, 1, 0); } indexReturn = index; } else { index = indexStore; indexReturn = indexStore; } Vector2 targetPosition = targetPositions[index]; targetPosition.x = Mathf.Clamp(targetPosition.x, clampValues.x, clampValues.y); _transform.position = Vector2.Lerp(_transform.position, targetPosition, 15 * Time.deltaTime); } inMoveReturn = inMove; }
private void Start() { meshRenderer = GetComponentInChildren <MeshRenderer>(); boxCollider = GetComponent <BoxCollider>(); }
/// <summary> /// Draws a wireframe box given a <see cref="BoxCollider"/>. /// </summary> public static void DrawBoxCollider(BoxCollider box) { DrawBoxCollider(box, Color.green); }
public static GameObject CreatePlacedObject(PlacedObjectData_v2 data, Transform parent, bool previewGo = false) { // Custom models like Handpainted Models have insanley different scales (< 0.0 to 200+) Set all models as a child to a parent, so // EditMode can uniformly scale properly. GameObject parentGo = new GameObject(); GameObject childGo; parentGo.transform.parent = parent; if (data.modelID == 0) { childGo = MeshReplacement.ImportCustomFlatGameobject(data.archive, data.record, Vector3.zero, parentGo.transform); if (childGo == null) { childGo = GameObjectHelper.CreateDaggerfallBillboardGameObject(data.archive, data.record, parentGo.transform); } } else { Matrix4x4 matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, Vector3.one); childGo = MeshReplacement.ImportCustomGameobject(data.modelID, parentGo.transform, matrix); if (childGo == null) { childGo = GameObjectHelper.CreateDaggerfallMeshGameObject(data.modelID, parentGo.transform); } } parentGo.transform.eulerAngles = Vector3.zero; childGo.transform.eulerAngles = Vector3.zero; if (previewGo) { data.isLight = true; } BoxCollider parentCollider = parentGo.AddComponent <BoxCollider>(); BoxCollider childCollider; //Expanding collider a little gives better hit detection. float buffer = 0.02f; // Some custom models have a box collider and are made of multiple smaller models. Get the parent collider size. if (childCollider = childGo.GetComponent <BoxCollider>()) { parentCollider.size = new Vector3((childCollider.size.x * childGo.transform.localScale.x) + buffer, (childCollider.size.y * childGo.transform.localScale.y) + buffer, (childCollider.size.z * childGo.transform.localScale.z) + buffer); parentCollider.center = new Vector3(childCollider.center.x * childGo.transform.localScale.x, childCollider.center.y * childGo.transform.localScale.y, childCollider.center.z * childGo.transform.localScale.z); // Child colliders screw with EditMode. GameObject.Destroy(childCollider); } else { Bounds childBounds = childGo.GetComponent <MeshFilter>().sharedMesh.bounds; parentCollider.size = new Vector3((childBounds.size.x * childGo.transform.localScale.x) + buffer, (childBounds.size.y * childGo.transform.localScale.y) + buffer, (childBounds.size.z * childGo.transform.localScale.z) + buffer); parentCollider.center = new Vector3(childBounds.center.x * childGo.transform.localScale.x, childBounds.center.y * childGo.transform.localScale.y, childBounds.center.z * childGo.transform.localScale.z); } parentCollider.isTrigger = true; parentGo.AddComponent <PlacedObject>(); SetPlacedObject(data, parentGo); return(parentGo); }
// Use this for initialization void Start() { rend = this.GetComponent <Renderer>(); boxCollider = (BoxCollider)gameObject.AddComponent(typeof(BoxCollider)); UpdateCollider(); }
void RotateTheMesh() { List <Transform> children = new List <Transform>(); Transform current = UnityEditor.Selection.activeTransform; MeshFilter mf; if (current == null) { error = "No appropriate object selected."; Debug.Log(error); return; } if (current.localScale.x < 0.0 || current.localScale.y < 0.0f || current.localScale.z < 0.0f) { error = "Cannot process game object with negative scale values."; Debug.Log(error); return; } mf = current.GetComponent <MeshFilter>(); if (mf == null || mf.sharedMesh == null) { error = "No mesh on the selected object"; Debug.Log(error); return; } // Create the duplicate game object GameObject go = Instantiate(current.gameObject) as GameObject; mf = go.GetComponent <MeshFilter>(); mf.sharedMesh = Instantiate(mf.sharedMesh) as Mesh; current = go.transform; // Disconnect any child objects and same them for later foreach (Transform child in current) { if (child != current) { children.Add(child); child.parent = null; } } // Rotate and scale the mesh Vector3[] vertices = mf.sharedMesh.vertices; for (int i = 0; i < vertices.Length; i++) { vertices[i] = current.TransformPoint(vertices[i]) - current.position; } mf.sharedMesh.vertices = vertices; // Fix the normals Vector3[] normals = mf.sharedMesh.normals; if (normals != null) { for (int i = 0; i < normals.Length; i++) { normals[i] = current.rotation * normals[i]; } } mf.sharedMesh.normals = normals; mf.sharedMesh.RecalculateBounds(); current.transform.rotation = Quaternion.identity; current.localScale = new Vector3(1, 1, 1); // Restore the children foreach (Transform child in children) { child.parent = current; } // Set selection to new game object UnityEditor.Selection.activeObject = current.gameObject; //--- Do a rudamentary fixup of mesh, box, and sphere colliders---- MeshCollider mc = current.GetComponent <MeshCollider>(); if (mc != null) { mc.sharedMesh = mf.sharedMesh; } BoxCollider bc = current.GetComponent <BoxCollider>(); if (bc != null) { DestroyImmediate(bc); current.gameObject.AddComponent <BoxCollider>(); } SphereCollider sc = current.GetComponent <SphereCollider>(); if (sc != null) { DestroyImmediate(sc); current.gameObject.AddComponent <SphereCollider>(); } if (current.GetComponent <Collider>()) { error = "Be sure to verify size of collider."; } }
private void Start() { self = GetComponent <BoxCollider>(); size = self.size; }
public static void ShowModelViewer() { if (((Mod_OnGUI_Player)GameState.s_playerCharacter).showModelViewer) { global::Console.AddMessage("Closing ModelViewer."); ((Mod_OnGUI_Player)GameState.s_playerCharacter).showModelViewer = false; modelViewerBackground.SetActive(false); } else { global::Console.AddMessage("Opening ModelViewer. Type the same command to hide it."); if (modelViewerBackground == null) { ////////////////////// finding various buttons and textures UISprite closeButton = null; UISprite[] mdo = Resources.FindObjectsOfTypeAll(typeof(UISprite)) as UISprite[]; foreach (UISprite brr in mdo) { if (brr.ToString() == "CloseButton (UISprite)" && closeButton == null) { closeButton = brr; //Console.AddMessage ("Assigning CloseButton."); } } UIMultiSpriteImageButton portraitLast = null; foreach (UIMultiSpriteImageButton btn in UnityEngine.Object.FindObjectsOfType <UIMultiSpriteImageButton>()) { if (btn.ToString() == "PartyPortrait(Clone) (UIMultiSpriteImageButton)" && portraitLast == null) { portraitLast = btn; //Console.AddMessage ("Assigning optioButton."); } } /////////////////////////////// modelViewerBackground = new GameObject("ModelViewer"); modelViewerBackground.transform.parent = portraitLast.transform.parent; modelViewerBackground.layer = portraitLast.gameObject.layer; modelViewerBackground.transform.localScale = new Vector3(1f, 1f, 1f); UISprite spr = NGUITools.AddSprite(modelViewerBackground, closeButton.atlas, "BUT_genericBGMid"); spr.transform.localScale = new Vector3(Screen.width / 4, Screen.height * 1.6f, 1f); spr.type = UISprite.Type.Sliced; spr.color = new Color(0f, 0f, 0f, 0.3f); BoxCollider cold = spr.gameObject.AddComponent <BoxCollider>(); cold.size = new Vector3(1f, 1f, 1f); spr.gameObject.AddComponent <UINoClick>().BlockClicking = true; modelViewerBackground.transform.localPosition = new Vector3(Screen.width / 10, Screen.height * 0.8f, 0); } else { modelViewerBackground.SetActive(true); } ((Mod_OnGUI_Player)GameState.s_playerCharacter).showModelViewer = true; } }
public static void ClampPosition(this Transform transform, BoxCollider box) { transform.position = box.bounds.Clamp(transform.position); }
/** * Activate the dam * * @param dropOffBox BoxCollider the box where succesfully passing fish will be dropped off */ public void Activate(BoxCollider dropOffBox) { this.dropOffBox = dropOffBox; active = true; }