void Update(){
float accel = Input.acceleration.x;
transform.Translate(accel, 0, 0);
}
Above is my current code for accelerator control in my game. I want to be able to tilt my phone left and right and the character will move left and right. The code works fine, but the character moves outside the screen. I tried Mathf.Clamp on the accel value and also tried clamping the transform.position but neither work and just seem to change the speed of the accelerometer control.
I need a way to dynamically limit the characters movement within any screen size.
If I understand the question correctly you want to keep an object clamped within the visible area. To achieve this you could use the Viewport.
Vector3 pos = this.transform.position;
Vector3 viewportPos = Camera.main.WorldToViewportPoint(pos);
if (viewportPos.x < 0f) Camera.main.ViewportToWorldPoint(new Vector3(0f, pos.y, pos.z));
else if (viewportPos.x > 1f) Camera.main.ViewportToWorldPoint(new Vector3(1f, pos.y, pos.z));