TopDownShooter Tutorial in UNITY. PART 03 – shooting.

Hello, part 03 of Top Down Shooter is already available under this link:

https://youtu.be/CpabElug1dU

CODE:

public class Bullet : MonoBehaviour
{
    public float speed;
    public float damage;

    Rigidbody2D rb2d;
    // Start is called before the first frame update
    void Start()
    {
        rb2d = GetComponent<Rigidbody2D>();
        rb2d.velocity = transform.up * speed;

        Destroy(gameObject, 3);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    private void OnCollisionEnter2D(Collision2D collision)
    {
        Destroy(collision.gameObject);
        Destroy(gameObject);
    }
}
public class Weapon : MonoBehaviour
{
    public Bullet bullet;
    public Transform firePoint;

    public float damage = 1;
    public float shotsPerSecond;
    float nextShotTime;
    // Start is called before the first frame update

    public void Shoot()
    {
        if (nextShotTime <= Time.time)
        {
            Bullet _bullet = Instantiate(bullet, firePoint.position, firePoint.rotation);
            _bullet.damage = damage;

            nextShotTime = Time.time + (1 / shotsPerSecond);
        }
        
    }
}
public class PlayerController : MonoBehaviour
{
    public Weapon weapon;

    public float moveSpeed = 2.0f;
    Vector2 moveDir; // moveDir(x,y) w =1, s =-1
    Rigidbody2D rb2d;

    Vector2 mousePos;
    // Start is called before the first frame update
    void Start()
    {
        rb2d = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        moveDir.x = Input.GetAxisRaw("Horizontal"); //x =1 or x=-1
        moveDir.y = Input.GetAxisRaw("Vertical");

        mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);

        if (Input.GetButton("Fire1"))
        {
            Shoot();
        }
    }

    private void FixedUpdate()
    {
        Move();
        RotateToMousePos();
    }

    public void Move()
    {
        rb2d.MovePosition(rb2d.position + moveDir * moveSpeed * Time.fixedDeltaTime);
    }

    public void RotateToMousePos()
    {
        Vector2 dirToMousePos = mousePos - rb2d.position;

        transform.up = new Vector2(dirToMousePos.x, dirToMousePos.y);
    }

    public void Shoot()
    {
        weapon.Shoot();
    }
    
}

Leave a Reply

Your email address will not be published. Required fields are marked *