Bullet not registering collisions when set to 'Is trigger',Bullet set to "Is Trigger'' goes through any object with RigidBody and Collider
Hello everyone. So when I don't set my bullet prefab to "Is trigger" the bullet works fine and collides with objects. When I set bullet prefab to "Is trigger" it goes through all objects ignoring box colliders... Have been stuck at this one for a while... I would like that when I set the bullet prefab to is trigger It would react to colliders and I could programm it to do things on collisions...
My code below (rotating shooting object)
public class PointAndShoot : MonoBehaviour {
public GameObject crosshairs; public GameObject player; public GameObject bulletPrefab; public GameObject bulletStart; public float bulletSpeed = 60.0f; private Vector3 target; // Start is called before the first frame update void Start() { // Cursor.visible = false; }
// Update is called once per frame
void Update()
{
target = transform.GetComponent<Camera>().ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, transform.position.z));
crosshairs.transform.position = new Vector2(target.x, target.y);
//Distance between turret and targer
Vector3 difference = target - player.transform.position;
float rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
player.transform.rotation = Quaternion.Euler(0.0f, 0.0f, rotationZ);
if(Input.GetMouseButtonDown(0)){
float distance = difference.magnitude;
Vector2 direction = difference / distance;
direction.Normalize();
fireBullet(direction, rotationZ);
}
}
void fireBullet(Vector2 direction, float rotationZ){
GameObject b = Instantiate(bulletPrefab) as GameObject;
b.transform.position = bulletStart.transform.position;
b.transform.rotation = Quaternion.Euler(0.0f, 0.0f, rotationZ);
b.GetComponent<Rigidbody2D>().velocity = direction * bulletSpeed;
}
private void OnCollisionEnter2D(Collision2D collision)
{
Destroy(gameObject);
}
}
Answer by Senetry · Nov 04, 2021 at 07:23 PM
Hello colliders and triggers are not same thing so you probably have to use
private void OnTriggerEnter2D(Collider2D other)
{
throw new NotImplementedException();
}
instead of
private void OnCollisionEnter2D(Collision2D collision)
{
Destroy(gameObject);
}