Reputation: 3842
I got a Cube with a box collider and a trigger on it. When the player stands on it, it falls down.
I want the platform to destroy itself after colliding with something and before that, instantiate itself at its starting position.
So my code looks this:
void OnTriggerEnter(Collider col)
{
if (col.CompareTag("Player"))
isFalling = true;
}
void OnCollisionEnter(Collision col)
{
if (!col.gameObject.CompareTag("Player"))
{
Instantiate(gameObject, startPosition, startRotation);
Destroy(gameObject);
}
}
void Update()
{
if (isFalling)
{
fallingSpeed += Time.deltaTime / 20;
transform.position = new Vector3(transform.position.x, transform.position.y - fallingSpeed, transform.position.z);
}
}
Well when my platform crashes down, it just passes through the ground. There is even no collision detected.
Does someone got a hint for me?
Upvotes: 1
Views: 553
Reputation: 3842
So I just got my mistake.
The platform got no rigidbody attached. Therefore it was not able to collide with the ground.
This is my new code:
private void Start()
{
data.PlatformRigid.useGravity = false; // Disable the gravity to make it stay in the air
}
private void OnTriggerEnter(Collider col)
{
if (!data.Activated) // just do this 1 time
{
if (col.CompareTag("Player")) // just start executing the following code if the colliding object is the player
{
data.Activated = true; // don't execute this code a second time
data.PlatformRigid.useGravity = true; // start falling
}
}
}
private void OnCollisionEnter(Collision col)
{
if (!col.gameObject.CompareTag("Player"))
{
Instantiate(gameObject, data.StartPosition, data.StartRotation); // Create itself at default
Destroy(gameObject); // Destroy itself
}
}
I don't need to calculate the fallspeed in the update anymore. I just disable the gravity and enable it, when the player hits the platform.
Upvotes: 2
Reputation: 571
If your collider is set to trigger, it won't fire the OnCollisionEnter
event. Instead, put your code in the OnTriggerEnter
like this:
void OnTriggerEnter(Collider col)
{
if (col.CompareTag("Player")) {
isFalling = true;
}
else
{
Instantiate(gameObject, startPosition, startRotation);
Destroy(gameObject);
}
}
Upvotes: 0