Unity 2D... getting accurate X and Y values of camera when rotating it.

Hey all! I am currently working on a 2D runner and I am using my camera position to determine when to spawn objects. At the beginning of each stage I make a list of every object that will be spawned and its spawn position, and then when the player gets close (basically, when the objects are just off of the player’s screen), the object will spawn. So far I have been using this code to get my camera position:

camera_location = Camera.main.ViewportToWorldPoint(new Vector3(1, 0.5f, Camera.main.nearClipPlane));

I then use a simple comparison on the x position in Update to create a list of stuff that will spawn that frame:

short_spawnerpositionlist = spawnerpositionlist.Where(x => x.x_position - distance_to_spawn < camera_location.x + x.distance_to_spawn_x_offset).ToList();

And voila. It works. I use something similar to despawn once off the screen.

HOWEVER. I recently added an object which, when the player hits it, makes the camera spin around once on its z-axis (so basically the screen spins clockwise in one full circle.) Here is the code:

if(is_rotating)
		{
			transform.Rotate(0, 0, Time.deltaTime * rotate_smooth);

			if(rotation_last > transform.rotation.eulerAngles.z)
			{ 
				is_rotating = false;
				rotation_last = 0;
				transform.rotation = Quaternion.identity;
			} 

			rotation_last = transform.rotation.eulerAngles.z;
		}

I noticed this totally messes up the spawns and despawns while the spin is happening. Looking into it a bit, I realized that the way I am getting camera location each frame is affected by the rotation of the camera… so my x value, for instance, will go from 2 all the way to like… -6 or something… and then back to 2 even though the camera / player has not moved at all, just the camera’s rotation.

So obviously I need another solution. I’m thinking maybe there is some way to get camera_location that is more about getting the location in fixed space, such that even if you rotate the camera it is still giving the fixed x location? Or something? Does anyone have any ideas here?

The problem you’re having is that you’re making measurements through the viewport. When the camera moves the world point it is pointing at moves. Just use Camera.main.position. All you’re doing by projecting to the nearClipPlane is adding a small Vector3 depending on the magnitude of your nearClipPlane. So, if necessary, just add that Vector to your camera’s position. With a rtation of (0,0,0) and a nearClipPlane of .3, you’d add Vector3(0,0,.3) to your camera to attain the same thing but independent of rotation.