How to create a unity event to determine distance between objects, and do something when distance is small enough? - unity3d

I'm trying to use the EventManager and according Events to calculate the distance between objects, and to do something when enough objects are close to the target.
I watched video's on YouTube and searched for examples on Google, but I couldn't find something that looks like what I want. Of course I also watched the explanation videos of Events in general, but I just don't get it. They are all English, which is not my native language, this makes it difficult to understand. So, also sorry for any grammar mistakes. They often talk so fast. So please don't think I'm lazy, I have searched for hours but I just don't get it.
I have one target object, and several enemy objects. This enemy objects have the tag 'Enemy'. The target object can move. I made a coroutine, so when the target moves, the enemies follow, until a distance of 0.5. But from the moment that they reached the distance of 0.5, the enemies won't move anymore. Instead they should also follow the target when they already reached their target position. So to prevent this, I changed the while(Vector3.Distance(transform.position, target.position) > 0.5f) in while 1 > 0, (so just always) and I deleted the part of the code that was about 'after the while loop'. But this is probably not the right way.
So, in short, I want to make an Event that keeps track of when enemies reaches or loses their target position. When three enemies are on their target position, I want to make them blue.
Could anyone show me how I can do this? I don't get it now, but when I see how it works I can use this for more events in the game.

I think You can use trigger collider, just make it bigger then your target object, then do all you want about enemies in methods OnTriggetEnter, OnTriggerStay

As an another technique you can use raycasts. Raycasts will provide you more performance than colliders.
You can locate your raycasts in your target position, in case your raycast hit the enemy then make them blue. For Example;
public LayerMask enemyLayer;
bool isTouch = false;
public bool isTouched(){
if (Physics.Raycast(transform.position,-Vector3.up,1f,enemyLayer)) {
isTouch = true;
return isTouch ;
}
return !isTouch ;
}

Related

Unity - two human players, how to detect which player did most damage to AI enemy?

I truly apologize for I have no code to offer here.
I am completely stumped, I’m still a coding noob and trying to run a simple exercise to test a game mechanic idea via prototype.
I’ll use a simple example:
2 players vs. 2 AI enemies
both enemy ai have 400 points of health
both human players have guns that do 20 points of damage per trigger
press.
both enemies are dead after a quick battle.
I want to reward the player who did the most damage to the enemies.
This is what I am trying to achieve:
How do I go about detecting, which player, did the most damage to the enemy AI?
Any help would be appreciated, once I can grasp the concept of how to even go about doing this, I can then move forward on how to code it.
Thanks.
The question is too general - there are a lot of ways to do this. Let's stick to OOP: let's make the "damage" object (script, class), which contains the following info: damage amount, player id. Wheh player hits trigger, lets assume, the bullet prefab is instantiated. It has a script (MonoBehaviour) on it, called "DamageContainer". When you instantiate a bullet, you also create your "damage" object, set correct values, and put it into bullet's "damage container". Then, when bullet collides with enemy, you get this info from bullet. Damage amount you use to reduce enemy's health. For counting damage, you need the counter itself. It can be a static class, a scriptable object, singleton, or something else. Let's use a static class, which is not the best practice, but simplest one. You need a simple static class, called "DamageCounter", and containing two public fields: Player1Damage and Player2Damage. When bullet collides with enemy, you need to add dealt damage to proper field of "DamageCounter", depending of damage.PlayerId field.
And don't forget to reset static class values on start of each battle.

Unity - Deleting other instances spawning on top of another, but keeping the original

So, I am working on some level generation stuff in Unity, and I have some cubes spawning around the world. The way I have it working right now, is that each floor tile checks if there is 'air' around it and if so, it spawns a wall. But, if I have a situation where this is an air block between two floors, it'll spawn two walls.
Is there a way I can check if there is multiple in the same position, but keep one from destroying?
Thanks!
p.s Also worth nothing, I place the walls using Raycasts, so the floor will check in 4 directions using one hit. I figure it's checking all 4 directions without stopping when it places a cube. So, may be an issue...
U can try making a overlapsphere where the raycast hits, that way all the objects in a certain radius get detected (so also objects that are in each other)
void GetWalls(Vector3 raycastTargetPosition, float radius)
{
Collider[] hitColliders = Physics.OverlapSphere(center, radius);
int i = 0;
while (i < hitColliders.Length)
{
hitColliders[i].SendMessage("AddDamage");
i++;
}
}

How to calculate the length of platform/object in Unity 5?

