Question by
tatecreative · Dec 06, 2020 at 01:32 AM ·
cameratransformcollidersworldtoscreenpointviewporttoworldpoint
Limit game object to camera view
I want to create a scene where objects are restricted to what's currently shown in the camera. 3D objects can be moved, scaled, etc, but they can't be outside of the camera bounds at all. Here's a quick mockup of the idea.
I've tried the following but it doesn't really work the way I want it to:
// Return random position float for movement
public void setRandomPos()
{
Vector3 pos = Camera.main.WorldToViewportPoint(thebox.transform.position);
float ppx = Random.Range(0.1f, 0.9f);
pos.x = Mathf.Clamp(ppx, 0.1f, 0.9f);
// Convert the values first, then replace them with new vals again before animating
Vector3 asdf = Camera.main.ViewportToWorldPoint(pos);
asdf.y = Random.Range(-0.5f, 2.0f);
asdf.z = Random.Range(4.0f, 10.0f);
thebox.transform.DOMove(asdf, tweentime);
}
Note that the Y value is replaced after the ViewportToWorldPoint b/c I was getting really funny behavior with this:
float ppx = Random.Range(0.1f, 0.9f);
pos.x = Mathf.Clamp01(ppx);
float ppy = Random.Range(0.1f, 0.9f);
pos.y = Mathf.Clamp01(ppy);
Vector3 asdf = Camera.main.ViewportToWorldPoint(pos);
bounds.jpg
(28.0 kB)
Comment
Your answer
Follow this Question
Related Questions
Focus Camera on object to use GUI Interface. 0 Answers
Maintaining Camera Rotation between modes 0 Answers
Google Cardboard & Daydream Camera Tracking Bug 0 Answers
How do you stop SteamVR Player from colliding with a car? 0 Answers
Creating a camera controller for isometric view - Positioning the camera 1 Answer