I am trying to have a block that can only be pushed inside of a rectangular collider. The player has to be able to move through the collider in order to push the block. I have tried to affect the mass upon the block being pushed into the edge collider, the drag, the angular drag, the velocity, isKinematic but nothing will stop the cube from moving when it hits the collider. It is really confusing, any help would really be appreciated...Here is the code:
public class pushBlock2 : MonoBehaviour {
public Rigidbody2D pBlock2;
void OnTriggerEnter2D(Collider2D col)
{
if (col.tag == "edge") {
Debug.Log ("pushblock2 touched edge");
pBlock2.isKinematic = true;
pBlock2.isKinematic = false;
}
}
void OnTriggerStay2D(Collider2D col)
{
if (col.tag == "edge") {
pBlock2.isKinematic = true;
}
}
Why don't you try and create four colliders around the area you want to move your block within? This way you'll have to stop the block from entering those which is much easier task than trying to prevent an item from leaving the collider.
I am pretty sure you will be able to pull this off without any code at all, you just need to setup a couple of static colliders to collide with objects on certain layer and put the cube you wanna move on that layer.
More info on Layer-based collisions can be found here: http://docs.unity3d.com/Manual/LayerBasedCollision.html
The way I understood, you're trying to use the volume defined by a collider as a delimiter for movement. I'm supposing you also desire "realistic" collisions when the object attempts to go outside said volume. That being the case, I'm afraid it is not possible.
The whole physics simulation is made by assuming some rules. Whenever two colliders intersect, the physics follows the rule that two objects should not occupy the same space (just like the real world), and thus it will try to figure out how to separate them again.
You can somewhat work around this by using a set of colliders that defines an hollow object, such as a barrel or box, but its more likely you'll turn off physics simulation for the box and roll up your own algorithm if consistent behavior is needed.
Many things in games are actually "fake" behaviors. Perhaps you can achieve what you want by faking physics or faking collisions?
Related
I am working on a game in unity, a type of sliding number puzzle where you have to line up each piece in ascending order. My code of checking collisions is only working when I start the game, so if I move a piece, it won't tell the near pieces that I moved the near piece. I hope you understood my problem, every help is appreciated. Thank you.
This is how my code looks with the up check. I
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.name == "Piece" || collision.gameObject.name == "Up_Collider")
{
piece_Script.Collide_Up = true;
Debug.LogError("Up");
}
else
{
piece_Script.Collide_Up = false;
}
}
I Thought that the else statement will solve this problem but it didn't.
Make sure all the things I write below are correct in your project:
1- You are using "2D" colliders on both objects.
2- At least 1 of the objects has a "Rigidbody2D".
3- IsTrigger Checkbox is active in your collider.
4- You are using the correct Tag.
5- Check layer collision matrix in - Edit > Project Setting > Physics2D.
And it is better to use tag instead of name
Based on your code in your question and your video, I see at least a couple issues.
First, there's an issue with how you're moving pieces. Your movement code for a Piece is:
Piece.transform.position = Vector3.Lerp(a, b, t);
This is not correct if you want to trigger collider events. These require interactions with rigidbodies, which means you should instead be changing the position of the piece's rigidbody with Rigidbody2D.MovePosition(). This will move your rigidbody within the physics system, which means taking into account collisions/triggers.
So (assuming you get the rigidbody for each Piece when you initialize them), your code might look like:
// Note also that I used Vector2 here - it's best you keep it consistent
pieceRigidbody.MovePosition(Vector2.Lerp(a, b, t));
Second, OnTriggerEnter2D() is not fired when two colliders stop touching. So I don't see your "else" condition being particularly useful. To achieve that with your current code, you could theoretically introduce OnTriggerExit2D() to take care of the "else" condition. However, you run into complications because while moving, a Piece may Enter and Exit the same directional colliders of two other Pieces before coming to rest. You'd have to take into account the order that occurs to get an accurate final state.
While workable, I have an alternative approach to suggest: Abandon using Trigger Collider events, and only check for a valid move at the time a Piece is clicked. Eliminate the collider event handlers, and just execute a Physics2D.OverlapBox() in each position around a Piece when it is clicked. If the position is occupied by another piece or an edge, that's not a valid move. If there is a position without something blocking it, then move the piece there.
I have my main character and added a capsule collider 2d so he would take damage when attacked. When the character is attacking, for example his body is out of the collider space and won’t take damage when hit. Please may you help me solve this issue, I’m very new to unity
One way of doing it is having two different hitboxes that does the same thing but with different shapes so they match two different states of your character.
Enable and disable them in a script when calling the attack using:
Public Collider2D attackCollider; //Drag your attack collider here in the inspector
Public Collider2D idleCollider; //Drag your idle collider here in the inspector
void AttackCollider() //call this fucntion to change to attack collider
{
attackCollider.enabled == true;
idleCollider.enabled == false;
}
void IdleCollider() //call this function to go back to normal collider.
{
attackCollider.enabled == false;
idleCollider.enabled == true;
}
If you want to I'm sure you can incorporate these two functions into an already existing attack function if you have one.
In 3D, you could simply make the Collider a child of any of your bones, it would get animated altogether.
But you mentioned Collider2D, so:
If you have a 2D Rig with bones, you can do the same as obove
If you have a Keyframe Animation, you could animate the collider to match your animation
I am currently making a sidescrolling game in Unity 2D where an enemy rises up, and then dives down to the player, but then keeps going until it is off screen, like how this image shows. 1 I can get the enemy to collide with the player but I can't make it keeping in that direction until off screen. How would I be able to do this?
You have to make your collider to trigger (it's a checkbox on your collider)
That means your object will not be affected by physics when it touch another collider, but it can calls functions.
You have to replace OnCollisionEnter/OnCollisionEnter2D, etc by OnTriggerEnter/OnTriggerEnter2D, etc.
Be careful, the parameter of the function may change too (Collision/Collider).
I'm developing a simple 2D Unity game (which I'm very new to so sorry if this is a silly question!) in which my player can eat its enemies by colliding with them. This works fine as I'm just selecting the "is trigger" component for the enemies and using this code in my Player class:
private void OnTriggerEnter2D(Collider2D other)
{
Debug.Log("Hit detected");
Destroy(other.gameObject);
transform.localScale += new Vector3(x, y, z);
}
However, this means the colliders placed around the border of my background image aren't stopping the enemies. What's the best fix for this?
I don't understand very well your question. However it seems that your collisions are not working. So, remember that for have collisions actually taking place in your game you need to use colliders and that one of the two elements participating in the collision need to have the rigidbody component.
That will make the physics work in the engine, which triggers dont.
To check if that works you can debug with:
// called on collision
void OnCollisionEnter2D(Collision2D col)
{
Debug.Log("OnCollisionEnter2D");
}
From what I understood, you want only to detect triggers between the player and the enemies, but you still want these to collide with physic objects in your scene, such as background colliders.
One possible way to achieve this is to create a child object for the player object with a collider component with the trigger option set, and attaching a script to it to handle the triggers. Then, with the use of layers to group your player and enemy objects, you can uncheck the collision between them following: Edit -> Project Settings -> Physics 2D: "Layer Collision Matrix".
You can assign a script to any enemy, checking the distance with the player in each frame. Then you can Uncheck "is trigger"
Vector2.Distance
I'm making a game (similar to Subway Surfers), and I have a floor made of many small cubes. And I want to make my game do something when the player stops colliding with the floor. But when I use OnTriggerExit (Collider other) I never know if the player stops colliding the floor or just moves from one piece of the floor to another:
OnTriggerExit (Collider other){
if (other.tag == "floor") {
if(/*Object isn't coliding with any other object with the tag "floor" (Or simply isn't coliding with the other piece of the floor) */){
//Do something
}
}
}
It depends on the needs of the game. Since you named Subway Surfer, I would go with the z-coordinate of the player.
I would add the heightFromGround field to the player class (calculated as the difference on the z-axis between the player and the platform underneath).
Then, if heightFromGround is higher than a threshold, you know the player is jumping.
This also allows you to control the Animation of the character based on it's height from the ground (so he can prepare to land) and transition to the running state.
To have different platforms at different heights, you need to know the platform currently underneath the player at runtime.
This is just an approach to avoid collision checking.
If you don't need that level of control on Animations and prefer to keep using collisions, you can simply add a field int touchingPlatforms = 1; and add 1 to it OnCollisionEnter, subtract 1 from it OnCollisionExit. The player is jumping if touchingPlatforms is 0.