For some reason Debug.DrawLine won’t stay with my camera’s bottom-left corner (origin.x), and instead moves slightly left or slightly right when the camera shifts. I assume the issue has something to do with converting to ScreenToWorldPoint but I’m not smart enough to figure out what’s going on on my own.
Here’s my code (the line gets drawn from an enemy’s collider2D min.x to the Camera’s origin.x, which is suppose to be the Camera’s “min.x” in theory):
Vector3 origin = Camera.main.ScreenToWorldPoint(Camera.main.transform.position);
Debug.DrawLine(new Vector3(transform.collider2D.bounds.min.x, transform.collider2D.bounds.min.y), new Vector3(origin.x, origin.y));
if (transform.collider2D.bounds.min.x < origin.x)
Debug.Log(transform.collider2D.bounds.min.x + ", " + origin.x);
[code ][/code ] tags rather than list (sticky at the top of the scripting forum it’s a little hidden away in the edit function bar, or just type them manually )
You were correct in your assumption! The first line is the problem. You’re trying to convert the cameras transform position from screen space to world space. It’s already in world space, so the conversion is unnecessary.
Also, I’m assuming you’re using a version of unity earlier than 5, because the collider2D quick-reference variable is gone.
public class Test : MonoBehaviour {
Collider2D coll;
void Start() {
coll = GetComponent<Collider2D> ();
}
void Update() {
Bounds bounds = coll.bounds;
Vector3 origin = Camera.main.transform.position;
//no need to create new Vector3's from scratch. They already are Vector3s!
Debug.DrawLine (bounds.min, origin);
if (bounds.min.x < origin.x)
Debug.Log(bounds.min.x + ", " + origin.x);
}
}
Thanks Ben, that gets the line to the center of the camera, but unfortunately I can’t figure out how to get the line (what math is needed) to attach to the corner bounds of the viewport (lower-left corner, upper-right-corner, etc.). I was thinking about adding a Collider2D to the camera (as a Trigger), but I keep thinking there’s a better way to handle this.
I thought maybe subtracting the orthographicSize might work since that’s half the camera, but no dice.
Debug.DrawLine(transform.collider2D.bounds.min, new Vector3(origin.x - Camera.main.orthographicSize, origin.y), Color.green);
(I was writing this as you posted your reply)
THIS is where you would use ScreenToWorldPoint, or ViewportToWorldPoint.
Bottom left would be 0,0.
For the viewport, topRight would be 1,1.
For ScreenPoint, topRight would be ScreenWidth,ScreenHeight.
Since viewport is slightly less code, let’s use that. Handily enough, we can use either a Vector2 or a Vector3 for this purpose (because implicit conversions exist), and there are already shorthand methods for each: