limit the player so he can't go off screen

hi, again, i’m making a side scroll game and the player can go left and right while the screen is moving but i don’t want the player to be able to go off screen, i tried to use Mathf.Clamp but the problem here is that the screen is the player is moving with the screen. andy ideas? , thnx.

Hi BakeSlots, I've got the same problem (with a 2D arcade shoot-em-'up)...If the screen is scrolling (vertically, I suppose), Camera also scrolls, isn't it? So you can, in the Update() function of Player, calculate the position of the Camera, getting its y-component (I'm supposing that the screen scrolls towards y axis), then check the actual position of Player with the y-component just obtained.

Thanks it works for me :D

3 Answers

3

Here is C# script that I am using I just changed couple things so that it would stop at the desired LEFT/RIGHT end possitions. (if that makes any sense)

To test it just create New object Cube and attach this script to it.
Make sure to set Player Speed for moovement in Inspector.

using UnityEngine;    
using System.Collections;
        
public class Player : MonoBehaviour 
{
public float PlayerSpeed;	

void Update () 
  {

	//Amount to move
	// Input.GetAxis MAKES MOOVEMENT LEFT TO RIGHT WITH SMOOTHING
	float amountToMove =Input.GetAxis("Horizontal") * PlayerSpeed * Time.deltaTime;

	//Move the Player
	transform.Translate(Vector3.right * amountToMove);
	
	//When Players reaches desired (L/R)possition make him stop
	if (transform.position.x <= -7.5f)
	    transform.position = new Vector3(-7.5f, transform.position.y, transform.position.z);
	else if (transform.position.x >=7.5f)
	     transform.position = new Vector3(7.5f, transform.position.y, transform.position.z);
   }
}

All Credit goes to Jason “BuZZ” Busby

At 3D Buzz, Inc.

6 years later and this still worked for me. I'm using this bit of code for a Star Fox like recreate (for my own edification and to possibly adapt it using the Tobii Eye X controller so my son can use it). So I just adjusted the code to fit my needs as the Y and X are my screen's up/down and side/side respectfully. Playing with the values, I was able to make it work.

You could add colliders/triggers to the edges of the screen and make the player character stop, once he enters it.

It depends highly on what the rules are for your game. Easiest way is to position the camera after the player:

Camera.main.transform.position = Vector3.Lerp(Camera.main.transform.position, player.transform.position+Vector3(offsetX, offsetY, offsetZ), Time.deltaTime*Speed);

If you on the other hand want the camera to scroll and the player has to run to keep up, then you can either control the player motion by script, child the player to the camera when it gets to close to border or push the player with a collider at the camera frustrum.