I'm new to Unity and after watching and reading some tutorials I'm now trying to make a simple 2D platformer kind of game. In the said game both enemies and player can jump to different platforms and traverse it like the old SnowBros game.
The problem I'm facing is related to programming the enemy movement. In my game there would be several types of enemies but generally for now there are two types, one that can jump from the platform and one that only walks upto the length of the platform, wait for 1 second then flip and walk backwards; meaning they don't get off the platform. Now this is an issue I'm having trouble with. I can't seem to find a way to calculate the length of the underlying current platform. I thought of using the collider.bound.min.x and max.x to come around the problem but the issue is I can't seem to find a simple way to reach the current platform's collider without fetching the script and then going through it.
Since, there would be many platforms of many different sizes and each platform is made up of a prefab of other platforms, it just doesn't seem like a workable solution to use the platform script and then traverse through it.
You can use Physics2D.Raycast to "sense" for collisions on a Ray. Imagine the enemy putting their toe one step forward, feeling if there is still solid ground, and then deciding whether to stop.
void Update()
{
Vector2 newPosition = transform.position + velocity * Time.deltaTime;
Vector2 downwardDirection = Vector2.down; // you may have to replace this with your downward direction if you have a different one
RaycastHit2D hit = Physics2D.Raycast(newPosition, downwardDirection);
if (hit.collider != null)
{
// solid ground detected
transform.position = newPosition;
}
else
{
// no ground detected. Do something else...
}
}
You can and should define the Layers your Raycast is supposed to hit, so it can ignore the enemy itself and avoid self-collision.
Well, I hope that you have prefabs of platform and in those prefabs put colliders at start and at end. You can specify layers and tags so that only enemy can detect those colliders and then you can detect tags on collision from enemy script and make your operation.
First create layers by opening Edit -> Project Settings -> Tags and Layers. Create two Layers
Create layers for enemy and enemyColliders and Goto Edit -> Project Settings -> Physics2D. Set collision matrix as EnemyCollider will collider with enemy only.
And your prefab will be looks like,
I hope this would help you.

Unity 2D Bounce Back moving object when colliding with another object

I have an object that, after receiving its respective input, it moves this way:
mov = new Vector3((Input.GetAxis("Horizontal") * vel), 0, 0);
transform.position += mov;
But, I want it to bounce back, once it collides with an object.
I´ve made the procedures already (OnCollisionEnter2D(Collsion2D col){bla bla...}), but I need help with what happens on the collision (bouncing back the object)....
I´ve tried giving the collided object a bouncing material, but it just slows it a bit, my guess is that because of the constant force given by the acceleration.
Greetings.
If you move the object with transform.position what you are doing is basically a "teleport" so it will ignore the bouncing material. If you want it to bounce you have to write the physics code to detect a collision and change the movement or you can do addforce to move the object and it will detect collisions and react automatically.
you are teleporting the object at the current time. instead you should use the Rigidbody.addForce this will add a force in the specified direction thus if you do the opposite direction will "bounce" of the object. Another option would be to create a physics material then not bother with the code.
You are not using materials, right?
See if the content of this post may help you, the OP is using a formula using Raycast and the answer guides him to use the Raycast with Layers Maks:
2D bouncing formula doesn't work properly
There is this one also with fixed angles (like Pong), but it uses material (with values: friction: 0, bounciness: 1):
https://gamedev.stackexchange.com/questions/70294/get-gameobject-to-bounce-of-colliders
But if nothing makes sense and you are going crazy and might want to start from zero, there is this official video tutorial on bouncing and sliding in 2D:
https://unity3d.com/learn/tutorials/modules/beginner/2d/sliding-bouncing-2d

Unity3d - check for collision on non moving objects

I have a sphere build from multiple objects. What I want to do is when I touch/click an object, that object should find all adjunctive objects. But because none off them are moving, no collision detection can be used.
I can't find a way to detect these adjunctive objects even when the colliders do collide with each other, as I can see that in the scene. I tried all the possibilities, but none off them are working, because no objects are moving.
Is there a way to check for manual collision detection, or is there some sort of way to let Unity3d do the collision detection automatically?
You could keep a list of all those objects, then when your event happens you can send messages to all them to do what you want them to do.
Lets assume you want your sphere to break into little pieces. You send a Force message to the sphere. Then you use Newton's Laws of motion and find out how much velocity each piece gets. Remember velocity is a vector thus it has direction.
This is how I would do it and still keep the right amount of control over what happens in my game/simulation. Remember F = ma.
you could use RaycastHit (http://docs.unity3d.com/Documentation/ScriptReference/RaycastHit.html) for your collision, this also works on non-moving objects but it needs more performance
You can add rigidbody to every objects; when you touch one of them, give a force onto it, then it is going to move and trigger event of the adjacent objects.
for the reason you do not want to move the object you touch, you can cancel movement in the OnCollider or OnTrigger event handler function.
I managed to work around this by checking the distance from the selected object and all other objects that are part of the sphere. If the distance is below a certain value, then it is an adjunctive object.
Although this is certaintly not fool proof, it works without problems so far.
I am sorry I was not clear enough. Thanks for all the advice what so ever.