// -1 means the object bounds are completely outside the explosion. // 0 means the bounds intersect. // 1 means the object bounds are completely inside the explosion. public static int BoundsCheck(DestructibleObject dtObj, Explosion exp) { Bounds oBounds = dtObj.GetComponent <Collider2D>().bounds; Vector3 ePos = new Vector3(exp.Position.x, exp.Position.y); float radSq = exp.Radius * exp.Radius; // Completely outside if ((oBounds.ClosestPoint(ePos) - ePos).sqrMagnitude >= radSq) { return(-1); } // Compute furthest point Vector3 furthestPoint = new Vector3(oBounds.min.x, oBounds.min.y, 0); if (oBounds.center.x > ePos.x) { furthestPoint.x = oBounds.max.x; } if (oBounds.center.y > ePos.y) { furthestPoint.y = oBounds.max.y; } // Completely inside if ((furthestPoint - ePos).sqrMagnitude <= radSq) { return(1); } // Bounds intersect return(0); }
public static IEnumerator OneTimeExplosionTest <T> (IExplosionExecutor ee, IPolygonSubtractor sub, int numExplosions, float explosionRadius, bool hasHoles, float radius, int numEdges, int columns, int rows) where T : DestructibleObject { // Set a constant seed so that we get the same results every time UnityEngine.Random.InitState(12345); new GameObject("Main Camera").AddComponent <Camera>().transform.position = new Vector3(0, 50, -100); // Meaure the time to create all destructible objects CreateRingsAndMeasure <T>(hasHoles, true, radius, numEdges, columns, rows); yield return(null); List <Explosion> explosions = new List <Explosion>(); for (int i = 0; i < numExplosions; ++i) { explosions.Add(new Explosion(UnityEngine.Random.Range(-10, 10), UnityEngine.Random.Range(0, 20), explosionRadius, 24)); } using (Measure.ProfilerMarkers(ProfilerMarkers.SampleGroupDefinitions)) { ProfilerMarkers.ProcessExplosions.Begin(); ee.ExecuteExplosions(explosions, DestructibleObject.FindAll(), sub); ProfilerMarkers.ProcessExplosions.End(); } yield return(null); // Wait to observe whether the result is correct yield return(WaitFrames(60)); CleanUp(); }
isAttacking; // Check if the orb is attacking #endregion // Unity Named Methods #region Main Methods /// <summary> Make the orb passive and set up access to its scripts to control its behavior </summary> void Start() { missileScript = GetComponent <LockOnMissile>(); revolveScript = GetComponent <RevolveAroundObject>(); destructible = GetComponent <DestructibleObject>(); isAttacking = false; }
private void Start() { player = GetComponent <DestructibleObject>(); ServiceLocator.Get <GameManager>().SetHealthBar(player.MaxHealth); ServiceLocator.Get <GameManager>().UpdateHealthBar(player.CurrentHealth); //DontDestroyOnLoad(gameObject); }
void Explode() { Instantiate(explosionEffect, transform.position, transform.rotation); Collider[] collidersToDestroy = Physics.OverlapSphere(transform.position, radius); foreach (Collider nearbyObject in collidersToDestroy) { DestructibleObject dest = nearbyObject.GetComponent <DestructibleObject>(); if (dest != null) { dest.Destroy(); } } Collider[] collidersToMove = Physics.OverlapSphere(transform.position, radius); foreach (Collider nearbyObject in collidersToMove) { Rigidbody rb = nearbyObject.GetComponent <Rigidbody>(); if (rb != null) { rb.AddExplosionForce(force, transform.position, radius); } } Destroy(rocket); Destroy(gameObject, 5); }
public void Hit(DestructibleObject target) { if (target.Pv > 0) { // Enemies are destroyed when damaging the objective if (target.gameObject.tag.Equals("Objective")) { gameObject.SetActive(false); } target.Pv -= Dmg; } else if (target.Pv <= 0) { if (target.gameObject.tag.Equals("Enemy")) { target.gameObject.SetActive(false); } else if (target.gameObject.tag.Equals("Objective")) { target.gameObject.SetActive(false); } else { // Game over } } }
void AimAndFire() { // Gun barrel rotation go_barrel.transform.Rotate(0, 0, currentRotationSpeed * Time.deltaTime); // if can fire turret activates if (canFire) { // start rotation currentRotationSpeed = barrelRotationSpeed; // aim at enemy Vector3 baseTargetPostition = new Vector3(go_target.position.x, this.transform.position.y, go_target.position.z); Vector3 gunBodyTargetPostition = new Vector3(go_target.position.x, go_target.position.y, go_target.position.z); go_baseRotation.transform.LookAt(baseTargetPostition); go_GunBody.transform.LookAt(gunBodyTargetPostition); // start particle system if (!muzzelFlash.isPlaying) { muzzelFlash.Play(); } //go_target.GetComponentInParent<IDamageable>().TakeDamage(damage); //go_target.GetComponentInParent<Enemy>().UpdateHealthBar(go_target.transform.GetComponentInParent<DestructibleObject>().CurrentHealth); RaycastHit hit; if (Physics.Raycast(go_barrel.transform.position, go_barrel.transform.forward, out hit, firingRange)) { Debug.Log(hit.transform.name); IDamageable target = hit.transform.GetComponentInParent <IDamageable>(); DestructibleObject enemy = hit.transform.GetComponentInParent <DestructibleObject>(); Enemy Enemy = hit.transform.GetComponentInParent <Enemy>(); // Rigidbody rb= hit.transform.GetComponentInParent<Rigidbody>(); if (target != null && Enemy != null) { target.TakeDamage(damage); Enemy.UpdateHealthBar(enemy.CurrentHealth); } if (enemy != null && enemy.CurrentHealth == 0) { ServiceLocator.Get <GameManager>().UpdateScore(10); } } } else { // slow down barrel rotation and stop currentRotationSpeed = Mathf.Lerp(currentRotationSpeed, 0, 10 * Time.deltaTime); // stop the particle system if (muzzelFlash.isPlaying) { muzzelFlash.Stop(); } } }
public void FixBarricade(DestructibleObject barricade) { if (suppliesHolder.GetGold() >= barricadeFixCost) { suppliesHolder.SpendGold(barricadeFixCost); barricade.upgradeUI.SetActive(false); barricade.Activate(); } }
private void OnTriggerEnter(Collider other) { PlayerController player = FindObjectOfType <PlayerController>(); DestructibleObject enemy = other.gameObject.GetComponent <DestructibleObject>(); if (enemy != null) { enemy.CurrentHealth = 0; player.gameObject.GetComponent <DestructibleObject>().TakeDamage(10); ServiceLocator.Get <GameManager>().UpdateHealthBar(player.gameObject.GetComponent <DestructibleObject>().CurrentHealth); } }
public static IEnumerator ContinuousExplosionTest <T> (IExplosionExecutor ee, IPolygonSubtractor sub, int numExplosions, float explosionRadius, float explosionInterval, bool hasHoles, float radius, int numEdges, int columns, int rows, int warmupFrames, int captureFrames) where T : DestructibleObject { // Set a constant seed so that we get the same results every time UnityEngine.Random.InitState(12345); new GameObject("Main Camera").AddComponent <Camera>().transform.position = new Vector3(0, 50, -100); // Meaure the time to create all destructible objects CreateRingsAndMeasure <T>(hasHoles, true, radius, numEdges, columns, rows); // Set all objects to static var dObjs = DestructibleObject.FindAll(); foreach (var dObj in dObjs) { dObj.GetComponent <Rigidbody2D>().bodyType = RigidbodyType2D.Static; } yield return(null); float explosionTimer = 0; // To be called every fixed update; // Generates a number of explosions every time the timer reaches a fixed interval. void explosionGenerator() { explosionTimer += Time.fixedDeltaTime; List <Explosion> explosions = new List <Explosion>(); while (explosionTimer > explosionInterval) { explosionTimer -= explosionInterval; for (int i = 0; i < numExplosions; ++i) { explosions.Add(new Explosion(UnityEngine.Random.Range(-10, 10), UnityEngine.Random.Range(0, 20), explosionRadius, 24)); } } ProfilerMarkers.ProcessExplosions.Begin(); ee.ExecuteExplosions(explosions, DestructibleObject.FindAll(), sub); ProfilerMarkers.ProcessExplosions.End(); } // Allow objects to collide before we measure physics yield return(WarmupFrames(warmupFrames, explosionGenerator)); // Measure physics yield return(CaptureFrames(captureFrames, explosionGenerator)); CleanUp(); }
private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.GetComponent <DestructibleObject>() != null) { DestructibleObject DO = collision.gameObject.GetComponent <DestructibleObject>(); if (DO.faction != faction) { DO.takeDamage(attackType, dmg); onDestroy(); } } }
public void PlayerShoot() { RaycastHit hit; if (Physics.Raycast(fpsCamera.transform.position, fpsCamera.transform.forward, out hit, range)) { Debug.Log(hit.transform.name); if (!laser.enabled) { laser.enabled = true; } laser.SetPosition(0, muzzleTransform.transform.position); Vector3 endposition = hit.point; laser.SetPosition(1, endposition); IDamageable target = hit.transform.GetComponentInParent <IDamageable>(); DestructibleObject enemy = hit.transform.GetComponentInParent <DestructibleObject>(); Enemy Enemy = hit.transform.GetComponentInParent <Enemy>(); // Rigidbody rb= hit.transform.GetComponentInParent<Rigidbody>(); if (target != null && Enemy != null) { target.TakeDamage(damage); Enemy.UpdateHealthBar(enemy.CurrentHealth); } //if (rb != null) //{ // rb.AddForce(-hit.normal * ImpactForce); //} //GameObject impactGO = Instantiate(impacteffect, hit.point, Quaternion.LookRotation(hit.normal)); //Destroy(impactGO, 2.0f); if (enemy != null && enemy.CurrentHealth == 0) { ServiceLocator.Get <GameManager>().UpdateScore(10); Instantiate(muzzleExplosion, hit.point, Quaternion.LookRotation(hit.normal)); Invoke("DestroyLaser", 0.1f); } } //if (laser.enabled) //{ // laser.enabled = false; //} Invoke("DestroyLaser", 0.1f); }
void SearchObjectToDamage() { Vector2 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition); clickedObject = Physics2D.Raycast(mouseWorldPos, Vector2.zero); if (clickedObject && clickedObject.collider.GetComponent <DestructibleObject>()) { DestructibleObject dObject = clickedObject.collider.GetComponent <DestructibleObject>(); Vector2 closestPointOnObject = clickedObject.collider.bounds.ClosestPoint(transform.position); if (Vector2.Distance(transform.position, closestPointOnObject) < 5f && dObject.State != DestructibleObject.DestructionState.Destroyed) { dObject.TakeDamage(player.damage); } } }
// Use this for initialization void Start() { m_bossAgent = GetComponent <NavMeshAgent>(); m_bossAgent.GetComponent <NavMeshAgent>().enabled = false; m_weaponController = GetComponent <WeaponController>(); m_barrels = GetComponent <DestructibleObject>(); #region ///Lerp Attempt //Starts the boss on the right side of the tracks m_boss.transform.position = m_rightSide.transform.position; //Gets the distance between the left side and right side of the tracks m_journeyLength = Vector3.Distance(m_leftSide.position, m_rightSide.position); #endregion }
void Update() { Transform t = transform; DestructibleObject d = GetComponent <DestructibleObject>(); if (d != null) { t = d.GetCurrentActiveObject().transform; } Transform playAreaTransform = VRTK_DeviceFinder.PlayAreaTransform(); if (playAreaTransform != null) { playAreaTransform.position = t.position; playAreaTransform.rotation = t.rotation; } }
private void OnTriggerEnter(Collider other) { var damageable = other.gameObject.GetComponent <IDamageable>(); if (damageable != null) { damageable.TakeDamage(bulletDamage); } Destroy(gameObject); if (other.gameObject.CompareTag("Enemy")) { DestructibleObject enemyhealth = other.gameObject.GetComponent <DestructibleObject>(); if (enemyhealth.CurrentHealth == 0) { ServiceLocator.Get <GameManager>().UpdateScore(10); } } }
protected virtual void OnCollisionEnter(Collision collision) { if (doesDamage) { DestructibleObject destructibleObject = collision.transform.GetComponent <DestructibleObject>(); if (destructibleObject) { destructibleObject.Hit(damage); } } if (destroyOnHit) { Die(); } doesDamage = false; // Once the projectile has hit something (ideally the ground) it will no longer be lethal, allowing subclasses (the weapon) to be picked up. }
private void OnCollisionEnter(Collision collision) { if (collision.gameObject == transform.parent.parent.gameObject || ignore.IndexOf(collision.gameObject) >= 0) { return; } ignore.Add(collision.gameObject); OnHit(collision); DestructibleObject destructible = collision.gameObject.GetComponent <DestructibleObject>(); if (destructible != null) { destructible.GetHit(); } itemAnimator.SetTrigger("Stop"); }
private void SpawnBarrel() { Instantiate(fireObj, transform.position, fireObj.transform.rotation); DestructibleObject destructibleObj = GetComponent <DestructibleObject>(); if (destructibleObj == null) { //Destructible objects will not spawn a barrel OilBarrel barrel = ((GameObject)Instantiate(barrelObj, transform.position, Quaternion.identity)).GetComponent <OilBarrel>(); barrel.SetValue(statsObj.oilValue); GameObject barrelOutline = Instantiate(barrelObjBG); barrelOutline.transform.position = barrel.gameObject.transform.position; barrelOutline.transform.rotation = barrel.gameObject.transform.rotation; barrelOutline.transform.localScale = barrel.transform.localScale * 1.35f; barrelOutline.transform.SetParent(barrel.gameObject.transform); barrelOutline.GetComponent <SpriteRenderer>().sortingLayerName = "Outline"; OutlinePulser outline = barrelOutline.AddComponent <OutlinePulser>(); outline.cols = new Color[3]; outline.cols[0] = Color.black; outline.cols[1] = Color.yellow; outline.cols[2] = Color.red; barrel.transform.localScale *= 1 + statsObj.oilValue / 20; } Camera.main.gameObject.GetComponent <ScreenShake>().DoScreenShake(); BackgroundManager.instance.PlaySound(3); if (type == BuildingType.GAS) { GetComponent <SpriteRenderer>().sprite = rubbleSpr; } else { Destroy(gameObject); } }
void HitATarget() { RaycastHit hit; if (Physics.Raycast(mainCamera.transform.position, mainCamera.transform.forward, out hit, range)) { DestructibleObject target = hit.transform.GetComponent <DestructibleObject>(); if (target != null) { target.TakeDamage(damage); } if (hit.rigidbody != null) { hit.rigidbody.AddForce(-hit.normal * impactForce); } GameObject impactObject = Instantiate(Impact, hit.point, Quaternion.LookRotation(hit.normal)); Destroy(impactObject, 2f); } }
void Update() { if (Input.GetMouseButtonDown(0)) { Vector3 worldPoint = Camera.ScreenToWorldPoint(Input.mousePosition); List <Explosion> explosions = new List <Explosion> { new Explosion(worldPoint.x, worldPoint.y, 2.0f, 24), }; IEnumerable <DestructibleObject> destructibleObjects = DestructibleObject.FindAll(); var stopwatch = new System.Diagnostics.Stopwatch(); stopwatch.Restart(); AdvancedIterativeExplosionExecutor.Instance.ExecuteExplosions(explosions, destructibleObjects, ORourkeSubtractor.Instance); stopwatch.Stop(); //stopwatch.LogTime("Execute Explosions"); } }
private void Update() { RaycastHit hit; Vector3 dif = transform.position - lastPosisiton; bool success = Physics.Raycast(lastPosisiton, dif.normalized, out hit, dif.magnitude, LayerMask.GetMask(interactLayers)); if (success) { if (Vector3.Distance(initialPosition, hit.point) >= inactiveDistance) { Creature creature = hit.collider.gameObject.GetComponentInParent <Creature>(); DestructibleObject destructibleObject = hit.collider.gameObject.GetComponentInParent <DestructibleObject>(); Hitbox hitbox = hit.collider.gameObject.GetComponent <Hitbox>(); if (creature != null) { int modifiedDamage = damage; if (hitbox != null) { modifiedDamage = Mathf.RoundToInt(modifiedDamage * hitbox.damageMultiplier); } creature.DealDamage(modifiedDamage); } else if (destructibleObject != null) { destructibleObject.DealDamage(damage); } if (!isPiercing) { Destroy(this.gameObject); } } } UpdateLineRenderer(); lastPosisiton = transform.position; }
public static IEnumerator SimpleTest <T>(IExplosionExecutor ee, IPolygonSubtractor sub) where T : DestructibleObject { // Set a constant seed so that we get the same results every time UnityEngine.Random.InitState(12345); new GameObject("Main Camera").AddComponent <Camera>().transform.position = new Vector3(0, 50, -100); // Meaure the time to create all destructible objects T ring; using (Measure.ProfilerMarkers(ProfilerMarkers.SampleGroupDefinitions)) { ProfilerMarkers.Creation.Begin(); ring = CreateRingObject <T>(true, 1, 4); ProfilerMarkers.Creation.End(); ring.GetComponent <Rigidbody2D>().bodyType = RigidbodyType2D.Static; } yield return(null); ring.transform.position = new Vector2(0, 0); List <Explosion> explosions = new List <Explosion>() { new Explosion(-2, 0, 2, 4), new Explosion(2, 0, 2, 4), }; using (Measure.ProfilerMarkers(ProfilerMarkers.SampleGroupDefinitions)) { ProfilerMarkers.ProcessExplosions.Begin(); ee.ExecuteExplosions(explosions, DestructibleObject.FindAll(), sub); ProfilerMarkers.ProcessExplosions.End(); } yield return(null); // Wait to observe whether the result is correct yield return(WaitFrames(60)); CleanUp(); }
private void GenerateDunkExplosion(Vector3 position, float radius, float power, int damages) { float trueRadius = radius * GameManager.i.momentumManager.momentum; float truePower = power * GameManager.i.momentumManager.momentum; int trueDamages = Mathf.RoundToInt(damages + (1 * GameManager.i.momentumManager.momentum)); Collider[] colliders = Physics.OverlapSphere(position, trueRadius); foreach (Collider hit in colliders) { Enemy potentialEnemy = hit.gameObject.GetComponent <Enemy>(); if (potentialEnemy != null) { potentialEnemy.DisableNavmeshAgent(); potentialEnemy.AddDamage(trueDamages); Rigidbody rb = hit.GetComponent <Rigidbody>(); if (rb != null) { //rb.AddForce(new Vector3(0, 5000, 0)); Debug.DrawRay(position, Vector3.up, Color.green, 10f); rb.AddExplosionForce(truePower, position, trueRadius, 3.0F); } } DestructibleObject potentialDestructibleObject = hit.gameObject.GetComponent <DestructibleObject>(); if (potentialDestructibleObject != null) { potentialDestructibleObject.Damage(1); } } Vector3 spawnPosition = new Vector3(transform.position.x, 0.05f, transform.position.z) + transform.forward * 2; spawnPosition.y = 0.05f; GameObject dunkFXRef = Instantiate(groundDunkEffect, spawnPosition, Quaternion.Euler(-90, 0, 0)); dunkFXRef.transform.localScale = new Vector3(trueRadius, trueRadius, trueRadius); Destroy(dunkFXRef, 2); }
public void ExecuteExplosions(IEnumerable <Explosion> explosions, IEnumerable <DestructibleObject> dtObjects, IPolygonSubtractor subtractor) { // Store destructible objects in a new list, since we may add or remove some during processing List <DestructibleObject> dtObjectList = dtObjects.ToList(); // Add new destructible objects to this list instead of objectList until finished processing the current explosion List <DestructibleObject> pendingAdditions = new List <DestructibleObject>(); // Process all objects for all explosions var explosionPolygons = explosions.Select(e => e.DTPolygon); var dtObjectPolygons = dtObjectList.Select(o => o.GetTransformedPolygonList()); int numInputPolygonGroups = dtObjectPolygons.Count(); var result = subtractor.SubtractBulk(dtObjectPolygons, explosionPolygons); // Iterate results corresponding to each input polygon group for (int i = 0; i < result.Count; i++) { // Add new destructible objects for any output polygon groups that could not be matched with an input polygon group if (i >= numInputPolygonGroups) { GameObject go = new GameObject(); DestructibleObject newObj = go.AddComponent <DestructibleObject>(); List <DTPolygon> polygroup = result[i][0]; newObj.ApplyTransformedPolygonList(polygroup); pendingAdditions.Add(newObj); continue; } // We know that these output polygons correspond to one or more pieces of this existing destructible object DestructibleObject dtObj = dtObjectList[i]; if (result[i].Count == 0) { // If no output polygons, remove the current destrucible object dtObjectList[i] = null; UnityEngine.Object.Destroy(dtObj.gameObject); continue; } else { // Otherwise apply the output polygons (fragments) to GameObjects (new or reused) foreach (List <DTPolygon> polygroup in result[i]) { if (polygroup != result[i].Last()) { // Duplicate the GameObject that was clipped by the explosion, so that we maintain properties such as velocity GameObject go = UnityEngine.Object.Instantiate(dtObj.gameObject, dtObj.transform.parent); DestructibleObject newObj = go.GetComponent <DestructibleObject>(); // Apply the new clipped polygon newObj.ApplyTransformedPolygonList(polygroup); // Add it to the objectList, but not until after finished processing this explosion pendingAdditions.Add(newObj); continue; } else { // Reuse the existing GameObject by applying the new clipped polygon to it dtObj.ApplyTransformedPolygonList(polygroup); continue; } } } } // Delete any entries that were set to null for (int i = 0; i < dtObjectList.Count; ++i) { if (dtObjectList[i] == null) { dtObjectList.RemoveAt(i--); } } // Add pendingAdditions elements to objectList so that they are included when processing the next explosion in explosions dtObjectList.AddRange(pendingAdditions); pendingAdditions.Clear(); }
public void AddDestructibleObject(DestructibleObject theObject) { destObjectsMap.Add(new Point((int)theObject.Center.X, (int)theObject.Center.Y), theObject); }
private void Update() { Animator anim = GetComponentInChildren <Animator>(); GameController gc = GameController.GetInstance(); RiverGenerator rg = gc.riverGenerator; Creature cr = GetComponent <Creature>(); // apply acceleration velocity += Vector3.ClampMagnitude(GetAcceleration(), maxAcceleration) * Time.deltaTime; // apply water resistance Vector3 waterSpeed = rg.GetWaterSpeedAt(transform.position); velocity += (waterSpeed - velocity) * waterResistance * Time.deltaTime; // enforce max velocity relative to water speed velocity = Vector3.ClampMagnitude(velocity - waterSpeed, maxSpeed) + waterSpeed; velocity.Scale(new Vector3(1, 0, 1)); // Apply gravity when dead if (cr.IsDead() && (anim.GetCurrentAnimatorStateInfo(0).IsName("Dead"))) { velocity += Vector3.down * beaverSinkSpeed * Time.deltaTime; } // move according to velocity transform.position += velocity * Time.deltaTime; // calculate the beaver's rotation and animation blending if (!cr.IsDead()) { Vector3 oldRotation = transform.rotation.eulerAngles; Quaternion desiredRotation = transform.rotation; // figure out where the beaver wants to look if (target != null && lookAtBoatVSDirectionBlending != null) { float distanceToTarget = Vector3.Distance(target.position, transform.position); // Use more precise distance if target collider is available if (targetCollider != null) { distanceToTarget = Vector3.Distance(targetCollider.ClosestPoint(transform.position), transform.position); } // blend between looking to boat and looking forwards depending on distance float lookAtTarget = lookAtBoatVSDirectionBlending.Evaluate(distanceToTarget); desiredRotation = Quaternion.Lerp( Quaternion.LookRotation(velocity - waterSpeed, Vector3.up), Quaternion.LookRotation(target.position - transform.position, Vector3.up), lookAtTarget ); } // "Lerp" the beaver towards the desired rotation over time transform.rotation = Quaternion.Lerp(transform.rotation, desiredRotation, rotationLerp * Time.deltaTime); // Set the beavers apparent curvature depending on rotation change float rotationChange = Mathf.DeltaAngle(oldRotation.y, transform.rotation.eulerAngles.y) / Time.deltaTime; anim.SetFloat("Blend", rotationChange / fullTurnAngle); // determine if attacking if (attackTimer == 0f && !anim.GetCurrentAnimatorStateInfo(0).IsName("Attack")) { // look for attackable objects SphereCollider attackSphere = attackPoint.GetComponent <SphereCollider>(); Collider[] attackResult = Physics.OverlapSphere(attackPoint.transform.position, attackSphere.radius, LayerMask.GetMask(attackLayerMask)); foreach (Collider col in attackResult) { DestructibleObject d = col.gameObject.GetComponentInParent <DestructibleObject>(); if (d != null && d.objectMaterial == DestructibleObject.DestructibleObjectMaterial.WOOD) { // attack! objectAttacking = d; anim.SetTrigger("Attack"); attackTimer = attackCooldown; } } } } // Update timers attackTimer -= Mathf.Min(Time.deltaTime, attackTimer); }
// Start is called before the first frame update void Start() { powerBar = GameObject.Find("PowerBar"); destructible = gameObject.GetComponent <DestructibleObject>(); }
public void ExecuteExplosions(IEnumerable <Explosion> explosions, IEnumerable <DestructibleObject> dtObjects, IPolygonSubtractor subtractor) { // Store destructible objects in a new list, since we may add or remove some during processing List <DestructibleObject> dtObjectList = dtObjects.ToList(); // Add new destructible objects to this list instead of objectList until finished processing the current explosion List <DestructibleObject> pendingAdditions = new List <DestructibleObject>(); // Process all objects for all explosions foreach (var exp in explosions) { List <List <DTPolygon> > relevantObjectPolygons = new List <List <DTPolygon> >(); List <int> relevantObjectIndices = new List <int>(); for (int i = 0; i < dtObjectList.Count; ++i) { var dtObj = dtObjectList[i]; // Do basic AABB-circle check to see whether we can skip processing this destructible object with this explosion int bc = DTUtility.BoundsCheck(dtObj, exp); if (bc == -1) { // Object is not affected by explosion continue; } else if (bc == 1) { // Object is completely removed by explosion dtObjectList[i] = null; UnityEngine.Object.Destroy(dtObj.gameObject); continue; } else { // Add object to the input list for the subtractor relevantObjectPolygons.Add(dtObj.GetTransformedPolygonList()); relevantObjectIndices.Add(i); continue; } } var result = subtractor.SubtractBulk(relevantObjectPolygons, new DTPolygon[] { exp.DTPolygon }); // Iterate results corresponding to each input polygon group for (int i = 0; i < result.Count; i++) { // Add new destructible objects for any output polygons that could not be matched with an input polygon if (i >= relevantObjectPolygons.Count) { GameObject go = new GameObject(); DestructibleObject newObj = go.AddComponent <DestructibleObject>(); List <DTPolygon> polygroup = result[i][0]; newObj.ApplyTransformedPolygonList(polygroup); pendingAdditions.Add(newObj); continue; } // We know that these output polygons correspond to one or more pieces of this existing destructible object DestructibleObject dtObj = dtObjectList[relevantObjectIndices[i]]; if (result[i].Count == 0) { // If no output polygons, remove the current destrucible object dtObjectList[relevantObjectIndices[i]] = null; UnityEngine.Object.Destroy(dtObj.gameObject); continue; } else { // Otherwise apply the output polygons (fragments) to GameObjects (new or reused) foreach (List <DTPolygon> polygroup in result[i]) { if (polygroup != result[i].Last()) { // Duplicate the GameObject that was clipped by the explosion, so that we maintain properties such as velocity GameObject go = UnityEngine.Object.Instantiate(dtObj.gameObject, dtObj.transform.parent); DestructibleObject newObj = go.GetComponent <DestructibleObject>(); // Apply the new clipped polygon newObj.ApplyTransformedPolygonList(polygroup); // Add it to the objectList, but not until after finished processing this explosion pendingAdditions.Add(newObj); continue; } else { // Reuse the existing GameObject by applying the new clipped polygon to it dtObj.ApplyTransformedPolygonList(polygroup); continue; } } } } // Delete any entries that were set to null for (int i = 0; i < dtObjectList.Count; ++i) { if (dtObjectList[i] == null) { dtObjectList.RemoveAt(i--); } } // Add pendingAdditions elements to objectList so that they are included when processing the next explosion in explosions dtObjectList.AddRange(pendingAdditions); pendingAdditions.Clear(); } }
public IEnumerator attack() { #region Item Collider2D[] coll = Physics2D.OverlapCircleAll(transform.position, 1); Item item = null; for (int i = 0; i < coll.Length; i++) { if (coll[i].GetComponent <Item>() != null) { item = coll[i].GetComponent <Item>(); break; } } if (item != null) { //StartCoroutine("takeWeapon"); Debug.Log("Guantes"); ApplyItem(item); } #endregion #region DestructibleItem Collider2D[] coll2 = Physics2D.OverlapCircleAll(transform.position, 1); DestructibleObject saco = null; for (int i = 0; i < coll2.Length; i++) { if (coll2[i].GetComponent <DestructibleObject>() != null) { saco = coll2[i].GetComponent <DestructibleObject>(); Debug.Log("Un saco"); break; } } if (saco != null) { saco.RecieveHit(); Debug.Log("Le quedan " + saco.healt); } #endregion #region Enemy Collider2D[] coll3 = Physics2D.OverlapCircleAll(transform.position, 1.5f); Enemy Tayson = null; for (int i = 0; i < coll3.Length; i++) { if (coll3[i].GetComponent <Enemy>() != null) { Tayson = coll3[i].GetComponent <Enemy>(); Debug.Log("Un Negro"); break; } } if (Tayson != null) { Tayson.RecieveDamage(m_punchDamage); Debug.Log("Le quedan " + Tayson.m_life); } #endregion #region Animation if (m_isGrounded && !m_isBlocking) { m_rigidBody.velocity = Vector2.zero; m_mainCharacterAnimation.ChangeAnimatorState("movingTransition", 4); yield return(new WaitForSeconds(0.5f)); m_mainCharacterAnimation.ChangeAnimatorState("movingTransition", 0); } #endregion }