- Home /
Question by
Mika_Joel · Dec 01, 2017 at 01:27 PM ·
collisionprefabphysics2dcollider2d
Physics2D.IgnoreCollision not working!
In this project I want each enemy prefab to ignore each other's collision boxes (2D) but only the first to spawn ignores everyone else's collider. Please help. Attached is my enemy code and a video demonstration of the bug: https://youtu.be/XOAm6KTvtXY The code to note is line 22-24.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Depression : MonoBehaviour {
private int speed = 5; //Speed of enemy
private Rigidbody2D rb; //Enemies rigidbody
private SpriteRenderer lookingRight; //Is the enemy facing right?
private bool movingRight = true; //Is the enemy moving right?
private GameObject clones; //Other cloned of the same enemy
public static float health = 40f; //Enemies helath
public TextMesh healthText; //Enemies health text display
void Start(){
rb = GetComponent<Rigidbody2D> (); //Get the rigidbody of the enemy
lookingRight = GetComponent<SpriteRenderer> (); //Get the sprite renderer of the enemy
}
void Update(){
clones = GameObject.FindGameObjectWithTag ("Depression"); //Finding other clones in game
Physics2D.IgnoreCollision (GetComponent<Collider2D> (), clones.GetComponent<Collider2D> ()); //This allows the enemy type to pass through each other's colliders
healthText.text = health.ToString(); //Set the health text to the current health of the enemy
//Enemy movement
if (movingRight) {
rb.AddForce (transform.right * speed); //Moving right
} else if (!movingRight) {
rb.AddForce (-transform.right * speed); //Moving left
}
if (health <= 0f) { //If the enemy is at or below 0 health, destroy the enemy.
Destroy (this.gameObject);
Game_Manager.focus += 0.05f;
//TODO: Make focus increment (per kill) relative to player's accuracy.
}
}
void OnTriggerEnter2D(Collider2D other){ //Changing the direction of the enemy
if (other.gameObject.tag == "Turn" && movingRight == true) { //If the enemy hits a trigger called "Turn", the enemy flips it's sprite on the x-axis and starts to move left
movingRight = false;
lookingRight.flipX = true;
} else if (other.gameObject.tag == "Turn" && movingRight == false) { //If the enemy hits a trigger called "Turn", the enemy flips it's sprite on the x-axis and starts to move right
movingRight = true;
lookingRight.flipX = false;
}
}
}
Thank you, Mika Joel.
Comment