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.
↧
Detecting how much of a Sphere is overlapped
↧
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 ();
}
}
↧
Can you use OnCollisionExit with an OverlapSphere?
I need to simulate a gravitational field around a planet so I used an `OverlapSphere` to have certain affects on objects once they enter its field. I need to know when it exits the `OverlapSphere` so I can handle its velocity accordingly.
↧
↧
How to check if 2 collisions are on the same objects ? (is player on the same ground than enemy?)
Hi guys,
I'd like to check if my groundCheck for player and groundCheck for enemy are colliding with the same ground.
My detection system is an OverlapCircle checking for a Ground layer.
So I want to look at my "collision" events for both detections and compare the objects concerned.
NB : all that is 2D
Thanks !
↧
My OverlapSphere and Layer Mask isn't working.
So what I'm trying to do is instantiate a bunch of items at random points, each a certain distance apart.
Reading around, I saw that using Layermasks and the Physics OverlapSphere would be my best bet.
But I can't figure out what's wrong with my code for the life of me. No matter what I do, all the items spawn at the exact same spot.
public GameObject pickup;
private GameObject gameBike;
private Vector3 gameBikePosition;
private int numberOfPickups = 10;
private float distributionRadius = 25;
private float distanceBetweenPickups = 10;
private float pickupHeight = 1;
private bool positionIsValid = false;
public LayerMask itemLayer;
private Vector3 pickupPosition;
Vector3 CheckForNeighbours(){
int mask = LayerMask.NameToLayer("Pickup");
while (positionIsValid == false)
{
float xPosition = Random.Range(gameBikePosition.x - distributionRadius, gameBikePosition.x + distributionRadius);
float zPosition = Random.Range(gameBikePosition.z - distributionRadius, gameBikePosition.z + distributionRadius);
pickupPosition = new Vector3(xPosition, 0, zPosition);
float height = Terrain.activeTerrain.SampleHeight(pickupPosition) + pickupHeight;
pickupPosition.y = height;
Collider[] neighbours = Physics.OverlapSphere(pickupPosition, distributionRadius, 1<<9);
if (neighbours.Length == 0){
positionIsValid = true;
return pickupPosition;
}else{
positionIsValid = false;
}
}
return pickupPosition;
}
↧
Obtaining Point Of Overlap with Physics.OverlapSphere?
I've been forced to make my own collision detection because unity's OnCollisionEnter doesn't seem to be working reliably. So I've been casting overlaps every frame in a small radius to check for collision. The only property I see about contact is contact offset. Is there a way I can find out the first point of contact with the overlap?
Code:
internal void FireProjectile(GameObject projectile, float speed)
{
projectile.transform.position =
State.PlayerTransform.position + State.PlayerTransform.forward;
projectile.transform.rotation = State.PlayerTransform.rotation;
m_ProjectileRigidbody = projectile.GetComponent();
m_ProjectileRigidbody.AddForce
(State.PlayerTransform.forward * speed, ForceMode.Impulse);
if (State.PlayerState.Consumes)
{
State.PlayerState.ConsumeCellEnergy(EnergyConsumption);
State.PlayerState.GenerateCellHeat(HeatProduction);
}
}
↧
Get all Objects from a Physics.OverlapSphere with Name X
heyhey. i wanna apply an explosion force to all objects in a Physics.OverlapSphere with the name "X". so my script snippet looks like this now:
Vector3 explosionPos = transform.position;
Collider[] colliders = Physics.OverlapSphere(explosionPos, radius);
foreach (Collider hit in colliders) {
Rigidbody rb = hit.GetComponent ();
rayhits.Add (hit.GetComponent().gameObject);
//Add force to nearby rigidbodies
if (rb != null)
rb.AddExplosionForce (power, explosionPos, radius, 3.0F);
}
in there you can see that all "rayhits" with the component collider gets added to a list. all i wanna do now is to sort out all the other colliders and just add the one with the name "X" to that list.
↧
↧
Check what overlapSphere is colliding with
I want overlapSphere to only return true if it's colliding with an object that has collision with the player enabled. Problem is, I need to know which collider it's overlapping with in order to do that. How can I get access to that, if it's even possible?
↧
How to get the nearest collider, or just a single collider from Physics.OverlapSphere?
So I'm making a game with different unit types moving about in formations, when the player controlled formation gets close to the enemy, it stops and projects an overlapsphere to check for tags - allowing it to see what type of unit it's up against.
So ultimately I need to take the colliders from overlapsphere and return anywhere from one to three strings, detailing the enemy unit's tags.
The problem is that overlapshere produces an **array** of colliders, and so I'm not sure how to return just one if that becomes an eventuality.
private string CheckEnemies()
{
Collider[] enemyColliders = Physics.OverlapSphere(unit.transform.position, combatRadius);
foreach (Collider col in enemyColliders)
{
string unitName = col.gameObject.tag;
}
return what?
}
C# doesn't have the ability to return two data types to the best of my knowledge, so I'm not sure what to do here.
↧
OverlapSphereNonAlloc Not Working?
Ok, so I'm trying to write a simple little script to detect objects that can be picked up in front of my character. If I use Physics.OverlapSphere I get the results I want, but if I use the exact same values in Physics.OverlapSphereNonAlloc then I don't detect any collisions. It's running every frame, so I'd prefer to use the less-garbage-y approach.
Here's my code:
[SerializeField]
private float pickupSphereForward = 0.5f;
[SerializeField]
private float pickupSphereSize = 1f;
private Collider[] nearbyPickupables;
private void Update()
{
// This works.
nearbyPickupables = Physics.OverlapSphere(transform.position + transform.forward * pickupSphereForward,
pickupSphereSize,
LayerManager.PickupableMask);
if (nearbyPickupables.Length > 0)
{
Debug.Log("Nearby pickupables!");
}
// This doesn't work.
if (Physics.OverlapSphereNonAlloc(transform.position + transform.forward * pickupSphereForward,
pickupSphereSize,
nearbyPickupables,
LayerManager.PickupableMask) > 0)
{
Debug.Log("Nearby pickupables!");
}
}
At this point in time I really just need to figure out what's going wrong on point of principle. I'm not going to sleep properly otherwise haha
↧