Пуля не реагирует на врага Unity2D
Написал код, у пули и врага есть Rb и BoxCollider2D, находятся на одном слое, но пуля просто пролетает сквозь врага, вообще никак не реагирует на него. Код для пули:
public class bullet : MonoBehaviour
{
/*public float speed;
public float lifetime;
public float distance;
public int damage;
public LayerMask whatIsSolid;
private void Update()
{
RaycastHit2D hitInfo = Physics2D.Raycast(transform.position, transform.right, distance, whatIsSolid);
if (hitInfo.collider != null)
{
if (hitInfo.collider.CompareTag("Enemy"))
{
hitInfo.collider.GetComponent<Enemy>().TakeDamage(damage);
}
Destroy(gameObject);
}
transform.Translate(Vector2.right * speed * Time.deltaTime);
}*/
public float timeDestroy = 3f;
public float speed = 0.1f;
public int damagee = 10;
public Rigidbody2D rb;
private Enemy enemy_damage;
void Start()
{
rb = GetComponent<Rigidbody2D>();
Vector3 diference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
float rotateZ = Mathf.Atan2(diference.y, diference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotateZ);
rb.velocity = transform.right * speed;
Invoke("DestroyBullet", timeDestroy);
enemy_damage = GetComponent<Enemy>();
}
void DestroyBullet()
{
Destroy(gameObject);
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Enemy"))
{
DestroyBullet();
enemy_damage.TakeDamage(damagee);
}
}
}
и код для врага:
public class Enemy : MonoBehaviour
{
public int health;
private bullet damage;
private void Update()
{
damage = GetComponent<bullet>();
if (health <= 0)
{
Destroy(gameObject);
}
}
public void TakeDamage(int damage)
{
health -= damage;
}
}
Источник: Stack Overflow на русском