This is what happens now: https://www.dropbox.com/s/91u32eifzl3f8c5/Unity_Xx8GuSCuM5.mp4?dl=0
As you can see, it's not going towards the mouse position, sometimes vaguely.
Basically, to get the direction I want the ball to go in which is: Ball --------> Mouse Position, I'm casting a ray from the camera to the ground, based on the mouse position, and then substracting the intersection of that ray with the ground from the ball's position and storing that in a vector3 variable.
pointToHit = pointToLook - ball.transform.position;
My code:
float rayLength;
Vector3 mousePos;
Vector3 pointToLook;
Vector3 pointToHit;
public GameObject ball;
private void RotatePlayerToMousePos()
{
//Casts a ray from camera to the ground then stores the intersection of the ray with the ground in pointToLook
cameraRay = mainCamera.ScreenPointToRay(mousePos);
Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
if (groundPlane.Raycast(cameraRay, out rayLength))
{
pointToLook = cameraRay.GetPoint(rayLength);
}
//Rotates player to the positioned where the ray intersects with the ground
transform.LookAt(new Vector3(pointToLook.x, transform.position.y, pointToLook.z));
}
private void HitBallToMousePos()
{
ball.transform.position = attackPointOrigin.transform.position;
pointToHit = pointToLook - ball.transform.position;
ball.GetComponent<Rigidbody>().velocity = pointToHit - ball.transform.position;
//Maintains velocity in all directions.
if (pointToHit.x > 0 && ball.GetComponent<Rigidbody>().velocity.x < 0)
{
ball.GetComponent<Rigidbody>().velocity = new Vector3(
ball.GetComponent<Rigidbody>().velocity.x * -1,
ball.GetComponent<Rigidbody>().velocity.y,
ball.GetComponent<Rigidbody>().velocity.z);
}
else if (pointToHit.x < 0 && ball.GetComponent<Rigidbody>().velocity.x > 0)
{
ball.GetComponent<Rigidbody>().velocity = new Vector3(
ball.GetComponent<Rigidbody>().velocity.x * -1,
ball.GetComponent<Rigidbody>().velocity.y,
ball.GetComponent<Rigidbody>().velocity.z);
}
if (pointToHit.z > 0 && ball.GetComponent<Rigidbody>().velocity.z < 0)
{
ball.GetComponent<Rigidbody>().velocity = new Vector3(
ball.GetComponent<Rigidbody>().velocity.x,
ball.GetComponent<Rigidbody>().velocity.y,
ball.GetComponent<Rigidbody>().velocity.z * -1);
}
else if (pointToHit.z < 0 && ball.GetComponent<Rigidbody>().velocity.z > 0)
{
ball.GetComponent<Rigidbody>().velocity = new Vector3(
ball.GetComponent<Rigidbody>().velocity.x,
ball.GetComponent<Rigidbody>().velocity.y,
ball.GetComponent<Rigidbody>().velocity.z * -1);
}
//Adds force to ball from hit
ball.GetComponent<Rigidbody>().AddForce(pointToHit.normalized * hitForce, ForceMode.Impulse);
}