void DealRadialDamage(Vector3 origin) { Collider[] all_enemies_in_range = Physics.OverlapSphere(origin, Range, shootableMask); foreach (Collider c in all_enemies_in_range) { EnemyHealth enemyHealth = c.GetComponent <EnemyHealth>(); if (null != enemyHealth) { Rigidbody rb = c.GetComponent <Rigidbody>(); rb?.AddExplosionForce(Damage * 500f, origin, Range, 1f, ForceMode.Impulse); enemyHealth?.TakeDamage(Damage, c.transform.position + new Vector3(0f, 0.25f)); } } }
public override void Act(GameObject g) { Collider[] colliders = Physics.OverlapSphere(g.transform.position + explosionOffset, explosionRange, layermask); foreach (Collider c in colliders) { if (c.gameObject != g) { Rigidbody r = c.attachedRigidbody; r?.AddExplosionForce(explosionForce, g.transform.position + explosionOffset, explosionRange, upwardModifier); } } }
private void OnCollisionEnter(Collision collision) // => gdy wykryje kolizje => rysuje niewidzialna sfere { Collider[] hitColliders = Physics.OverlapSphere(transform.position, radius); int i = 0; while (i < hitColliders.Length) { Rigidbody rb = hitColliders[i].GetComponent <Rigidbody>(); if (rb != null) { rb?.AddExplosionForce(force, transform.position, radius); } i++; } Destroy(this.gameObject); }
public void Explode() { Instantiate(explosionPrefab, new Vector3(transform.position.x, transform.position.y - transform.lossyScale.y / 2, transform.position.z), Quaternion.identity); Collider[] hitColliders = Physics.OverlapSphere(transform.position, ExplosionRadius); foreach (Collider c in hitColliders) { IAmRigid pushable = c.GetComponent <IAmRigid>(); if (pushable != null) { pushable.LoseControl(); Rigidbody rb = c.GetComponent <Rigidbody>(); rb?.AddExplosionForce(300.0f, transform.position, ExplosionRadius); } } }
public void ExplosionCubes(Vector3 point) { List <Vector3> LayerPositions = new List <Vector3>(); /* * * float SeperationZ = PieceSize.z; * float SeperationX = PieceSize.x; * * List<Vector3> RowPositions = new List<Vector3>(); * * for(int i = 0; i < Pieces; i++) * { * RowPositions.Add(new Vector3(0, 0, SeperationZ * i)); * } * * * for(int i = 0; i < Pieces; i++) * { * for (int j = 0; j < RowPositions.Count; j++) * { * Vector3 vector = RowPositions[j]; * vector.x = SeperationX * i; * LayerPositions.Add(vector); * } * } */ Vector3 Size = this.transform.localScale; Vector3 PieceSize = Size / Pieces; for (int i = 0; i < Pieces; i++) { for (int j = 0; j < Pieces; j++) { for (int k = 0; k < Pieces; k++) { Vector3 PiecePosition = new Vector3((PieceSize.x * j) - PieceSize.x, (PieceSize.y * i) - PieceSize.y, (PieceSize.z * k) - PieceSize.z); LayerPositions.Add(PiecePosition); } } } foreach (Vector3 position in LayerPositions) { GameObject Piece = GameObject.CreatePrimitive(PrimitiveType.Cube); Piece.AddComponent <Rigidbody>(); Rigidbody Rigid = Piece.transform.GetComponent <Rigidbody>(); Piece.transform.localScale = PieceSize; Piece.transform.rotation = Quaternion.identity; if (this.GetComponent <Rigidbody>() != null) { Rigid.mass = this.GetComponent <Rigidbody>().mass / LayerPositions.Count; } else { Rigid.mass = 1000 / LayerPositions.Count; } Rigid.collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic; Rigid.useGravity = true; Timeline t = Piece.AddComponent <Timeline>(); t.mode = TimelineMode.Global; t.globalClockKey = "Root"; Piece.transform.SetParent(partStorage); Piece.transform.position = this.transform.position + position; Piece.transform.name = "Piece"; Piece.GetComponent <Renderer>().sharedMaterial = this.GetComponent <Renderer>().sharedMaterial; Piece.GetComponent <Renderer>().sharedMaterial.color = this.GetComponent <Renderer>().sharedMaterial.color; Rigid.AddExplosionForce(Rigid.mass * 10f, point, 2f, 0.001f, ForceMode.Force); //Rigid.AddForce(-point * (Rigid.mass * 10f), ForceMode.Impulse); } }
private void Update() { if (!arrived) { flightTimer += Time.deltaTime; // Move the Arrow along the Parabola transform.position = MathParabola.Parabola(startPoint, target, (targetDistance / 5f) * hightMultiplier, flightTimer * speedToDistance); // The direction the Arrow is currently flying Vector3 direction = transform.position - lastPosition; // Collision detection with raycast RaycastHit hit = new RaycastHit(); if (Physics.Raycast(new Ray(lastPosition, direction), out hit, direction.magnitude)) { // Only collide with objects that are not tagged with "Projectile" and not the owner // Here you might want to add more things the Arrow should ignore if (hit.collider.tag != "Projectile" && hit.collider != ownerCollider && hit.collider.tag != "collectable") { Arrive(hit); GameObject hitPrefab = Instantiate(hitEffect, hit.point, Quaternion.identity); float destroyTime = isSpecialAttack ? 4f : 2.5f; Destroy(hitPrefab, destroyTime); Collider[] colliders = Physics.OverlapSphere(transform.position, effectRadius); foreach (Collider nearByObject in colliders) { // add force Rigidbody rb = nearByObject.transform.root.GetComponent <Rigidbody>(); if (rb != null) { float forceToUse = isSpecialAttack ? effectForceSkill02 : effectForceNormal; rb.AddExplosionForce(forceToUse, transform.position, effectRadius); EnemyHealth health = rb.GetComponent <EnemyHealth>(); if (health != null) { if (health.health <= 0) { return; } int damageToUse = isSpecialAttack ? 20 : 5; health.DamageEnemy(damageToUse); } } } if (arrowEffects.Length > 0) { foreach (GameObject effect in arrowEffects) { Destroy(effect); } } //Debug.Log("hit collider tag: " + hit.collider.transform); EnemyHealth enemyHealth = hit.collider.transform.root.GetComponent <EnemyHealth>(); if (enemyHealth != null) { //we hitted the enemy somewhere if (hit.collider.tag == "torso") { arrowDamage = 40; //deal 40 damage enemyHealth.DamageEnemy(arrowDamage); } else if (hit.collider.tag == "head") { arrowDamage = 80; //deal 80 damage enemyHealth.DamageEnemy(arrowDamage); } else if (hit.collider.tag == "arms") { arrowDamage = 20; //deal 20 damage enemyHealth.DamageEnemy(arrowDamage); } } //if(hit.collider.transform.root.GetComponent<Rigidbody>() != null) //{ // if (isSpecialAttack) // { // hit.collider.transform.root.GetComponent<Rigidbody>().AddExplosionForce(30f, hit.point, 6f, 3f, ForceMode.Impulse); // } // else // { // hit.collider.transform.root.GetComponent<Rigidbody>().AddExplosionForce(4f, hit.point, 2f, 1.5f, ForceMode.Impulse); // } //} return; } } // Rotate the arrow transform.rotation = Quaternion.LookRotation(direction); // Update the lastPosition lastPosition = transform.position; } }
//If the projectile collides with anything void OnCollisionEnter(Collision collision) { //********** USED IN THE DEMO SCENES ********** //If the projectile hit the tag "Target", and if "isHit" is false if (collision.gameObject.tag == "Target" && collision.gameObject.GetComponent <TargetScript>().isHit == false) { //Spawn explosion prefab on surface Instantiate(explosionMetalPrefab, collision.contacts[0].point, Quaternion.LookRotation(collision.contacts[0].normal)); //Animate the target collision.gameObject.transform.gameObject.GetComponent <Animation> ().Play("target_down"); //Toggle the isHit bool on the target object collision.gameObject.transform.gameObject.GetComponent <TargetScript>().isHit = true; } //If the projectile collides with metal tag or metal impact static tag if (collision.gameObject.tag == metalImpactTag || collision.gameObject.tag == metalImpactStaticTag) { Instantiate(explosionMetalPrefab, collision.contacts[0].point, Quaternion.LookRotation(collision.contacts[0].normal)); } //If the projectile collides with concrete tag or concrete impact static tag if (collision.gameObject.tag == concreteImpactTag || collision.gameObject.tag == concreteImpactStaticTag) { Instantiate(explosionConcretePrefab, collision.contacts[0].point, Quaternion.LookRotation(collision.contacts[0].normal)); } //If the projectile collides with wood tag or wood impact static tag if (collision.gameObject.tag == woodImpactTag || collision.gameObject.tag == woodImpactStaticTag) { Instantiate(explosionWoodPrefab, collision.contacts[0].point, Quaternion.LookRotation(collision.contacts[0].normal)); } //If the projectile collides with dirt tag or dirt impact static tag if (collision.gameObject.tag == dirtImpactTag || collision.gameObject.tag == dirtImpactStaticTag) { Instantiate(explosionDirtPrefab, collision.contacts[0].point, Quaternion.LookRotation(collision.contacts[0].normal)); } //Explosion force Vector3 explosionPos = transform.position; Collider[] colliders = Physics.OverlapSphere(explosionPos, radius); foreach (Collider hit in colliders) { Rigidbody rb = hit.GetComponent <Rigidbody> (); //Add force to nearby rigidbodies if (rb != null) { rb.AddExplosionForce(power, explosionPos, radius, 3.0F); } //********** USED IN THE DEMO SCENES ********** //If the explosion hit the tags "Target", and "isHit" is false if (hit.GetComponent <Collider>().tag == "Target" && hit.GetComponent <TargetScript>().isHit == false) { //Animate the target hit.gameObject.GetComponent <Animation> ().Play("target_down"); //Toggle the isHit bool on the target object hit.gameObject.GetComponent <TargetScript>().isHit = true; } //If the projectile explosion hits barrels with the tag "ExplosiveBarrel" if (hit.transform.tag == "ExplosiveBarrel") { //Toggle the explode bool on the explosive barrel object hit.transform.gameObject.GetComponent <ExplosiveBarrelScript>().explode = true; } } //Destroy the projectile on collision if (!isArrow) { Destroy(gameObject); } //If arrow collides, freeze the position if (isArrow == true) { GetComponent <Rigidbody> ().isKinematic = true; } }
public IEnumerator SplitMesh(bool destroy, Vector3 explosionPoint, bool multiColored = true) { if (GetComponent <MeshFilter>() == null || GetComponent <SkinnedMeshRenderer>() == null) { yield return(null); } if (GetComponent <Collider>()) { GetComponent <Collider>().enabled = false; } Mesh M = new Mesh(); if (GetComponent <MeshFilter>()) { M = GetComponent <MeshFilter>().mesh; } else if (GetComponent <SkinnedMeshRenderer>()) { M = GetComponent <SkinnedMeshRenderer>().sharedMesh; } Material[] materials = new Material[0]; if (GetComponent <MeshRenderer>()) { materials = GetComponent <MeshRenderer>().materials; } else if (GetComponent <SkinnedMeshRenderer>()) { materials = GetComponent <SkinnedMeshRenderer>().materials; } Vector3[] verts = M.vertices; Vector3[] normals = M.normals; Vector2[] uvs = M.uv; for (int submesh = 0; submesh < M.subMeshCount; submesh++) { int[] indices = M.GetTriangles(submesh); for (int i = 0; i < indices.Length; i += 3) { Vector3[] newVerts = new Vector3[3]; Vector3[] newNormals = new Vector3[3]; Vector2[] newUvs = new Vector2[3]; for (int n = 0; n < 3; n++) { int index = indices[i + n]; newVerts[n] = verts[index]; newUvs[n] = uvs[index]; newNormals[n] = normals[index]; } Mesh mesh = new Mesh(); mesh.vertices = newVerts; mesh.normals = newNormals; mesh.uv = newUvs; mesh.triangles = new int[] { 0, 1, 2, 2, 1, 0 }; GameObject GO = new GameObject("Triangle " + (i / 3)); GO.layer = LayerMask.NameToLayer("Default"); GO.transform.position = transform.position; GO.transform.rotation = transform.rotation; GO.transform.localScale = transform.localScale; MeshRenderer mr = GO.AddComponent <MeshRenderer> (); mr.material = materials[submesh]; GO.AddComponent <MeshFilter> ().mesh = mesh; Rigidbody rb = GO.AddComponent <Rigidbody> (); rb.AddExplosionForce(Random.Range(explosionForceMin, explosionForceMax), explosionPoint, explosionRadius); rb.useGravity = false; rb.angularVelocity = Random.insideUnitSphere * Mathf.PI; FadeOut fo = GO.AddComponent <FadeOut> (); fo.multiColored = multiColored; fo.alphaFadeRate = Random.Range(fadeMin, fadeMax); } } if (destroy == true) { Destroy(gameObject); } }
// Update is called once per frame void Update() { Debug.DrawRay(_lastRayCast.origin, _lastRayCast.direction * _raycastDistance, Color.red); // Select an object based on mouse click. // button 0 is the left mouse button. if (Input.GetMouseButtonDown(0) == true) { // Create a ray that represents the 3D equivalent of our 2D position in the window frame. Ray clickRay = _currentCamera.ScreenPointToRay(Input.mousePosition); _lastRayCast = clickRay; // Play the selected sound effect. _currentSource.Play(); // This stores what we have hit with our raycast. RaycastHit hit; // Cast the click ray into the world and see what is hit. bool didHit = Physics.Raycast(clickRay, out hit); if (didHit) { Debug.Log("Hey! We hit something!"); // Grab the GameObject we hit, and store it for later. GameObject objectWeHit = hit.transform.gameObject; // Check to see if the object we've hit has an AudioSource.. AudioSource objectWeHitAudio = objectWeHit.GetComponent <AudioSource>(); if (objectWeHitAudio != null) { // If so, play it! objectWeHitAudio.Play(); } // Store the distance of the last raycast. _raycastDistance = hit.distance; Collider[] allObjectsWithinSphere = Physics.OverlapSphere(hit.point, 1.8f); foreach (Collider collider in allObjectsWithinSphere) { Rigidbody colliderRigidbody = collider.GetComponent <Rigidbody>(); // Apply a force where the ray hit the object. if (colliderRigidbody != null) { // If the object isn't using gravity, tell it to. colliderRigidbody.useGravity = true; // Spawn an explosion where the ray hit the object. colliderRigidbody.AddExplosionForce(5000.0f, hit.point, 10.25f); } } // Apply a force where the ray hit the object. /*if(hit.rigidbody != null) { * // If the object isn't using gravity, tell it to. * hit.rigidbody.useGravity = true; * * // Spawn an explosion where the ray hit the object. * hit.rigidbody.AddExplosionForce(5000.0f, hit.point, 10.25f); * }*/ if (materialToChangeTo != null) { // Grabs the MeshRenderer from the objectWeHit so that we can change its material. MeshRenderer renderer = objectWeHit.GetComponent <MeshRenderer>(); // Set the renderer to use the material we want to use. renderer.material = materialToChangeTo; } } } }
void PlayerTwo() { player.drag = 0.1f; CamTrackBlue(); play2Loc = transform; //raycast om te checken of je op de grond staat RaycastHit hit; if (Physics.Raycast(transform.position, -Vector3.up, out hit, 1000f, LayerMask.GetMask("floors"))) { } //SPRINGEN //cooldowns op jump zodat je niet meerdere frames achter elkaar kan springen als je afzet van de grond if (hit.distance >= 1.05f) { jumpLoop = 7; } jumpLoop = (jumpLoop - 1); if (jumpLoop < 0) { jumpLoop = 0; } //double jump charge krijg je pas als je een meter van de grond af bent //zodat je niet direct kan springen na je eerste sprong if (jumpCooldown > 0.3f) { doubleJumpAble = true; } if (jumpCooldown < 0.3f) { doubleJumpAble = false; } //slaan cooldown punchCooldown = (punchCooldown - 1 * Time.deltaTime); if (punchCooldown <= 0) { punchCooldown = 0; } if (punchCooldown == 0) { ableToPunch = true; } if (punchCooldown > 0) { ableToPunch = false; } //als cooldown van slaan nog bezig is if (ableToPunch == false) { hitColliderRed.enabled = false; hitColliderBlue.enabled = false; meshy.enabled = false; meshy2.enabled = false; } //naar links kijken if (Input.GetKey("left")) { if (facingDirection.transform.rotation.eulerAngles.y >= 180) { facingDirection.Rotate(0, 180, 0, Space.Self); charPlane.transform.localScale = new Vector3(1, 1, 1); } } //naar rechts kijken if (Input.GetKey("right")) { if (facingDirection.transform.rotation.eulerAngles.y <= 180) { facingDirection.Rotate(0, 180, 0, Space.Self); charPlane.transform.localScale = new Vector3(-1, 1, 1); } } //LOPEN //checkt of je op de grond staat if (hit.distance < 1.01) { //frictie zodat je niet op ijs loopt collie.material.dynamicFriction = 7; collie.material.staticFriction = 0.1f; //Doublejump cooldown stopt als je op grond loopt //je krijgt je jump charge terug die je hebt gebruikt in de vorige jump jumpCooldown = 0; doubleJumpCharge = true; //lopen if (Input.GetKey("left")) { player.AddForce(-moveSpeed * Time.deltaTime * statMagnitude, 0, 0); } if (Input.GetKey("right")) { player.AddForce(moveSpeed * Time.deltaTime * statMagnitude, 0, 0); } //springen if (Input.GetKey("up")) { if (jumpLoop == 0) { player.AddForce(player.velocity.x * 7, jumpHeight * 10 * statMagnitude, 0); jumpLoop = 5; } } //maximale snelheid werkt alleen op de grond omdat je verticale snelheid niet moet worden gelimiteerd tijdens springen float tempY = player.velocity.y; //checkt je relatieve snelheid en limiteert deze zodat je niet oneindig accelereert if (player.velocity.magnitude > maxSpeed * statMagnitude) { player.velocity = player.velocity.normalized * maxSpeed * statMagnitude; player.velocity = new Vector3(player.velocity.x, tempY, player.velocity.z); } } //als je niet op de grond staat...dan zal je wel in de lucht gesprongen zijn? else { //frictie uit als je niet op de vloer staat zodat je nergens aan blijft kleven collie.material.dynamicFriction = 0; collie.material.staticFriction = 0; //extra force naar beneden als extra zwaartekracht player.AddForce(0, -1400 * Time.deltaTime, 0); //DOUBLE JUMP jumpCooldown = (jumpCooldown + 1 * Time.deltaTime); if (Input.GetKey("up")) { if (doubleJumpCharge == true && doubleJumpAble == true && isRunner == true) { player.AddForce(player.velocity.x * 0.5f, jumpHeight * 10 * statMagnitude, 0); doubleJumpCharge = false; } } //beweging in de lucht is zwakker dan gewone beweging zodat de speler nog een beetje bij kan sturen tijdens een sprong if (Input.GetKey("left")) { player.AddForce((-moveSpeed * Time.deltaTime * 0.07f), 0, 0); } if (Input.GetKey("right")) { player.AddForce((moveSpeed * Time.deltaTime * 0.07f), 0, 0); } } //als cooldown van slaan voorbij is if (ableToPunch == true) { if (Input.GetKey("down")) { //cooldown van slaan in seconden punchCooldown = 0.5f; //alles wat er bij slaan hoort if (player2 == true) { hitColliderBlue.enabled = true; meshy2.enabled = true; //knockback mechanic Collider[] colliders = Physics.OverlapSphere(hitColliderBlue.transform.position, 1f); foreach (Collider contact in colliders) { Rigidbody rb = contact.GetComponent <Rigidbody>(); if (rb != null) { if (rb != player) { rb.AddExplosionForce(knockbackForce, forceCenter.position, 0, 2); } } } } } } }
public void SwitchGameplay(GameState state) { if (state == gameState) { return; } gameState = state; switch (state) { case GameState.MENU: player.enabled = false; player.rigid.constraints = RigidbodyConstraints.FreezeAll; playerCanvas.SetActive(false); gameplayCamera.SetActive(false); menuCanvas.SetActive(true); menuCamera.SetActive(true); lostCanvas.SetActive(false); break; case GameState.PLAY: player.rigid.constraints = RigidbodyConstraints.None; player.rigid.constraints = RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ; menuCanvas.SetActive(false); menuCamera.SetActive(false); player.enabled = true; playerCanvas.SetActive(true); gameplayCamera.SetActive(true); lostCanvas.SetActive(false); break; case GameState.WON: player.enabled = false; playerCanvas.SetActive(false); float delay = 0; StartCoroutine(ActivateWinCanvas(true, delay)); StartCoroutine(ResetGamePlay(delay + wonCanvas.GetComponentInChildren <ImageLerp>().duration)); break; case GameState.LOST: player.enabled = false; player.meshRend.enabled = false; player.currentSpeed = 0; player.rigid.velocity = Vector3.zero; player.metalbar.SetActive(false); GameObject explPlayer = Instantiate(explosionPlayer); explPlayer.transform.position = player.transform.position; Rigidbody rigid = explPlayer.GetComponentInChildren <Rigidbody>(); rigid.transform.DetachChildren(); rigid.AddExplosionForce(14f, explosionPlayer.transform.position - Vector3.forward * 3f, 3f); playerCanvas.SetActive(false); delay = 3; explosionAudio.Play(); StartCoroutine(ActivateLostCanvas(true, delay)); StartCoroutine(ResetGamePlay(delay + lostCanvas.GetComponentInChildren <ImageLerp>().duration)); break; default: break; } }
private void OnTriggerEnter(Collider other) { Collider[] colliders = Physics.OverlapSphere(transform.position, explosionRadius, tankMask); // Go through all the colliders... for (int i = 0; i < colliders.Length; i++) { // ... and find their rigidbody. Rigidbody targetRigidbody = colliders[i].GetComponent <Rigidbody>(); // If they don't have a rigidbody, go on to the next collider. if (!targetRigidbody) { continue; } // Add an explosion force. targetRigidbody.AddExplosionForce(explosionForce, transform.position, explosionRadius); // Find the TankHealth script associated with the rigidbody. if (targetRigidbody.GetComponent <TankController>()) { TankController targetHealth = targetRigidbody.GetComponent <TankController>(); // Calculate the amount of damage the target should take based on it's distance from the shell. float damage = CalculateDamage(targetRigidbody.position); // Deal this damage to the tank. targetHealth.HandleTakeDamage(damage); } else if (targetRigidbody.GetComponent <AITankController>()) { AITankController targetAI = targetRigidbody.GetComponent <AITankController>(); // Calculate the amount of damage the target should take based on it's distance from the shell. float damage = CalculateDamage(targetRigidbody.position); // Deal this damage to the tank. targetAI.HandleTakeDamage(damage); } else { // If there is no TankHealth script attached to the gameobject, go on to the next collider. continue; } } if (explosionParticles) { // Unparent the particles from the shell. explosionParticles.transform.parent = null; // Play the particle system. explosionParticles.Play(); } if (explosionAudio) { // Play the explosion sound effect. explosionAudio.Play(); } if (explosionParticles) { // Once the particles have finished, destroy the gameobject they are on. ParticleSystem.MainModule mainModule = explosionParticles.main; Destroy(explosionParticles.gameObject, mainModule.duration); } // Destroy the shell. Destroy(gameObject); }
public void Explode() { Vector3 explosionPos = transform.position; Collider[] colliders = Physics.OverlapSphere(explosionPos, radius); //Debug.Log("EXPLODE0: " + explosionPos + "," + radius + ": " + colliders.Length); foreach (Collider hit in colliders) { Rigidbody rb = hit.GetComponentInChildren <Rigidbody>(); if (rb == null) { rb = hit.GetComponentInParent <Rigidbody>(); } var dist = Vector3.Distance(hit.ClosestPoint(transform.position), transform.position); var damage = power * 0.1f / dist; // Debug.Log("EXPLODE: " + rb.name + "," + power); if (rb != null) { rb.AddExplosionForce(power, explosionPos, radius, 0F); var health = hit.GetComponentInChildren <Health>(); if (health != null) { health.TakeDamage(damage); } } var block = hit.GetComponent <Block>(); if (block != null) { block.ExplodeOn(damage); } var weakPoint = hit.GetComponent <WeakPoint>(); if (weakPoint != null) { weakPoint.Trigger(); } // Debug.Log("HIT: " + hit.gameObject.name + ", "+ (weakPoint != null)); } if (particleSystem != null) { particleSystem.gameObject.SetActive(true); particleSystem.Play(); Destroy(gameObject, particleSystem.main.duration); var body = gameObject.GetComponent <Rigidbody>(); if (body != null) { body.isKinematic = true; } if (renderer == null) { renderer = gameObject.GetComponentInChildren <Renderer>(); } if (renderer != null) { renderer.enabled = false; } } else { Destroy(gameObject, 0); } if (audio != null) { audio.Play(); } }
void CmdHit() { rb.AddExplosionForce(force, transform.position, 5, 0f, ForceMode.Impulse); }
private void OnTriggerEnter(Collider other) { // Find all the tanks in an area around the shell and damage them. // Collect all the colliders in a sphere from the shell's current position to a radius of the explosion radius. Collider[] colliders = Physics.OverlapSphere(transform.position, m_ExplosionRadius, m_TankMask); Collider[] remotecolliders = Physics.OverlapSphere(transform.position, m_ExplosionRadius, m_RemoteTankMask); // Go through all the colliders... for (int i = 0; i < colliders.Length; i++) { // ... and find their rigidbody. Rigidbody targetRigidbody = colliders[i].GetComponent <Rigidbody>(); // If they don't have a rigidbody, go on to the next collider. if (!targetRigidbody) { continue; } // Add an explosion force. targetRigidbody.AddExplosionForce(m_ExplosionForce, transform.position, m_ExplosionRadius); // Find the TankHealth script associated with the rigidbody. TankHealth targetHealth = targetRigidbody.GetComponent <TankHealth>(); // If there is no TankHealth script attached to the gameobject, go on to the next collider. if (!targetHealth) { continue; } // Calculate the amount of damage the target should take based on it's distance from the shell. float damage = CalculateDamage(targetRigidbody.position); // Deal this damage to the tank. //gets playerID and appends damage to them if (colliders[i].GetComponent <Collider>().tag == PLAYER_TAG) { if (!isServer) { //remotecolliders[i].GetComponent<NetworkIdentity>().AssignClientAuthority(this.GetComponent<NetworkIdentity>().connectionToClient); targetHealth.CmdTakeDamage(colliders[i].GetComponent <PlayerSetup>().NetID, damage); } //remotecolliders[i].gameObject.GetComponent<NetworkIdentity>().RemoveClientAuthority(this.GetComponent<NetworkIdentity>().connectionToClient); else { targetHealth.RpcTakeDamage(colliders[i].GetComponent <PlayerSetup>().NetID, damage); } } else { targetHealth.TakeDamage(damage); } } for (int i = 0; i < remotecolliders.Length; i++) { // ... and find their rigidbody. Rigidbody targetRigidbody = remotecolliders[i].GetComponent <Rigidbody>(); // If they don't have a rigidbody, go on to the next collider. if (!targetRigidbody) { continue; } // Add an explosion force. targetRigidbody.AddExplosionForce(m_ExplosionForce, transform.position, m_ExplosionRadius); // Find the TankHealth script associated with the rigidbody. TankHealth targetHealth = targetRigidbody.GetComponent <TankHealth>(); //TankHealth targetHealth; // If there is no TankHealth script attached to the gameobject, go on to the next collider. if (!targetHealth) { continue; } // Calculate the amount of damage the target should take based on it's distance from the shell. float damage = CalculateDamage(targetRigidbody.position); // Deal this damage to the tank. //gets playerID and appends damage to them if (remotecolliders[i].GetComponent <Collider>().tag == PLAYER_TAG) { if (!isServer) { //remotecolliders[i].GetComponent<NetworkIdentity>().AssignClientAuthority(this.GetComponent<NetworkIdentity>().connectionToClient); targetHealth.CmdTakeDamage(remotecolliders[i].GetComponent <PlayerSetup>().NetID, damage); } //remotecolliders[i].gameObject.GetComponent<NetworkIdentity>().RemoveClientAuthority(this.GetComponent<NetworkIdentity>().connectionToClient); else { targetHealth.RpcTakeDamage(remotecolliders[i].GetComponent <PlayerSetup>().NetID, damage); } } else { targetHealth.TakeDamage(damage); } } if (GameManager.IsOnline) { if (!isServer) { // Unparent the particles from the shell. m_ExplosionParticles.transform.parent = null; // Play the particle system. m_ExplosionParticles.Play(); // Play the explosion sound effect. m_ExplosionAudio.Play(); // Once the particles have finished, destroy the gameobject they are on. #pragma warning disable CS0618 // Type or member is obsolete Destroy(m_ExplosionParticles.gameObject, m_ExplosionParticles.duration); #pragma warning restore CS0618 // Type or member is obsolete // Destroy the shell. Destroy(gameObject); } else { RpcShellstuff(); } } else { // Unparent the particles from the shell. m_ExplosionParticles.transform.parent = null; // Play the particle system. m_ExplosionParticles.Play(); // Play the explosion sound effect. m_ExplosionAudio.Play(); // Once the particles have finished, destroy the gameobject they are on. #pragma warning disable CS0618 // Type or member is obsolete Destroy(m_ExplosionParticles.gameObject, m_ExplosionParticles.duration); #pragma warning restore CS0618 // Type or member is obsolete // Destroy the shell. Destroy(gameObject); } }
void explode() { rb.AddExplosionForce(1, explosionPos.position, 10); }
/// <summary> /// The object has taken been damaged. /// </summary> /// <param name="amount">The amount of damage taken.</param> /// <param name="position">The position of the damage.</param> /// <param name="direction">The direction that the object took damage from.</param> /// <param name="forceMagnitude">The magnitude of the force that is applied to the object.</param> /// <param name="frames">The number of frames to add the force to.</param> /// <param name="radius">The radius of the explosive damage. If 0 then a non-explosive force will be used.</param> /// <param name="attacker">The GameObject that did the damage.</param> /// <param name="attackerObject">The object that did the damage.</param> /// <param name="hitCollider">The Collider that was hit.</param> public virtual void OnDamage(float amount, Vector3 position, Vector3 direction, float forceMagnitude, int frames, float radius, GameObject attacker, object attackerObject, Collider hitCollider) { #if ULTIMATE_CHARACTER_CONTROLLER_MULTIPLAYER if (m_NetworkInfo != null && m_NetworkInfo.IsLocalPlayer()) { m_NetworkHealthMonitor.OnDamage(amount, position, direction, forceMagnitude, frames, radius, attacker, hitCollider); } #endif // Add a multiplier if a particular collider was hit. Do not apply a multiplier if the damage is applied through a radius because multiple // collider are hit. if (radius == 0 && direction != Vector3.zero && hitCollider != null) { Hitbox hitbox; if (m_ColliderHitboxMap != null && m_ColliderHitboxMap.Count > 0) { if (m_ColliderHitboxMap.TryGetValue(hitCollider, out hitbox)) { amount *= hitbox.DamageMultiplier; } else { // The main collider may be overlapping child hitbox colliders. Perform one more raycast to ensure a hitbox collider shouldn't be hit. float distance = 0.2f; if (hitCollider is CapsuleCollider) { distance = (hitCollider as CapsuleCollider).radius; } else if (hitCollider is SphereCollider) { distance = (hitCollider as SphereCollider).radius; } // The hitbox collider may be underneath the base collider. Fire a raycast to detemine if there are any colliders underneath the hit collider // that should apply a multiplier. var hitCount = Physics.RaycastNonAlloc(position, direction, m_RaycastHits, distance, ~(1 << LayerManager.IgnoreRaycast | 1 << LayerManager.Overlay | 1 << LayerManager.VisualEffect), QueryTriggerInteraction.Ignore); for (int i = 0; i < hitCount; ++i) { var closestRaycastHit = QuickSelect.SmallestK(m_RaycastHits, hitCount, i, m_RaycastHitComparer); if (closestRaycastHit.collider == hitCollider) { continue; } // A new collider has been found - stop iterating if the hitbox map exists and use the hitbox multiplier. if (m_ColliderHitboxMap.TryGetValue(closestRaycastHit.collider, out hitbox)) { amount *= hitbox.DamageMultiplier; hitCollider = hitbox.Collider; break; } } } } } // Apply the damage to the shield first because the shield can regenrate. if (m_ShieldAttribute != null && m_ShieldAttribute.Value > m_ShieldAttribute.MinValue) { var shieldAmount = Mathf.Min(amount, m_ShieldAttribute.Value - m_ShieldAttribute.MinValue); amount -= shieldAmount; m_ShieldAttribute.Value -= shieldAmount; } // Decrement the health by remaining amount after the shield has taken damage. if (m_HealthAttribute != null && m_HealthAttribute.Value > m_HealthAttribute.MinValue) { m_HealthAttribute.Value -= Mathf.Min(amount, m_HealthAttribute.Value - m_HealthAttribute.MinValue); } var force = direction * forceMagnitude; if (forceMagnitude > 0) { // Apply a force to the object. if (m_ForceObject != null) { m_ForceObject.AddForce(force, frames); } else { // Apply a force to the rigidbody if the object isn't a character. if (m_Rigidbody != null && !m_Rigidbody.isKinematic) { if (radius == 0) { m_Rigidbody.AddForceAtPosition(force * MathUtility.RigidbodyForceMultiplier, position); } else { m_Rigidbody.AddExplosionForce(force.magnitude * MathUtility.RigidbodyForceMultiplier, position, radius); } } } } // Let other interested objects know that the object took damage. EventHandler.ExecuteEvent <float, Vector3, Vector3, GameObject, Collider>(m_GameObject, "OnHealthDamage", amount, position, force, attacker, hitCollider); if (m_OnDamageEvent != null) { m_OnDamageEvent.Invoke(amount, position, force, attacker); } // The object is dead when there is no more health or shield. if (!IsAlive()) { #if ULTIMATE_CHARACTER_CONTROLLER_MULTIPLAYER if (m_NetworkInfo == null || m_NetworkInfo.IsLocalPlayer()) { #endif Die(position, force, attacker); #if ULTIMATE_CHARACTER_CONTROLLER_MULTIPLAYER } #endif } else { // Play any take damage audio if the object did not die. If the object died then the death audio will play. m_TakeDamageAudioClipSet.PlayAudioClip(m_GameObject); } }
// Will apply damage to any zombies within the Overlap Sphere. private void OverlapSphereDamage() { Collider[] hitColliders = Physics.OverlapSphere(transform.position, blastRadius); foreach (Collider collider in hitColliders) { Transform hitTransform = collider.transform; if (hitTransform.root.tag == "Zombie") { // If we have already iterated through a Zombie containing this collider, then skip to next. if (hitZombies.Contains(hitTransform.root)) { continue; } // Add the new zombie to the <hitZombies> so that he don't get iterated more than once. hitZombies.Add(collider.transform.root); ZombieAI targetZombie = collider.transform.root.GetComponent <ZombieAI>(); if (throwableType == ThrowableType.Molotov) { foreach (Transform child in targetZombie.transform) { // If the zombie is already on fire, there is not need to set him on fire. if (child.GetComponent <FireDamage>() != null) { continue; } } // Create a fire particle (does apply damage by itself). GameObject fireClone = Instantiate(fireParticle, collider.transform.position, Quaternion.identity) as GameObject; fireClone.name = "Flame"; fireClone.transform.SetParent(targetZombie.transform, true); fireClone.transform.localPosition = Vector3.zero; // Setup the fire particle FireDamage component. FireDamage fireDamage = fireClone.GetComponent <FireDamage>(); fireDamage.shooterID = shooterID; fireDamage.targetZombie = targetZombie; } else { // Set the grenade explosion to this one (for ExplosionForce physics) and apply damage to the zombie. targetZombie.grenadeExplosion = this; targetZombie.TakeDamage(damage, shooterID); } } else if (throwableType == ThrowableType.Grenade) { Rigidbody targetRigidbody = hitTransform.GetComponent <Rigidbody>(); if (targetRigidbody != null) { targetRigidbody.AddExplosionForce(damage * 10f, transform.position, blastRadius, 2f); } } } if (throwableType == ThrowableType.Grenade) { Destroy(gameObject); } }
private IEnumerator AttackSequence() { isAttacking = true; if (agent.enabled) { agent.isStopped = true; } yield return(new WaitForSeconds(1f)); Vector3 explosionPos = transform.position; var colliders = new Collider[32]; var size = Physics.OverlapSphereNonAlloc(explosionPos, 10, colliders, attackMask); for (var i = 0; i < size; i++) { Collider hit = colliders[i]; Rigidbody rb = hit.attachedRigidbody; BaseEntity baseEntity = hit.GetComponent <BaseEntity>(); if (baseEntity != null) { if (baseEntity == self || baseEntity.faction == self.faction) { continue; } } if (rb != null && baseEntity == null) { rb.AddExplosionForce(3000, explosionPos, 10, 1.0F); } var damageable = hit.GetComponent <Damageable>(); if (damageable != null) { damageable.TakeDamage(unitData.damage); } var playerManager = hit.GetComponent <PlayerManager>(); if (playerManager != null) { PlayerEvents.Current.Shake(); } attackTimer = 0; } yield return(new WaitForSeconds(1)); if (agent.enabled) { agent.isStopped = false; } isAttacking = false; }
IEnumerator Attack() { Jump(); yield return(new WaitForSeconds(1f)); Vector3 explosionPos = transform.position; gorbonRB.isKinematic = true; gorbonRB.velocity = Vector3.zero; transform.position = explosionPos; Collider[] colliders = Physics.OverlapSphere(explosionPos, attackRadius); foreach (Collider hit in colliders) { Rigidbody rb = hit.GetComponent <Rigidbody>(); if (rb != null) { rb.AddExplosionForce(attackForce, explosionPos, attackRadius); RaycastHit attackHit; if (rb.CompareTag("Player") && Physics.Linecast(transform.position, target.position, out attackHit, visibilityMask)) { if (attackHit.transform.CompareTag("Player")) { float realDamage = attackDamage - 3f * (target.position - transform.position).magnitude; realDamage = Mathf.Clamp(realDamage, 0f, attackDamage); rb.GetComponent <PlayerControl>().DamagePlayer(realDamage); Debug.LogWarning(attackDamage + " | " + (3f * (target.position - transform.position).magnitude) + " | " + realDamage); } } if (rb.CompareTag("PlayerShip")) { rb.GetComponent <ShipCollision>().BreakShip(); if (target == rb.transform) { FindObjectOfType <ShipController>().Exit(); } } } } MeshRenderer[] meshes = GetComponentsInChildren <MeshRenderer>(); foreach (MeshRenderer mesh in meshes) { mesh.enabled = false; } explosion.Play(); yield return(new WaitForSeconds(1f)); if (overlord != null) { overlord.RemoveGorbon(this); overlord = null; } Destroy(gameObject); }
void ApplyForce(Transform laser) { rb.AddExplosionForce(kickback, laser.position, 1000); }