using UnityEngine;

public class Ply : MonoBehaviour {
  public float moveSpeed = 10f;
  public float rotateSpeed = 75f;
  private float vInput;
  private float hInput;
  private Rigidbody rb;
  public float JumpVelocity = 5f;
  private bool isJumping;
  public float toGround = 0.1f;
  public LayerMask envLayer;
  private CapsuleCollider col;
  public GameObject TennisBall;
  public float tbSpeed = 100f;
  private bool isLaunching;


  void Start() {
    rb = GetComponent<Rigidbody>();
    isJumping = false;
    col = GetComponent<CapsuleCollider>();
  }
  void Update() {
    vInput = Input.GetAxis("Vertical") * moveSpeed;
    hInput = Input.GetAxis("Horizontal") * rotateSpeed;
    isJumping |= Input.GetKeyDown(KeyCode.J);
    isLaunching |= Input.GetKeyDown(KeyCode.Space);

  }
  private bool IsGrounded() {
    Vector3 min_y = new Vector3(col.bounds.center.x,
     col.bounds.min.y, col.bounds.center.z);
    bool touchingGround = Physics.CheckCapsule(col.bounds.center,
     min_y, toGround, envLayer,
     QueryTriggerInteraction.Ignore);
    return touchingGround;
  }

  void FixedUpdate() {
    if (isJumping && IsGrounded()) {
      rb.AddForce(Vector3.up * JumpVelocity, ForceMode.Impulse);
    }
    isJumping = false;
    Vector3 rotation = Vector3.up * hInput;
    Quaternion angleRot = Quaternion.Euler(rotation * Time.fixedDeltaTime);
    rb.MovePosition(this.transform.position + this.transform.forward * vInput * Time.fixedDeltaTime);
    rb.MoveRotation(rb.rotation * angleRot);
    if (isLaunching) {
      GameObject n = Instantiate(TennisBall,
       this.transform.position + new Vector3(0, 0, 1),
       this.transform.rotation);
      Rigidbody rb = n.GetComponent<Rigidbody>();
      rb.velocity = this.transform.forward * tbSpeed;
    }
    isLaunching = false;
  }
}
