using Unity.VisualScripting;
using UnityEngine;
public class Bullet : MonoBehaviour
{
public float speed = 5f;
public Rigidbody2D rb;
public Vector2 direction;
public int countCollision;
void Start(){
rb = GetComponent<Rigidbody2D>();
direction = transform.right;
}
void Update(){
rb.velocity = transform.right * speed;
}
void OnCollisionEnter2D(Collision2D col){
if(col.gameObject.CompareTag("Monster")){
Destroy(col.gameObject);
}
if(countCollision <= 0){
Destroy(gameObject);
}
Vector2 normal = col.contacts[0].normal;
if (col.gameObject.CompareTag("Wall")){
if (Vector2.Dot(normal, Vector2.up) > 0.5f){
direction.y = -direction.y;
}
else if (Vector2.Dot(normal, Vector2.down) > 0.5f){
direction.y = -direction.y;
}
else if (Vector2.Dot(normal, Vector2.left) > 0.5f || Vector2.Dot(normal, Vector2.right) > 0.5f){
direction.x = -direction.x;
}
UpdateRotation();
}
countCollision -= 1;
}
void UpdateRotation(){
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.eulerAngles = new Vector3(0, 0, angle);
}
}
Vector2 _moveDir;
Rigidbody2D _rb;
[SerializeField] float _speed=5f;
bool _blockMoveUpdate;
void Start()
{
_rb = GetComponent<Rigidbody2D>();
ShootUpdate(transform.right);
}
private void ShootUpdate(Vector2 newDir)
{
_moveDir = newDir.normalized;
_rb.velocity = _moveDir*_speed;
if(_blockMoveUpdate)_blockMoveUpdate = false;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (!_blockMoveUpdate)
{
_blockMoveUpdate = true;
var coll = collision.contacts[0];
Vector2 newMove = Vector2.Reflect(_rb.velocity.normalized, coll.normal);
ShootUpdate(newMove);
}
}