Falling Obstacle
What I'm trying to do is having the box falling after the player enters the danger zone (capsule collider). Then, once the box falls I want the player to not be visible (as if it got crushed by the box).
I can't wrap my head around this, if I set the box collider as a trigger, the player could be hidden but the box will keep falling to infinity, and if I don't make it a trigger it will stop on the player's head due to its collider. I'm kinda new to Unity and C# so I apologize if there's a simple solution I haven't considered.
Answer by highpockets · Nov 30, 2020 at 10:01 PM
You could set the box’s collider as a trigger, and when it falls, you could have a min y clamp on it so as to make sure it doesn’t drop through the floor. You can also listen for the box to collide with the floor. Either way just stop it and set the rigidbody to kinematic when it reaches the floor. Below is just a bare example that you would have to work your logic into, but it shows a clamp option, which could be easily swapped for the collision with the ground option.
//y clamp
float minY = 0.1f; //the minimum y axis position to clamp to
bool isFalling = false; //set to true when the box start falling
void Update()
{
//Just an example, you would have to figure out when to set isFalling to true, I have no idea what your code looks like.
if(isFalling && transform.position.y <= minY)
{
GetComponent<Rigidbody2D>().isKinematic = true;
transform.position = new Vector2(transform.position.x, minY);
isFalling = false;
}
}
This helped me to get a solution, however, when the Rigid Body was getting set to Kinematic it didn't stop (assu$$anonymous$$g because it kept the gravity force when it was dynamic), I tried turning it into a static rigid body instead, and it stopped but a little lower than $$anonymous$$Y.
What I did was to use "$$anonymous$$oveTowards" instead. I created a game object with the target transform and modified the code you posted a little to make it work.
Thanks!
Setting a rigidbody to kinematic should stop it being affected by forces and since gravity is a force, it should not make a difference. Were you moving it with by script in anyway? Or was it just falling naturally with physics?? anyhow since you found a solution, that’s great
Answer by WillyHB · Dec 01, 2020 at 10:29 PM
You could try going into Project Settings, then Physics 2D, and at the bottom you can choose which layers collide with eachother. Then you can just untick the box between the player layer and box layer