- Home /
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.Normalize();
dir *= Time.deltaTime;
transform.Translate(dir * speed);
Answer by coolbird22 · May 11, 2014 at 07:57 AM
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);
Answer by Batzuga · May 10, 2014 at 03:57 PM
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.
Using absolute values is not really recommended since I'm planning on making something for multiple devices. I need something that utilizes Screen.width and Screen.height. Something like this
Vector3 screenPos = Camera.main.WorldToScreenPoint(transform.position);
if(screenPos.x < Screen.width)
transform.position.x = screenPos;
else if(screenPos.x > Screen.width)
transform.position.x = Screen.width;
but this doesn't work