So say I have two sprites. These sprites will not have any BoxCollider2Ds or RigidBody2Ds.
How would I be able to detect if a sprite is touching the other sprite using a script inside of the first sprite.
For example I have a player and a flag. I would want something to happen when the player touches the flag
Sorry if this is poorly written or not informational enough, if you need any more information please just leave a comment and I'll respond.
Do you not want the collider due to the physical repulsion due to the collision? If you are looking to just detect if two objects have entered one another, Triggers might be what you are looking for. You will need to have a collider on both objects, but can mark them isTrigger. To see exactly what you need in order for the OnTriggerEnter2D to go off, view the collision action matrix.
If you really want nothing to do with colliders, you can implement basic collision detection yourself for these two objects. For two simple boxes, you can use AABB collision detection, which is just taking the corners of two boxes and determining if the corners overlap.
if (obj1Pos.x < obj2Pos.x + obj2.width &&
obj1Pos.x + obj1.width > obj2Pos.x &&
obj1Pos.y < obj2Pos.y + obj2.height &&
obj1Pos.y + obj1.height > obj2Pos.y) {
// collision detected!
}
If you want to learn more about self implementation to detect 2D collision, this is a good read. With more complex geometry, collision gets more advanced, but I believe you just want to use triggers. If you have more questions about what triggers are, how they function, etc. I can answer them but I was not exactly sure on how you wanted to approach your problem.
Related
I recently started having a look at game development with Unity and was trying to make a simple 2D character with basic movement abilities. This character is supposed to jump and move from side to side, but only if it is standing on something.
Now my question is: How do you check if a player is standing on something? / Get the distance to the next game object / collider beneath the player game object?
Would greatly apreciate any helpful answers and especially explanations on how exactly it works. Thanks!
To do this, you need to send a ray to detect the point of impact on the ground and then calculate the distance. The code below sends a ray from the center of your object down to the maximum height (3) and gives the size.
public LayerMask groundLayer;
public float maxRayLength = 3;
public void Update()
{
var hit = Physics2D.Raycast(transform.position, Vector3.down, maxRayLength, groundLayer.value);
if (hit) Debug.Log(hit.distance); // it will print current distance from pivot
}
If you want to calculate the height of the ray from the character's foot, there are two methods, one is subtracting half the height of the character from it.
Physics2D.Raycast(transform.position-transform.up*height, ....)
Next one is to use an empty object at the base of the character, which we refer to instead of the center.
public Transform pivot;
Then..
Physics2D.Raycast(pivot, ....)
There are a few ways of actually doing this.
The most usual although a bit complicated way of doing it for a beginner is using Raycasts. A Raycast is basically a small invisible line that starts and ends where you tell it to. If anything of a specific tag or layer is caught in it's crossfire you can basically pull that object from your code. Raycasts are used for a lot of things, most notably in Shooter games to shoot or in games like Skyrim to pickup objects and interact with them.
Another way to do this, which is a bit more popular in 2D games is to create a "feet" GameObject and make it the child of the player in the hierarchy. You can add a box collider on that GameObject and check the "IsTrigger". You can add a Tag to your ground objects and through your code using the OnTriggerEnter() and OnTriggerExit() Methods you can basically tell when your character is floating on air and when he is on ground.
Another popular method is to use the Physics.OverlapBox() Method which is pretty much the same as the Trigger Method but you are creating an invisible box (much like a raycast) and instead of only getting notified when Triggered (something enters or exits) you check if the invisible box is colliding with another object/tag/collider (which could be your ground).
There are also a few different things you can do with a Nav Mesh (mostly in 3D) but I think that for now these 3 should suffice!
I am currently working on a classical fps game, I want to be able to generate larger numbers "enemies", ideally in the hundreds. Though this may not be feasible. I am hoping to use physics and Rigidbod[ies] for these enemy models.
Obviously the nice solution would be to have mesh colliders on all these models but I'm pretty sure that will affect performance. So my alternative idea was to instead set them up initially with box colliders while they are atleast X distance from the player and then once they enter that radius around the player to switch (via enabling and disabling) these box colliders to mesh colliders.
Is this possible to do and what are the implications? My initial tests caused the model to lose its collision detection with the floor, and so drop through the environment.
Are there are performance implications to switching (enabling/disabling) colliders/if this would even make a difference?
Lastly if none of the above, is there a better solution to this problem that is performant?
The most common practice I know is using multiple primitive colliders under the same rigidbody; I believe this is much more efficient than using mesh colliders, plus, as an added bonus you can even very easily handle special hits (headshots do x2 damage, leg shots slow enemies down) since you know exactly which collider was hit.
Here is an example of how they did it back in the day in Counter Strike
Notice that you will have to place each primitive collider correctly on the bone structure for it to move correctly during animations.
I think you should have two colliders for your ennemies :
1) A persistant box for physical interaction. (This collider would be on a separate layer, colliding only with the physical space.
2) Then, you would have your flexible box / mesh collider. Instead of swapping colliders, enable/disable them. If it is too far, try enabling the box, and if too close, enable the mesh collider. I think enabling and disabling is better for performance than removing and adding components at runtime. Plus, since you already have an 'environmental collider', swapping isn't an issue for the movement of your ennemies.
Hope this helps.
I have 5 gameobjects on my scene, all having a collider attached to it.
Now I don't know why - but my first top layer (a starBtn) sometimes fail to detect a mouseClick?
It's in 2d.
I detect all raycastHits and store the hits in an array - I then check all layers of all of them and return the one at the top layer. The one I need to call anaction/function from. My top layer is a square sprite.
Is there a best practice for this or a way to ingnore a collider area if an object in from of it is overlapping?
Cheers
Ps: I willadd code to this question in an hour or so.
Ok. What I had to do to solve this was to add a z-value to each object with a collider.
Then cycle through each objects' z-value - storing the highest value. Although this is 2d.
I'm having a problem with Physics! I have imported an object which a bridge from 3ds max to unity 5 ,but the problem is that whenever I want to walk through on it ,I just fall down. It's like there's nothing called BRIDGE! I know there must be a problem about Physics. But how to fix it ?!
When importing a model into Unity it does not have any Collider.
Even though using auto-generated "MeshColliders" is an option
I highly recommend not to use them.
You never need such highly detailed colliders in a game.
Instead, you have to
Add the colliders manually
Here is a little step by step guide
This is the imported model (made with blender) without any collider whatsoever
First thing to do is add a new box collider to the components
as shown in this gif
The next thing to do is scaling the box collider
by either entering the values manually or using the drag/GUI version like I do in the gif below
(you probably know that already but the mode can be changed to orthographic by licking the small cube in between the cones in the upper right)
If necessary you can add as many "detail" collider as you want
by repeating the steps. Sometimes sphere or capsule colliders might fit better but keep in mind that they have a higher resolution!
In this case i added another box collider representing the upper part of the car:
Thats all you need to make things collide with your object
Right now you only have a MeshFilter, MeshRenderer, and Animator component attached. You walk through it because the mesh is only being rendered. In order to add collision, add a MeshCollider component to it.
Joe offers another way to do it with box colliders. There is a bit to know about both methods:
Box colliders will take more time to set up (rather than just adding a
component) and will have less precision. They will have faster performance.
Mesh colliders do not collide well with other mesh colliders.
However, this is often not an issue. If a mesh collider has the
"convex" checkbox checked then it will collide just fine with other
mesh colliders. Small items and any convex-shaped meshes should have
"convex" checked.
For something like your bridge.. it depends on your game. If you are doing a top-down game with limited mobility (no jumping) then box colliders may work for you. If you are making a first-person game then I would strongly suggest mesh colliders. If you decide to use box colliders then you must set them up carefully. Otherwise, physics may not match up with what the player sees!
Do not worry about performance at this time. Worry about it later IF it becomes an issue. With the physics upgrade in Unity 5, it probably won't be.
With a whole bunch of copy-pasting from all over the web, I managed to hack together a piece of C# code which spawns a random object from an array when the player enters a large, spherical collision trigger. When the player leaves the trigger, the object is deleted. It's working almost as intended, only problem is that six out of ten times when the player passes through the collider, for a split second it feels like a physical collider. Meaning that although the player is trying to move straight forward, he or she will move left or right along the trigger collider for about half a second, before the object spawns and the player can move freely again.
I was under the impression that checking the "Is Trigger" box would remove all physical properties of that specific collider? Am I missing something?
I'm using the standard FPS Character Controller in Unity 5 if that might have something to do with it.
All help is greatly appreciated.
Make sure the spherical collision trigger has a rigid body component, and that the "Is Kinematic" property of the rigid body is checked.
Realized my solution didn't get posted as I thought it had. Yoyo's solution was correct. The object containing the code was also the trigger. Switched so that the player was the trigger and now all is well.