Answer the question
In order to leave comments, you need to log in
How to correctly handle collisions of bullets with objects?
Hello dear experts.
I was tormented by one question, it concerns the processing of the results of the collision of objects.
After reading a lot of sources on the Internet, I always saw about the same concept and the same concept for the bullet collision handling approach,
for example:
//часть кода висит на пуле врага BulletEnemy:
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Player")
{
//получаем компонент отвечающий за жизни Player
HealthScript playerHealth = collision.GetComponent<HealthScript> ();
//наносим урон
playerHealth.Damage (1);
//уничтожаем пулю
Destroy(gameobject);
}
}
//часть кода висит на пуле Игрока PlayerBullet:
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Enemy")
{
//получаем компонент отвечающий за жизни PlayerBullet
HealthScript enemyHealth = collision.GetComponent<HealthScript> ();
//убиваем врага
enemyHealth.Die();
//уничтожаем пулю
Destroy(gameobject);
}
}
//часть кода пули врага BulletEnemy
void OnTriggerEnter2D(Collider2D coll)
{
//при столкновении с Player
if (coll.transform.CompareTag("Player") )
{
//просто уничтожаем пулю, и больше ничего не делаем
Destroy(gameobject);
}
}
//часть кода игрока Player
void OnTriggerEnter2D(Collider2D coll)
{
//если в нас попала пуля врага
if (coll.transform.CompareTag("BulletEnemy") )
{
//уменьшаем себе жизни
health--;
.......
}
}
//часть кода пули игрока PlayerBullet
void OnTriggerEnter2D(Collider2D coll)
{
//если пуля игрока попала во врага
if (coll.transform.CompareTag("Enemy") )
{
//просто уничтожаем пулю, и больше ничего не делаем
Destroy(gameobject);
}
}
//часть кода врага Enemy
void OnTriggerEnter2D(Collider2D coll)
{
//если в нас попала пуля игрока
if (coll.transform.CompareTag("PlayerBullet") )
{
//убиваемся
Die();
.......
}
}
Answer the question
In order to leave comments, you need to log in
If the victim will track hits, then she will need to know about all possible ways of dealing damage and ask the bullets for their damage, which is rather strange. The most logical thing is when the properties of the bullet are stored in it, and not anywhere else, and the bullet itself deals damage. This will make it easier for you to add new properties to weapons, such as incendiary cartridges, in which case. And it would be better if you use GetComponent in the pool to get not a specific class, but an interface, for example IDamageable, and pull the Damage method. I don’t advise you to check the tags either, it’s better to spread your own and enemy bullets into different layers, and indicate the possibility of a collision in the matrix in the project settings .
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question