- Home /
Limit player transform on x axis
I m making a game on android device , i use accelerometer and i want my player to transform only on x axis.
this is the code i write:
void Update() { float amtToMove = -Input.acceleration.y PlayerSpeed Time.deltaTime; Vector3 pos = transform.position; pos.x = Mathf.Clamp(pos.x + amtToMove, -0.19f, 2.3f); transform.position = pos; } I use Mathf.Clamp and this work very well but i don't want to put a fixed value. i want my player to be limited on screen width. Can any one help me PS: Sorry for my bad english and thanks in advance.
Answer by whydoidoit · Sep 18, 2012 at 08:48 AM
Sure you just need to convert the screen coordinates into world coordinates at the position of the player.
So you have Screen.width which will tell you your horizontal width, then:
minX = Camera.main.ScreenToWorldPoint(new Vector3(0,0,player.transform.position.z - Camera.main.transform.position.z)).x;
maxX = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, 0, player.transform.position.z - Camera.main.transform.position.z)).x;
So using ScreenToWorldPoint will convert the screen coordinate, based on the camera, to the world at z units from the camera.
Your answer

Follow this Question
Related Questions
limiting rotation to solid angle 5 Answers
Field of view, using raycasting 5 Answers
How to limit bullets in screen like old NES game 4 Answers
How do you limit velocity on a rigid body in only one direction? 1 Answer
Having a fuel limit 1 Answer