hii,,everyone...
my problem is related with physics.overlapSphere....i jus dont underStand why i cant access to any specific collider..
i have an emptygame object with rigidbody and mesh collider (layer=player) and 3 child object (layer=player)are attached to emptygameobject....
other side i have a shell with rigid body and capsule collider and with a tick on is trigger option...in script i used onTriggerEnter method and overlapSphere ...so what i was expecting ...whenever shell enter into other collider...all the object with layer=player and within a specific radius had to be part of array which i have created earlier.....but the array is empty.. sorry for my poor english.
↧
overlapsphere doesnot recognize child's collider
↧
OverlapSphere Problem.
Namaste Developers. _/\
My game has a theme of 'Survival Shooter'.
Every Enemy has 2 different colliders
(Capsule Collider & Sphere Collider).
Now, when I use Physics.OverlapSphere for the explosion or making a Tornado Effect, the enemy got killed but it is counting the Enemy DeathCount twice (1 Enemy Killed = 2 Enemy Death Count & Score Value = 20). It is so because I have 2 different colliders on enemy gameObject. When I turn off Sphere Collider then it is counting the death count and Scores normally i.e., 1 enemy killed = 1 enemy deathcount and Score value = 10. My Sphere Collider is a Triggered Collider and my Tornado also has a Sphere collider which is a Triggered too. My Tornado has a script. Below is my code.
private void OnTriggerStay(Collider other)
{
colliders = Physics.OverlapSphere(transform.position, Radius, CollidingLayerMask, QueryTriggerInteraction.Ignore);
foreach (Collider Hit in colliders)
{
Rigidbody RB = Hit.GetComponent();
if (RB != null)
{
RB.AddExplosionForce(Power, transform.position, Radius, 5.0f, ForceMode.Acceleration);
}
if ((RB != null) && (Hit.gameObject.tag == "Enemies" || Hit.gameObject.tag == "Birds"
|| Hit.gameObject.tag == "DYZ" || Hit.gameObject.tag == "Ghost" || Hit.gameObject.tag == "RBOSS"
|| Hit.gameObject.tag == "YBOSS" || Hit.gameObject.tag == "SBOSS"))
{
Hit.GetComponent().enabled = false;
RB.constraints &= ~RigidbodyConstraints.FreezePositionY;
Instantiate(TornadoDeathFx, onePosition.position, onePosition.rotation);
Instantiate(CoinPrefab, onePosition.position, CoinPrefab.transform.rotation);
RB.AddExplosionForce(Power, transform.position, Radius, 5.0f, ForceMode.Impulse);
EH = Hit.GetComponent();
EH.TakeDamageFromTornado(100);
}
}
}
It's been so long I am suffering from this problem. I am frustrated and I am loosing my edge.
The edge which strikes fuel for the 'Game Development'.
Any Help will be heartily appreciated.
↧
↧
How come certain Children don't cast an Overlapsphere?
Hi there,
I'm making a little game for Android where the player has to connect several gears with eachother by placing new gears on empty screws. Now this is going nicely apart from one little problem.
I've got 4 kinds of gears, of which the only difference is their size, which are 3, 4, 5 or 6. When placing a new gear, that gear becomes the child of the screw it is placed on, and checks for connecting gears by casting an OverlapSphere related to their size. Now all of the gears do their job perfectly, except for the one with size 5. As soon as it becomes a child of a screw, it won't cast the OverlapSphere anymore and I get null references because the code expects it to have at least one overlap. It doesn't even see its own collider, so I know it just doesn't cast it at all.
I've been testing the OverlapSphere sizes with Gizmos.DrawWireSphere , and even that doesn't work anymore as soon as it's a child. It does work when it's a child of anything but a screw. It needs to be a child since it should check the surrounding screw's children if theyre connecting.
I have no clue if you need the script for this, since for the other gears it works perfectly, but I'll post it anyway:
using UnityEngine;
using System.Collections;
public class H_Gear : MonoBehaviour
{
public Vector3 rot;
public float size;
public float speed;
public bool connectionset;
public float offset;
public Y_ButtonManager BM;
public Transform[] connector = new Transform[2];
GameObject[] connectorC = new GameObject[2];
Collider[] hitColliders;
public bool Gstatic;
bool speedset;
bool gotSpeedSource;
bool gamewonb;
float gamewon;
// Use this for initialization
void Start()
{
size = transform.lossyScale.x;
rot = transform.rotation.eulerAngles;
BM = GameObject.Find("ButtonManager").GetComponent();
}
void Update()
{
if (gamewonb)
{
gamewon += Time.deltaTime;
if (gamewon > 3)
{
Application.LoadLevel(0);
}
}
if (!transform.GetComponent())
{
//setting the overlapsphere
if (size == 6)
{
hitColliders = Physics.OverlapSphere(transform.position, 0.85f);
}
if (size == 5)
{
hitColliders = Physics.OverlapSphere(transform.position, 0.70f);
}
if (size == 4)
{
hitColliders = Physics.OverlapSphere(transform.position, 0.58f);
}
if (size == 3)
{
hitColliders = Physics.OverlapSphere(transform.position, 0.43f);
}
if (transform.name == "StartGear" || transform.name == "EndGear")
{
hitColliders = Physics.OverlapSphere(transform.position, 0.95f);
}
//check if any of the ones im overlapping are connected to the source
if (connector[0])
{
int i = 0;
while (i < hitColliders.Length)
{
if (hitColliders[i].transform.tag == "Gear")
{
if (hitColliders[i].transform.parent == connector[0] && hitColliders[i].GetComponent().connectionset)
{
connectionset = true;
if (!speedset)
{
speed -= hitColliders[i].GetComponent().speed * (hitColliders[i].GetComponent().size / size);
speedset = true;
}
connectorC[0] = hitColliders[i].gameObject;
}
else if (connector[1] && hitColliders[i].transform.parent == connector[1] && hitColliders[i].GetComponent().connectionset)
{
connectionset = true;
if (!speedset)
{
speed -= hitColliders[i].GetComponent().speed * (hitColliders[i].GetComponent().size / size);
speedset = true;
}
connectorC[1] = hitColliders[i].gameObject;
}
}
i++;
}
}
//to check if there really is noone connecting me to the source anymore
//yes i know it does the same several times, but combining the statements leads to errors
if ((!connectorC[0] && !connectorC[1] && !transform.GetComponent() && !gotSpeedSource))
{
speed = 0;
connectionset = false;
speedset = false;
}
if (connectorC[0] && connectorC[1])
{
if (!connectorC[0].GetComponent().connectionset && !connectorC[1].GetComponent().connectionset && !gotSpeedSource)
{
speed = 0;
connectionset = false;
speedset = false;
}
}
if (!connectorC[0] && connectorC[1] && !connectorC[1].GetComponent().connectionset)
{
speed = 0;
connectionset = false;
speedset = false;
}
if(!connectorC[1] && connectorC[0] && !connectorC[0].GetComponent().connectionset)
{
speed = 0;
connectionset = false;
speedset = false;
}
}
else
{
//if im connected to the source, i should get my speed from there
speed = transform.GetComponent().speed;
}
}
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
if (size == 6)
{
Gizmos.DrawWireSphere(transform.position, 0.85f);
}
if (size == 5)
{
Gizmos.DrawWireSphere(transform.position, 0.70f);
}
if (size == 4)
{
Gizmos.DrawWireSphere(transform.position, 0.58f);
}
if (size == 3)
{
Gizmos.DrawWireSphere(transform.position, 0.43f);
}
if(transform.name == "StartGear" || transform.name == "EndGear")
{
Gizmos.DrawWireSphere(transform.position, 0.95f);
}
}
void FixedUpdate()
{
if (transform.name == "EndGear" && connectionset)
{
//gamewonb = true;
}
rot.z += speed;
transform.rotation = Quaternion.Euler(rot.x, rot.y, rot.z);
}
//to get the gears back and place them again
void OnMouseOver()
{
if (Input.GetMouseButtonDown(0))
{
if (!Gstatic)
{
Destroy(gameObject);
if (size == 3)
{
BM.maxCog1++;
}
if (size == 4)
{
BM.maxCog2++;
}
if (size == 5)
{
BM.maxCog3++;
}
if (size == 6)
{
BM.maxCog4++;
}
}
}
}
//This is for connecting gears that are connected to the source and won't ever disappear
void OnTriggerEnter(Collider other)
{
if(other.GetComponent() && !speedset && other.GetComponent().connectionset)
{
speed -= other.GetComponent().speed * (other.GetComponent().size / size);
speedset = true;
gotSpeedSource = true;
connectionset = true;
}
}
}
I hope anyone can help. If you need pictures of the scene, let me know!
↧
OverlapSphere Doesn't Return Objects Inside?
I've been experimenting with some explosion code for the past few hours and I'm trying to make an explosion that does damage to everything in a certain radius, but not through walls. I'm thinking my best bet is to use OverlapSphere to get all of the objects in range, then raycast to them to see if they're through a wall. If the raycast goes through, deal damage.
HOWEVER I have noticed that OverlapSphere is not finding things consistently, and I have no idea. why. I've tried testing things but I'm not getting anything consistent enough to debug properly. So here's my hypotheses:
1: (Least likely) OverlapSphere is biased in the positive X, and negative Y directions, and only dealing damage to things in that direction.
2: (More likely) OverlapSphere only returns colliders that intersect with the sphere itself. Thus, a collider that is completely inside of the sphere radius will not be returned. While, logically, this seems more likely, it doesn't test consistently.
I have a line of "exploding barrels" set up that, when they "TakeDamage," they instantiate an explosion that is capable of dealing damage. This functions properly - shooting a barrel makes it explode, it exploding will make other barrels explode -- inconsistently. Depending on the radius used, sometimes the barrel next to it will be skipped and the one next to that will explode, thus leading me to hypothesis 2.
Given that it is almost always the barrels on the right of the one shot that explode, and ones to the left almost NEVER explode, I have hypothesis 1.
When an explosion is instantiated, this is the code used to deal damage with the OverlapSphere:
Collider[] hitColliders = Physics.OverlapSphere (transform.position, radius);
foreach (Collider hit in hitColliders) {
if (!collidersDamaged.Contains (collider)) {
collidersDamaged.Add (collider);
hit.SendMessage ("TakeDamage", explosionDamage, SendMessageOptions.DontRequireReceiver);
}
}
Explosions are instantiated at the position of the barrel, shown here:
public void TakeDamage (int amount)
{
if (!hasBeenDestroyed) {
hasBeenDestroyed = true;
health -= amount;
if (health <= 0) {
if (explosionEffect != null)
Instantiate (explosionEffect, transform.position, transform.rotation);
GameObject explodedObject = (GameObject)Instantiate (destroyedVersion, transform.position, transform.rotation);
explodedObject.transform.position = transform.position;
Destroy (gameObject);
}
}
}
![alt text][1]
The pivot point for the barrel is in the dead center of the barrel. I have also checked the explosion position in game, and it is lining up properly with the barrel. Thus, it cannot be that the explosion is off-position.
My questions: Why is my OverlapSphere not reliable? Is there a better way to do what I'm trying to do?
[1]: /storage/temp/40830-untitled.png
↧
Why is my Physics.overlapSphere returning a length of 0?
public Vector3[] nodepoints;
public float size = 2;
/*
*Buncha other code
*/
for(int nP = 0; nP < nodePoints.Length; nP++)
{
Collider[] nearBy = Physics.OverlapSphere(nodePoints[nP], size, gameObject.layer);
print(nearBy.Length);
So basically this isn't detecting anything, I'm confused as to why the overlapsphere isn't finding anything while everything is within 2 units of that space.
The code runs through, I get ~4000 outputs of 0, but it never finds any other objects in the same layer, or any other infact, that is within radius.
↧
↧
how to access parent script from child object with overlapsphere in a multiplayer game
Hello!
I have a problem when I'm trying to access a parent script when another gameobject is colliding with the child of the first gameobject. Let me explain this in detail:
This is an online game. The first player has a script attached called DemonSpells and I'm using OverlapSphere to find all the colliders it hits. This is a part of the script:
void Spell1_Damage(Vector3 center, float radius,string originatorName)
{
Collider[] hitColliders = Physics.OverlapSphere(center, radius);
int i = 0;
while (i < hitColliders.Length)
{
if(iAmOnTheRedTeam && hitColliders[i].transform.tag == "BlueTeamTrigger"){
Debug.Log(hitColliders[i].transform.root);
hitColliders[i].transform.SendMessageUpwards("Stun");
PlayerStats plstats = spawn.redspawn.GetComponent();
HealthAndDamage HDScript = hitColliders[i].transform.GetComponent();
HDScript.spellDamage = plstats.stats[2];
HDScript.iWasJustAttacked = true;
HDScript.myAttacker = originatorName;
HDScript.hitBySpell1 = true;
}
if(iAmOnTheBlueTeam && hitColliders[i].transform.tag == "RedTeamTrigger"){
Debug.Log(hitColliders[i].transform.root);
hitColliders[i].transform.SendMessageUpwards("Stun");
PlayerStats plstats = spawn.bluespawn.GetComponent();
HealthAndDamage HDScript = hitColliders[i].transform.GetComponent();
HDScript.spellDamage = plstats.stats[2];
HDScript.iWasJustAttacked = true;
HDScript.myAttacker = originatorName;
HDScript.hitBySpell1 = true;
}
i++;
}
}
This code finds the targets and accesses the child of the opponent named Trigger, which holds a script called HealthAndDamage. The player doesn't have any box collider, only the child (Trigger). I can access the Trigger gameobject and apply damage to the opponent but i can't access the parent. I need to access the Movement script from the parent so that I can apply a stun effect. I used SendMessageUpwards and it doesn't work. I also tried to access the parent like this: PointAndClickMovement move =
hitColliders[i].transform.parent.gameobject.GetComponent();
This is the method from the PointAndClickMovement script I'm trying to get:
public void Stun()
{
Debug.Log("STUN");
previousSpeed = speed;
speed = 0;
networkView.RPC("UpdateMySpeed", RPCMode.AllBuffered, speed);
StartCoroutine(waitForStun(5));
}
IEnumerator waitForStun(float time)
{
yield return new WaitForSeconds (time);
speed = previousSpeed;
networkView.RPC("UpdateMySpeed", RPCMode.AllBuffered, speed);
}
I've tried every possible way to do this but with no luck. I also did this with a Raycast and it worked. But this kind of spell is an AOE(area of effect) and I can't do it with Raycast. Please let me know if I'm doing anything wrong! Thanks! :)
↧
OverlapSphere doesn't work
I have a script that puts 6 buildings of the same box shape in random positions depending on the earlier building position. Each vector from Moves array defines one of 8 positions around current building. Then I faced with problem of multiple buildings spawning at the same position by accident so I added the OverlapSphere condition to check if there is a building already spawned in that direction. If it's not, the procedure repeats until it finds an empty place. Here's the code:
void Start () {
Moves[0]=new Vector3(0,0,1);
Moves[1]=new Vector3(1,0,1);
Moves[2]=new Vector3(1,0,0);
Moves[3]=new Vector3(1,0,-1);
Moves[4]=new Vector3(0,0,-1);
Moves[5]=new Vector3(-1,0,-1);
Moves[6]=new Vector3(-1,0,0);
Moves[7]=new Vector3(-1,0,1);
Buildings=GameObject.FindGameObjectsWithTag("Building");
Buildings[0].transform.position=new Vector3(0,0.5f,0);
for(i=1; i<=5; i++)
{
k=Random.Range(0,8);
Move=Moves[k];
if(Physics.OverlapSphere(Buildings[i-1].transform.position+Move*Distance, 5f,7).Length==0) //Layer 7 doesn't include Buildings
{Buildings[i].transform.position=Buildings[i-1].transform.position+Move*Distance;}
else{i--;}
}
}
But it didn't solve the problem. There were a few situations during runtime tests where two buildings spawned on the same place.
Debugging shows that function OverlapSphere doesn't find any placed object and returns 0 for condition.
↧
OverlapSphere doesn't detect colliders
I have a problem that has been driving me crazy for a week already. I have 6 boxes as Buildings and I have a script that places each building randomly according to the previous building's position.
The script uses OverlapSphere method to check if the place where it places the next building is empty.
Buildings are in one layer that is included in layermask used in this script.
GameObject[] Buildings=new GameObject[6];
int i;
int k;
Vector3 Move;
Vector3[] Moves=new Vector3[8];
public float Distance=10f;
public LayerMask Mask;
void Start () {
//This is a set of possible directions of building placements (horizontal, vertical and diagonal directions)
Moves[0]=new Vector3(0,0,1);
Moves[1]=new Vector3(1,0,1);
Moves[2]=new Vector3(1,0,0);
Moves[3]=new Vector3(1,0,-1);
Moves[4]=new Vector3(0,0,-1);
Moves[5]=new Vector3(-1,0,-1);
Moves[6]=new Vector3(-1,0,0);
Moves[7]=new Vector3(-1,0,1);
Buildings=GameObject.FindGameObjectsWithTag("Building");
//Placing the first building
Buildings[0].transform.position=new Vector3(0,0.5f,0);
i=1;
while(i<=5)
{
//Choosing random direction
k=Random.Range(0,8);
Debug.Log(k);
Move=Moves[k];
//Checks if there is a building in the place for the new building
Collider[] Scan=Physics.OverlapSphere(Buildings[i-1].transform.position+Move*Distance, 5f,Mask);
if(Scan.Length==0)
{Buildings[i].transform.position=Buildings[i-1].transform.position+Move*Distance;
Debug.Log(Buildings[i]);
Debug.Log(Buildings[i-1].transform.position+Move*Distance);
i++;
}
else if(Scan.Length>0){
Debug.Log("Found taken place");
Debug.Log(Buildings[i]);}
}
}
The problem is that OverlapSphere doesn't detect boxes. I tried placing terrain from another layer and changing the layermask to that layer and it detected terrain. It just refuses to detect boxes, resulting in multple boxes being placed at the same position. All boxes have standard box colliders.
I can't find any other explanation, other than something is wrong with OverlapSphere.
↧
Detecting how much of a Sphere is overlapped
I'm currently working on a system which requires an "Overlap Sphere" cast to detect how much of the sphere is filled by an object.
As an example, I may have 3 objects within the sphere; the ground, a wall and the player.
I ignore the player with a layermask, and attempt to detect the other two. I want to know whether there is more floor or more wall within the cast as I intend to use this data later.
If there is no way of using the "Overlap Sphere" cast for this, alternative suggestions would be appreciated.
↧
↧
Overlapsphere crashing my game?
My Unity keeps freezing when I run it while using this code, Am i doing something wrong?
using UnityEngine;
using System.Collections;
public class BasicAIMovement : MonoBehaviour {
NavMeshAgent nma;
public GameObject point;
// Use this for initialization
void Start () {
nma = gameObject.GetComponent();
Search(gameObject.transform.position,20);
}
// Update is called once per frame
void Update () {
if(point != null){
nma.destination = point.transform.position;
}
}
void Search(Vector3 center,float radius){
Collider[] hitColliders = Physics.OverlapSphere(center, radius);
int i = 0;
while (i < hitColliders.Length) {
if(hitColliders[i].tag == "Point"){
print(hitColliders[i].name);
i++;
}
}
}
}
↧
Physics.OverlapSphere not detecting colliders
I've seen other posts about problems with Physics.OverlapSphere not detecting colliders, but nothing seems to get mine to work.
My first question is, which types of colliders does OverlapSPhere detect? I am using Kinematic Rigidbody trigger box colliders 2d attached to a prefab object. I read in one post that OverlapSphere does not detect triggers, so I unchecked "Is Trigger", but that made no difference. Then I read somewhere that in Unity 5.0 it will detect triggers, so I updated from 4.6 to the latest 5.0, no change. I used OnDrawGizmos to make sure the sphere was positioned correctly, and that is definitely not the problem.
Anyway, here is the relevant code, hopefully someone will spot what noobish error I have made:
I have an enemy-spawning script that spawns a group of prefabs at either end of the game screen. For a simple test to try to get this working, I have it spawning two instances of the same prefab at one end of the game screen:
public class enemySpawner : MonoBehaviour {
public GameObject brownOrc;
public GameObject redOrc;
Vector3 brownSpawn = new Vector3(5, 10, 0);
Vector3 redSpawn = new Vector3(5, 1, 0);
// Use this for initialization
void Start () {
orc_stats newOrc;
GameObject go1, go2, temp;
orcTeam brownTeam, redTeam;
int numBrown, numRed, i;
go1 = GameObject.Find("brown team");
brownTeam = (orcTeam) go1.GetComponent(typeof(orcTeam));
numBrown = brownTeam.get_numOrcs();
go2 = GameObject.Find("red team");
redTeam = (orcTeam) go2.GetComponent(typeof(orcTeam));
numRed = redTeam.get_numOrcs();
for (i = 0; i < numBrown; i++) {
temp = Instantiate(brownOrc, brownSpawn, Quaternion.identity) as GameObject;
newOrc = temp.GetComponent();
newOrc.teamName = "brown";
brownSpawn.x++;
}
for (i = 0; i < numRed; i++) {
temp = Instantiate(redOrc, redSpawn, Quaternion.identity) as GameObject;
newOrc = temp.GetComponent();
newOrc.teamName = "red";
redSpawn.x++;
}
}
}
Then I have another script that, in Update() attempts to see if there are any Orcs within a certain range:
// Update is called once per frame
void Update () {
Collider[] targs = Physics.OverlapSphere(transform.position, 5.0f);
print("xxx-" + targs.Length);
}
No matter what I do, targs.Length is always 0.
↧
use Physics.OverlapSphere to detect neighbour of same tag in list of gameObjects
Hello, i have a 10x10 grid of gameobjects stored in a list. The computer will randomly select one of these gameobjects with a raycast. I want to check if this gameobject has any neighbours with the same tag if it is being selected. By using Physics.OverlapSphere i can raycast a sphere around this gameObject and return an array of colliders. I want to remove elements in this array if it doesnt have the same tag as the original object and keep the one that has the same tag. Additionally i want to take these found colliders and assign them as gameobjects and place them in a new array to keep track on all the neighbours with their own tags. How should i go about doing this?
↧
OverlapSphere and QueryTriggerInteraction
Hi,
i my PhysicsManager i turned off "Raycast Hit Triggers". But now i want to include a few trigger colliders in a Physics.OverlapSphere. In the documentation there is this queryTriggerInteraction variable, which looks exactly like what i am looking for. But i cant find i way to use it. I always get compiler errors as if there is no such thing as a fourth variable in the OverlapSphere function.
my (working) code so far, not including trigger colliders:
Collider[] hitColliders = Physics.OverlapSphere(position, range, layerMaskSphere);
how do i use the "queryTriggerInteraction" part?
Best Regards
chef_seppel
↧
↧
reverb zones with spheres and raycasts
I'm experimenting with some audio stuff using FMOD (audio middleware). I'm looking to create some functionality similar to what reverb zones do, but adding some particular features that FMOD allows. Basically, the idea is this: a sound is emitted from a sound source, raycasts are used to find which reverb areas are hit and how far they are from the sound source, and the wet signal for each hit area is played back from the position of the reverb area. In other words, the dry and wet signals would have separate positions in the game space (this is something FMOD can do).
So on to the question. I was originally thinking of trying to cast a whole bunch of rays out from the sound source, and read some posts suggesting how one might do that (i.e. set some number of rays, have them cast out with origin points evenly spaced out on a sphere). But another idea I had was to use OverlapSphere to see what gets hit, then cast rays to those spots to get the distance. I'm estimating that in most cases only a few reverb areas will be in range of the sound, so approach 1 would likely mean creating a lot more rays than are needed. That said, I don't know which approach would be more resource intensive. Anyone have any idea? Or suggestions? Thanks.
↧
Trying to check area for game objects that collide with spawnpoints, then spawn an item where ever there is not a collision
Currently i have an area i have designated for trees to spawn, with an array of spawn points for the trees to all be spawned on when the game starts, i need to write something so that i can get an array of all the spawn points where trees are not there(due to a player destroying a tree). I have tried working with Physics.OverlapSphere but to no avail. Any help or advice would be greatly appreciated.
Regards,
Pdkkid
↧
How to get an array of transforms and move GameObject for certain duration to that transforms list
Hi again..
lets go right to the point!
so here i want to make player skill similarly more like **(Ciri's Blinking Skill = The Witcher 3 game) or (Omnislash = Juggernaut's Dota Hero Skill)**
but bit different.
so specifically the logic is:
on Getbutton ("Fire")
i want to get an array list of "enemies" gameobject around player's radius and store it (tried using overlapsphere)
then get the transforms position of those gameobjects again store it
then automatically it'll move the player position between those all array of transform.positions
either consecutively or in random orders for a set of duration and intervals.. i.e keep moving/blinking the player for as long as 10sec and giving 1sec intervals for each, before moving to next transform into another position on the array list
if the time end before the list are complete then return to starting position (inCase the list was more than 10enemies bcs its only 10sec and 1sec between next transform)
or if the list of enemies are fewer than 10 then back to array[0] on the list and repeat until the timers end
orrrr if the enemies all dead before the timer end just return immediately
**and if it possible i want to add additional random XYZ value to each transform on the list so the player doesn't move exactly to the enemies position but only behind,beside,above or below them.**
here's what code i already tried
bool isBlinking;
RigidBody playerRB;
void Update()
{
if (input.GetButton ("Fire1"))
{
Seeking();
isBlinking = true;
invoke("blinkfalse",10f);
}
}
void blinkfalse(){
isBlinking = false;
}
void Seeking(){
collider[] enemiesInRange = Physics.OverlapSphere(transform.position,blinkRadius)
foreach (collider mobs in enemiesInRange)
{
if(mobs.isTrigger != true)
//bcs i had 2 colliders attached for each enemies 1 isTrigger 1 not
{
EnemyHealth isEnemy = mobs.GetComponent ();
//to make sure its not environments
if(isEnemy != null)
{
Transform target = isEnemy.GetComponent ();
//get transform data for each gameobjects on the array
if(isBlinking)
{
transform.position = Vector3.Lerp(playerRB.transform, target.transform,1f);
//i expect it'll kept moving into each gameobjects transform each 1f before the "isBlinking" turn to false after 10sec
}
}
}
}
}
but the result.. player is blinking only to one enemy on that array and not continuing into next transform on the array, i suspect it only the first one or straight to the last of the list. and had to wait for 10s after isBlinking return to false before i can press fire1 again well this one are actually intended for a limiter so the player won't kept jumpin around all day
about the damage calculations.. i'll add it later after i know how to code about the movement properly
if anyone got simpler method or more advanced coding please teach me
because i doubt OverlapSphere are the best way to do so
maybe even the worst bcs that is the only way i know to get info of our surrounding radius
THANK YOU VERY MUCH
↧
2D Area of Effect Script
Hi, this is my first attempt at an AoE script.
I attached the following to my rockets to do damage and apply an explosion force effect to the enemy it hits and any other enemies within a certain radius:
using UnityEngine;
using System.Collections;
public class RocketExplosion : MonoBehaviour {
public float expRadius = 10f; // Radius within which enemies are damaged.
public float expForce = 100f; // Force that enemies are thrown from the blast.
public GameObject soundPrefab; // Audioclip of explosion.
public GameObject explosionPrefab; // Prefab of explosion effect.
public float Damage=100;
void Start ()
{
}
void OnTriggerEnter2D(Collider2D other){
if(other.gameObject.tag == "Enemy"){
// Find all the colliders on the Enemies layer within the expRadius.
Collider2D[] enemies = Physics2D.OverlapCircleAll (transform.position, expRadius, 1 << LayerMask.NameToLayer("EnemyLayer"));
// For each collider...
foreach(Collider2D en in enemies)
{
// Check if it has a rigidbody (since there is only one per enemy, on the parent).
Rigidbody2D rb = en.GetComponent();
if(rb != null && rb.tag == "Enemy")
{
// Find the Enemy script and apply damage.
rb.gameObject.GetComponent();
HealthEnemy hp=(HealthEnemy)transform.GetComponent("HealthEnemy");
if(hp){
if(hp.CurrentHealth<=hp.MaxHealth){
hp.CurrentHealth=hp.CurrentHealth-Damage;
}
}
// Find a vector from the rocket to the enemy.
Vector3 deltaPos = rb.transform.position - transform.position;
// Apply a force in this direction with a magnitude of expForce.
Vector3 force = deltaPos.normalized * expForce;
rb.AddForce(force);
}
}
}
// Instantiate the explosion prefab.
Instantiate(explosionPrefab,transform.position, Quaternion.identity);
// Play the explosion sound effect.
Instantiate(soundPrefab, transform.position,transform.rotation);
}
}
Now the explosion is not going off half the time, and it doesn't cause damage to the enemies.
The explosion force effect seems to work most of the time though.
What am I doing wrong?
↧
↧
Rocket Explosion not applying damage when hitting ground
Hi Guys,
So in my game there is a rocket launcher which fires rockets of course and when the rocket hits an enemy it does AoE damage, but my problem is that when the rocket hits the ground, the explosion function gets called but there is no AoE damage.
here is my rocket script:
sing UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class rocket : MonoBehaviour {
public float m_Speed;
public float m_BlastRadius;
private Rigidbody rb;
public float m_BlastDamage;
public GameObject m_Player;
private Manager.Teams m_Team;
public List m_PlayerChilds;
void Start ()
{
rb = GetComponent();
m_Team = m_Player.GetComponent().Team;
foreach (Transform child in m_Player.transform)
{
m_PlayerChilds.Add(child.gameObject);
}
}
void Update ()
{
}
void OnCollisionEnter(Collision col)
{
if (m_PlayerChilds.Contains(col.gameObject))
Physics.IgnoreCollision(col.gameObject.GetComponent(), GetComponent());
if (col.gameObject.GetComponent() != null && col.gameObject.GetComponent().Team == m_Team)
{
Physics.IgnoreCollision(col.gameObject.GetComponent(), GetComponent());
}
else
{
ExplosionDamage(col.transform.position, m_BlastRadius);
Destroy(gameObject);
}
}
void ExplosionDamage(Vector3 center, float radius)
{
Collider[] hitColliders = Physics.OverlapSphere(center, radius);
foreach (Collider hitCollider in hitColliders)
{
if (hitCollider.GetComponent() != null && hitCollider.GetComponent().Team != m_Team)
{
float distanceToEnemy = (center - hitCollider.transform.position).magnitude;
float m_Distance01;
m_Distance01 = Mathf.Abs(1 - (1 / radius * distanceToEnemy));
hitCollider.GetComponent().ApplyDamage(0, m_Distance01 * m_BlastDamage);
}
}
}
void FixedUpdate()
{
rb.velocity = transform.forward * m_Speed;
}
}
so as I said the ExplosionDamage() gets called when the rocket hits the ground but no enemies take damage.
Thanks in advance for you help
-skullbeats1
↧
OverlapSphere ignoring all colliders when I use the layerMask parameter.
When I try to use the `layerMask` argument it ignores all layers and doesn't detect any colliders and/or objects. In all the examples I've seen people usually assign an integer the number of the layer and then use it as the right operand of a left bit shift operator on 1, for example: `1 << iLayer`. I don't understand why they do this, there isn't very good documentation on this function or that argument in particular and even after doing the left bit shift it still ignores all colliders/objects in the scene if I try to use the `layerMask` parameter. Same if I just put the integer only or try to use the `LayerMask.NameToLayer` method. Any suggestions, explanations, documentation, examples, etc would be much appreciated as to why it isn't working and how to properly use this function and or parameter.
using UnityEngine;
using System.Collections;
public class SunGrav : MonoBehaviour {
private Collider[] hitColliders;
void Update () {
hitColliders = Physics.OverlapSphere (transform.position, 20.0f, 8);
for (int i = 0; i < hitColliders.Length; i++) {
Debug.Log (hitColliders [i]);
hitColliders [i].gameObject.SetActive (false);
}
}
}
↧
How to write an overlap sphere 2D
Just trying to figure out how to write out a physics.overlapsphere in unity. Haven't used this kind of code yet. Would really appreciate the help, thank you.
void OnTriggerStay2D (Collider2D target) {
target = Physics2D.OverlapCircle (1,7);
if (target.tag == "Player")
{
AttackPlayer ();
}
}
↧