Keep object constrained to z space origin
I have a 3d object moving around screen controlled by gyroscope. I currently have its movement constrained to the boundaries of the camera viewport. I also have it so that tilting the mobile device forward moves it on Y axis as apposed to forward in Z space, since the camera won't be moving or following object and I don't want it moving forward or backward in Z space, only U,D,L,R. I want the object to remain at its starting point when game starts and constrained it in Z space. But with what I have right now the object pops in right in front of the camera and stays locked to the camera (the object fills the screen) when I press play. The code I have is as follows:
void Update()
{
transform.Translate (Input.acceleration.x, Input.acceleration.y, 0);
Vector3 boundaryVector = transform.position;
Vector3 pos = Camera.main.WorldToViewportPoint (transform.position);
pos.x = Mathf.Clamp01(pos.x);
pos.y = Mathf.Clamp01(pos.y);
pos.z = Mathf.Clamp01(pos.z);
transform.position = Camera.main.ViewportToWorldPoint(pos);
}
}
I know that the line pos.z = Mathf.Clamp01(pos.z);
is the culprit since this doesn't happen when I remove that line. But by removing that line the character moves freely in Z space which is no no. How do I keep it constrained to certain point in Z space, preferably its origin?
Answer by jigwiz · Mar 22, 2017 at 04:56 AM
I was able to get the object constrained by replacing the problem line of code accordingly:
Vector3 pos = Camera.main.WorldToViewportPoint (transform.position);
pos.x = Mathf.Clamp01(pos.x);
pos.y = Mathf.Clamp01(pos.y);
pos.z = Mathf.Clamp (transform.position.z, 50, 50);
Using this I can specify the z space area to stay constrained to. It took some fidgeting with the numbers to get it to a spot I like. Ideally I would have liked to code it to start from its origin point but this works for now.
Your answer
![](https://koobas.hobune.stream/wayback/20220612113655im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Change sensitivity of Z rotation on game object 0 Answers
How do I control the rotation of object. 1 Answer
How can I move an object between two positions, while it is on a rotating platform? 0 Answers
How do I move a 3d object from point a to b with a random timer? 1 Answer
UI buttons activate movement functions for one time only 1 Answer