Right now, I have a 360 degree camera that rotates around the player. I currently get the angle between the player's forward and the camera's forward and this works correctly. If the camera is directly behind the player the angle returns 0, and when the camera is in front of the player and looking towards the player, it returns 180.
void AngleBetweenCameraAndPlayer()
{
var playerAngle = _playerTransform.forward;
var camAngle = _cameraTransform.forward;
playerAngle.y = 0;
camAngle.y = 0;
var horizDiffAngle = Vector3.Angle(playerAngle, camAngle);
}
I shoot the ball using .AddForce on its rigidbody, and the ball moves in the direction of the cameras forward.
_ballrb.AddForce(_cameraForward * (power * _timer), ForceMode.Impulse); // projects the ball forward relative to the camera's forward by x power and x time held down.
I then in a separate method draw the balls trajectory using a kinematic equation. This script is attached to the ball gameObject and works correctly.
private void DrawProjection()
{
lineRenderer.positionCount = Mathf.CeilToInt(linePoints / timeBetweenPoints) + 1;
Vector3 startPosition = transform.position;
Vector3 startVelocity = _cameraForward* (power * _timer);
int i = 0;
lineRenderer.SetPosition(i, startPosition);
for (float time = 0; time < linePoints; time += timeBetweenPoints)
{
i++;
Vector3 point = startPosition + time * startVelocity;
point.y = startPosition.y + startVelocity.y * time + (Physics.gravity.y/2f * Mathf.Pow(time, 2));
lineRenderer.SetPosition(i, point);
}
}
The problem I am running into is that when the player is trying to kick a ball, I want the angle of which it can shoot to be locked/ clamped 45 degrees from the players forward, and when you go past 45 degrees, you can still shoot, but it will be locked at that 45 degree angle.
Some ideas I've had is to clamp the _cameraForward by that angle and not let the angle go past 45 degrees, or using an if statement saying that if the angle is less than 45 degrees you can shoot and it will project the line, but the issue is when you go past 45 degrees, you can no longer shoot and it wont project and this is not what I want. I still want you to be able to shoot and project, just locked at that 45 degree angle.
A slightly (imho improved) way of Serlite's answer would be to not go through
Quaternionbut directly stay withVector3.There is
Vector3.Slerpwhich is specifically for directions and maintains the same magnitude all the time (other thanVector3.Lerp).It also handles the clamping already since the factor is always clamped to be between
0and1.Personally I would keep it that way but some people like one-liners ^^