using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AiShootBall : MonoBehaviour
{
[SerializeField] Rigidbody soccerRb;
[SerializeField] float force;
[SerializeField] Transform target;
[SerializeField] float curveStartForce;
float timeToReachDestination;
bool addCurve=false;
float timeRemaining;
// Start is called before the first frame update
void Start()
{
Invoke("ShootBall", 2f);
//ShootBall();
}
public void ShootBall()
{
//this will get the direction to reach the desitination
Vector3 dir = target.position - transform.position;
//then we normalize the value
dir.Normalize();
//way of discovering the time it will take to reach destination
float distance = Vector3.Distance(target.position, transform.position);
//this will get the time to reach the destination
timeToReachDestination = TimeBetweenObjects(distance, force);
//float forceNecessary = ForceNeededToReachDestination(distance, timeToReachDestination);
//this will tell the code to add curve
addCurve = true;
//this will store the time remaining to add curve
timeRemaining = timeToReachDestination;
//we add the velocity to the rb
soccerRb.velocity = dir * force;
//this will add the initial curve force, so that we then add curve to the opossite direction
soccerRb.velocity += new Vector3(-curveStartForce, 0, 0);
}
private void Update()
{
//if we are adding a curve, we decrease the countdown
if (addCurve)
timeRemaining -= Time.deltaTime;
}
private void FixedUpdate()
{
if (addCurve && timeRemaining > 0)
{
soccerRb.AddForce(new Vector3((curveStartForce + curveStartForce) / timeToReachDestination * Time.fixedDeltaTime, 0, 0), ForceMode.VelocityChange);
}
//if the time has ended we tell the code to stop adding curve and we reset the curve timer
else
{
addCurve = false;
timeRemaining = 0;
}
}
//this will find the time it will take to reach destination
float TimeBetweenObjects(float distance, float force)
{
float timeBetweenObjects = distance / force;
Debug.Log("Distance: " + distance + " time to reach: " + timeBetweenObjects + " force " + force);
return timeBetweenObjects;
}
//this will find the force necessary to reach destinatiion
float ForceNeededToReachDestination(float distance, float timeBetweenObjects)
{
//way of discovering force necessary to reach destination at seconds
float forceNeeded = distance / timeBetweenObjects;
Debug.Log("Force needed : " + forceNeeded);
return forceNeeded;
}
}