#Spawning objects based off camera direction / mouse location

1 messages · Page 1 of 1 (latest)

near hazel
#

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!

gleaming zenith
#

Orthographic or perspective camera?

near hazel
#

Orthographic

gleaming zenith
#

2D game?

near hazel
#

3D

#

Sorry, should have specified

gleaming zenith
#

So like... Isometric/top down shooter kind of thing?

near hazel
#

yeah kinda

#

I imagine I want to draw a line from where the player is to where my camera is pointing at

gleaming zenith
#

Use:
Camera.ScreenPointToRay
To get a ray.
Then make a Plane with the Plane constructor and Raycast against it with Plane Raycast with the previously calculated ray

#

The Plane would be your game world Plane

near hazel
#

thanks! I'll give it a try