Using Mathf.clamp on a camera

Hi everyone.

I’m new to using Unity and C#. I am working on a project for uni and need some help please. I’m trying to make a side scrolling shooter game, like R-type. I am trying to make the camera work in the same way as R-Type.

The camera in R-type is always moving at a steady pace to the right and the player is bounded by the camera itself so they cannot move off the screen.

I can make the camera scroll at a steady pace but not sure how to/if I have to use mathf.clamp to set up the boundaries for my camera. If I do need to use mathf.clamp would this script be attached to just the camera or also the player gameobject?

Any help is greatly appreciated :slight_smile:

I haven’t played R type but one usual idea is that player position isn’t dependent on camera’s instead player moves at regular pace and camera’s x Vector2 position is always equal to player’s. To experiment with it create a sphere with constant force component and create a script with a public var named target/player and in Update() say transform.position.x = target/player.position.x; and attach it the camera, thus camera will scroll along with the sphere. If you want smoothness use lerp (to keep it simple). Hope this works…

Thanks for your advice!!

I have managed to clamp the player in my player script with the following…

Vector3 pos = transform.position;

pos.y = Mathf.Clamp (pos.y, minYValue, maxYValue);

pos.x = Mathf.Clamp (pos.x, minXValue, maxXValue);

transform.position = pos;

So now the player cannot move off the screen

However I am now trying to get the camera to scroll. I have read your reply several times and I am struggling to understand it fully, would you be able to shed some more light on the subject. Thanks

1 Like

Sorry for replying late, my character model had some skinning problem (had to do it manually mostly). I said player movements aren’t dependent on camera but camera movements are on player’s. Use this very simple camera scroll script to make camera scroll along player’s x axis. The smooth variable can be used to delay camera’s movement along (make it smoother) lesser the value more the delay :