- Home /
Answer by SFoxx28 · Nov 21, 2017 at 07:01 PM
transform.position = new Vector3(Mathf.Clamp(transform.position.x, -10f, 10f), 0, 0);
You can try this in your code as well. I think using the Mathf.Clamp function will work better.
Answer by EmreB05 · Nov 21, 2017 at 06:52 PM
if(transform.position.x > 10)
transform.position = new Vector3(10, transform.position.y, transform.position.z);
if (transform.position.x <-10)
transform.position = new Vector3(-10, transform.position.y, transform.position.z);
That's one of the ways you can use. Put them in Update or FixedUpdate methods.
Basically what I've done is; I created 2 if statements which check for the position of "x". First statement checks that if X is greater than 10. If it is greater than 10, sets the position back to 10 so the object which the script is assigned to cant move out of our restrictions. Then I've done the same thing for -10. If the x of the object is less than -10 it will be set back to -10. 2 simple if statements should solve your solution.
Have a nice and fun coding experience ^^
Your answer
Follow this Question
Related Questions
Limiting Game Object position by rect 1 Answer
Position Limit 2 Answers
Using Mathf.Clamp To Limit Camera Movement 0 Answers