Hello.
Currently I’m trying to make an aiming system for a 3D, 3rd person game. My goal is to have the character aim the attack (a projectile, in this case) in a direction corresponding to the mouse position relative to the character’s own position.
Example: if the mouse pointer is above and to the left of the character, I want the attack to be aimed forward, but with an upward and a leftward angle; this angle should increase the further the mouse pointer is relative to the character.
Unfortunately, I can’t quite get this system to work. What am I doing wrong?
public override void Aim(float range, Camera mainCamera, Transform firingPoint, LayerMask terrainMask)
{
Ray ray = mainCamera.ViewportPointToRay(Input.mousePosition);
float targetRayDistance = Vector3.Distance(mainCamera.transform.position, firingPoint.position) / Mathf.Cos(Vector3.Angle(mainCamera.transform.forward, -firingPoint.forward)) + range; //this takes into the account the angle the camera is at relative to the character, and compensates
if (Physics.Raycast(ray, targetRayDistance, terrainMask, QueryTriggerInteraction.Ignore))
{
firingPoint.rotation = Quaternion.LookRotation(ray.GetPoint(targetRayDistance), firingPoint.up); //if the Raycast collides with terrain, that means the projectile will too; I don't want that; therefore the projectile will be aimed horizontally instead
}
else
{
firingPoint.rotation = Quaternion.LookRotation(ray.GetPoint(targetRayDistance));
}
}