using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Bomb : Weapon {

    public float throwSpeed = 10f;

    Vector3 debugVec;

    protected override void Fire()
    {
        //GameObject.Instantiate(bulletPrefab, muzzle.position, muzzle.rotation);
        Transform playerTransform = transform.parent;

        Plane plane = new Plane(Vector3.up, playerTransform.transform.position);
        Ray cameraRay = Camera.main.ScreenPointToRay(Input.mousePosition);
        float enter;
        plane.Raycast(cameraRay, out enter);
        Vector3 targetPoint = cameraRay.GetPoint(enter);

        Vector3 spawnPos = muzzle.transform.position;

        float g = Physics.gravity.y;
        float dist2d = new Vector2(targetPoint.x - spawnPos.x, targetPoint.z - spawnPos.z).magnitude;
        float delta = Mathf.Pow(throwSpeed, 4) + 2 * g * throwSpeed * throwSpeed * (targetPoint.y - spawnPos.y) - g * g * dist2d * dist2d;
        float pitch;

        if (delta >= 0)
            pitch = Mathf.Atan(-(Mathf.Sqrt(delta) - throwSpeed * throwSpeed) / (dist2d * g)) * Mathf.Rad2Deg;
        else
            pitch = -45f;

        float yaw = Mathf.Atan2(targetPoint.x - spawnPos.x, targetPoint.z - spawnPos.z) * Mathf.Rad2Deg;

        GameObject bombGo = GameObject.Instantiate(bulletPrefab, muzzle.position, Quaternion.Euler(pitch, yaw, 0));
        Rigidbody rb = bombGo.GetComponent<Rigidbody>();
        rb.AddForce(bombGo.transform.forward * throwSpeed, ForceMode.VelocityChange);
        rb.angularVelocity = bombGo.transform.rotation * new Vector3(20, 0, 0);

        ammo--;
    }

    private void OnDrawGizmos()
    {
        
    }
}
