2D moving camera Camera (scrolling from a-b)

I’ve searched the answers and google, but couldn’t quite find the answer, so apologies if this has already been covered

In games such as classic shoot 'em ups, (those does by Cave/Capcom etc) the player is followed by the camera, yet the camera is continuously moving along a set axis. I know by attaching a camera to the player, it’ll follow regardless, but I wish for the camera to scroll continuously, whilst the player is confined within the view…

How would I go about doing that?

transform.Translate(Vector3(0,speed,0) * Time.deltaTime);

I know the above line will scroll the camera in the axis I wish, however that’s if the camera Is a child of the Player, so when I move player camera moves aswell… which sounds great but the camera adds the playerspeed to it’s own speen I think, so it doesn’t work well.

Any ideas?

EDIT: I unparented… that worked… now really just confining the player within the cameras view

Convert your player position to Viewport space (X and Y are a number from 0 at left/bottom of screen to 1 at right/ top, Z is distance from camera):

var vp = Camera.main.WorldToViewportPoint(player.transform.position);

then clamp it to the screen:

vp.y = Mathf.Clamp01(vp.y);

(same for X and you may want to clamp it with a margin)

then convert back to world space:

player.transform.position = Camera.main.ViewportToWorldPoint(vp);

do this after you have processed player movement controls (or as part of it).

See also : Detect Edge of Screen - Questions & Answers - Unity Discussions