How to Raycast from object to Orthographic camera
I am building an isometric game and I want to be able to make the walls transparent if the character is behind them. So I have done some research and I think casting a ray from the player to the camera and getting all the hits objects then altering their rendering ( as in this post http://docs.unity3d.com/ScriptReference/Physics.RaycastAll.html ). My problem is that on the scene window the orthographic camera appears under the scene even though the view from the camera is correct, the camera object appears under. Drawing a debug line shows it pointing under the scene when in play mode.
So i tried to reverse by taking off the player position it by taking the camera position, Camera.main.transforn.position - transform.position but that just moved it the didn't work and then I tried to inverse it using "-" but again it didn't help. I also have the issue that when rotating the camera around the world that doesn't effect the ray cast either.
This bit of a script rotates the camera (based on the leantouch asset) public static void RotateRTSCamera(Transform transform, float deltaRotation, float speed, Camera camera = null) {
if (transform != null && deltaRotation != 0.0f) {
transform.Rotate (Vector3.up * deltaRotation * speed, Space.World);
}
}
Any help would be appreciated.
Thanks
Nick
Answer by Owen-Reynolds · Jul 19, 2015 at 08:40 PM
Use Vector3.up
for the direction back to an orthoCam (if the camera is aimed down. Otherwise whatever direction is opposite the camera facing.)
Orthographic cameras don't draw things as seen from the exact position of the camera. A (downward-facing) ortho camera "magically" draws things straight down from the camera plane. So, a ray back to the camera is straight up.
Answer by anandmu · Oct 31, 2018 at 08:06 AM
private Camera cam;
private int maxDepth=20;
// Use this for initialization
void Start () {
cam = Camera.main;
}
// Update is called once per frame
void Update () {
if(Input.GetMouseButtonUp(0)) {
RaycastHit hit;
Vector3 camPosition = cam.transform.localPosition;
Vector3 mousez = cam.WorldToScreenPoint(new Vector3(0, 0,Input.mousePosition.z));
Vector3 origin = cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, mousez.z));
//For debug only
Vector3 direction = new Vector3(0, 0, camPosition.z);
Physics.Raycast(origin, direction, out hit, maxDepth);
Debug.DrawRay(origin, direction, Color.green, 15f);
var hit2D =Physics2D.Raycast(new Vector2(origin.x, origin.y), Vector2.up);
if(hit2D.collider) {
Debug.Log(hit2D.collider.gameObject.name);
} else {
Debug.Log("Null Hit");
}
}
}