I have a 3D, third person game for which I want to be able to instantiate objects at a fixed distance away from the player, in the direction that my camera is looking at.
Currently, I'm using Cinemachine virtual cameras, and I'd like to be able to spawn an object in the direction of my mouse location based off the current virtual camera I'm looking out of.
I have some logic like this, but the direction is very inconsistent (sometimes its in the same direction, othertimes its behind). Any ideas?
Vector3 mousePosition = Input.mousePosition;
mousePosition.z = Camera.main.transform.position.z;
Vector3 mouseLocation = Camera.main.ScreenToWorldPoint(mousePosition);
mouseLocation.y = Mathf.Max(0, mouseLocation.y);
Vector3 direction = (mouseLocation - transform.position).normalized;
Vector3 finalPos = transform.position + direction * Mathf.Min(maxDistance, (mouseLocation - transform.position).magnitude);
Instantiate(tempProjectile, mouseLocation, Quaternion.identity);
Help is appreciated!