I have a script that will raycast and take the transform.position of the collider hit and another raycast on a second collider hit and take their transform position to create a rect. The original code without worldtoscreenpoint works 100% fine, but as soon as I add that in, the number keeps increasing to ridiculous, near infinite numbers. I tried to figure it out but it just doesnt make any sense how one of the worldtoscreenpoint works properly and how the other worldtoscreenpoint doesn’t. How do I fix this?
using UnityEngine;
using System.Collections;
public class TopCamView : MonoBehaviour {
public Texture2D randomtexture = null;
public Camera cameracomp;
public static Rect selectionBox = new Rect(0,0,0,0);
public Vector3 originalPos = -Vector3.one;
public Vector3 currentPos = -Vector3.one;
// Use this for initialization
void Start () {
cameracomp = GetComponent<Camera>();
//cameracomp.orthographicSize =
}
// Update is called once per frame
void Update () {
CheckCamera();
}
void CheckCamera() {
if (Input.GetMouseButtonDown(1))
{
RaycastHit hitorg = new RaycastHit();
Ray rayorg = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(rayorg,out hitorg))
{
originalPos = hitorg.collider.transform.position;
Debug.Log("raycast original: " + originalPos);
}
}
else if (Input.GetMouseButtonUp(1))
{
if (selectionBox.width < 0) {
selectionBox.x += selectionBox.width;
selectionBox.width = -selectionBox.width;
}
if (selectionBox.height < 0) {
selectionBox.y += selectionBox.width;
selectionBox.height = -selectionBox.height;
}
/*originalPos = -Vector3.one;*/
}
if (Input.GetMouseButton(1)) {
RaycastHit hitcur = new RaycastHit();
Ray raycur = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(raycur,out hitcur))
{
currentPos = hitcur.collider.transform.position;
}
originalPos = Camera.main.WorldToScreenPoint(originalPos); //variable that screws up
currentPos = Camera.main.WorldToScreenPoint(currentPos); //this one for some reason is fine
Debug.Log(originalPos);
//selectionBox = new Rect(originalPos.x, InvertMouseY (originalPos.y), currentPos.x - originalPos.x, InvertMouseY(currentPos.y) - InvertMouseY(originalPos.y));
selectionBox = new Rect(originalPos.x, InvertMouseY(originalPos.y), currentPos.x - originalPos.x, InvertMouseY(currentPos.y) - InvertMouseY(originalPos.y));
}
}
public static float InvertMouseY(float y) {
return Screen.height - y;
}
void OnGUI()
{
if (originalPos != -Vector3.one)
{
GUI.color = new Color(1,1,1,.5f);
GUI.DrawTexture(selectionBox,randomtexture);
}
}
}