How do I stop my Player from moving outside the screen bounds while using an accelerometer ?

I found a solution to make it happen using triggers that push the object inside the screen bounds but I don’t wish to use triggers but plain code, that stops it from moving outside the screen. Here is the code I’m using for moving my character:

Vector3 dir = new Vector3 (Input.acceleration.x, Input.acceleration.y, 0.0f);
		if (dir.sqrMagnitude > 1)
		dir *= Time.deltaTime;
		transform.Translate(dir * speed);

Managed to get it to work using the foll code:

	Vector3 minScreenBounds = Camera.main.ScreenToWorldPoint(new Vector3(0, 0, 0));
	Vector3 maxScreenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, 0));

		transform.position = new Vector3(Mathf.Clamp(transform.position.x, minScreenBounds.x + 1, maxScreenBounds.x - 1),Mathf.Clamp(transform.position.y, minScreenBounds.y + 1, maxScreenBounds.y - 1), transform.position.z);

If you don’t want it to move outside the camera view, why don’t you create minimum and maximum positions for the Player.

if(transform.position.x > 4)


transform.position.x = 4;


if(transform.position.x < -4)


transform.position.x = -4;


simple yet efficient. I’ve used this many times.