- Home /
Colliders won't work
In my game I have a few gameobjects moving in one direction. I want them to collide with a box collider that I have attached to my camera, so it scales with screen size. The cups just go right through the collider. Here is my script:
public float colDepth = 30f; public float zPosition = 0f; private Vector2 screenSize;
private Transform rightCollider;
private Vector3 cameraPos;
// Use this for initialization
void Start () {
//Generate our empty objects
rightCollider = new GameObject().transform;
//Name our objects
rightCollider.name = "RightCollider";
//Add the colliders
rightCollider.gameObject.AddComponent<BoxCollider>();
//Make them the child of whatever object this script is on, preferably on the Camera so the objects move with the camera without extra scripting
rightCollider.parent = transform;
//Generate world space point information for position and scale calculations
cameraPos = Camera.main.transform.position;
screenSize.x = Vector2.Distance (Camera.main.ScreenToWorldPoint(new Vector2(0,0)),Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, 0))) * 0.5f;
screenSize.y = Vector2.Distance (Camera.main.ScreenToWorldPoint(new Vector2(0,0)),Camera.main.ScreenToWorldPoint(new Vector2(0, Screen.height))) * 0.5f;
//Change our scale and positions to match the edges of the screen...
rightCollider.localScale = new Vector3(colDepth, screenSize.y * 2, colDepth);
rightCollider.position = new Vector3(cameraPos.x + screenSize.x + (rightCollider.localScale.x * 0.5f), cameraPos.y, zPosition);
}
also, if someone could tell me how to just attach a gameobject to the edge of the camera, or the edge of what it sees, but scales with the camera, it would be great.
Your answer
![](https://koobas.hobune.stream/wayback/20220612131723im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Very complicated collider problems 0 Answers
camera collision 1 Answer
Detect if a non-trigger collider is inside another collider 1 Answer
How to stop camera from falling down when a collider is added to it 2 Answers
Resizing an object on collision in unity,Resizing an Object on Collision in unity 1 Answer