- Home /
Collision issue with SetParent (C#)
I'm developing a 2D game where I have a power up that sets a shield as parent on the player. The shield has it's own tag. But I have a problem, once the player gets the shield, I set it as parent and once an enemy collides with the player and the shield the player dies, making it seem that the player didn't have a shield at all.
I've set the enemies so that they should collide with a "Player" tag and kill the player, but i want to have it so that when the shield is in use, the enemies is going to collide and "bounce" off. Should I ignore the players collision when the player has a shield or is there some other way to solve this? Keep in mind that the enemies move with a speed, so could it be that the enemies move too fast so they still collide with the "Player" tag?
I'm grateful for all the help I can get, you guys are great!!
Here's the code for spawning shield:
public void SpawnShield()
{
// Get the transform ahead of time for readability
Transform charTransform = GetComponent<MoveScript>().character.transform;
// Instantiate and keep track of the new instance
GameObject newShield = Instantiate(shield, charTransform.position, charTransform.rotation) as GameObject;
// Set parent
newShield.transform.SetParent(charTransform);
shieldPowerUpActivated = true;
}
and here is the enemy collision code:
public void OnCollisionEnter2D(Collision2D col)
{
//If the enemy collides with "Player" load level
if(col.gameObject.tag == "Player")
{
Application.LoadLevel(0);
}
}
Answer by JoeStrout · Mar 14, 2016 at 06:55 PM
Yes, an object (especially a fast-moving one) may easily collide with both the shield and the player inside it at the same time. Your player-collision code should simply check whether the shield is currently in effect, and if so, ignore that collision.
Hm, seems I still can't fix the problem, I think there might be an issue because I set parent for the shield, I scaled up the collision box for the shield and when an enemy hit, but the player was still killed. So I don't think it's the speed of the enemy that causes it.
No, it's your code that is killing the player. The speed of the enemy relates (weakly) to whether the collision event fires. If that's confusing, ignore it and assume that the collision event is always going to fire on both the player and (when present) the shield. So, you need to update your code so that if the shield is in effect, it doesn't kill the player — it just ignores the collision.
Your answer
Follow this Question
Related Questions
make OnCollisionEnter2D ignore collisons of child objects 0 Answers
Checking for collision with 2D objects/sprites 3 Answers
Collision on specific Frames 1 Answer
Multiple Cars not working 1 Answer
[c#]collision script not working 1 Answer