Question by
andrewu331 · Mar 18, 2020 at 06:34 PM ·
raycasttransform
Problem with using raycast to stop camera from going through wall
I have a script that I modified from this script from here -http://wiki.unity3d.com/index.php/MouseCameraControl. I added a raycast to the scroll function so that it can detect when it gets close to a wall. It works okay and it stops the camera from going through the wall but if I keep scrolling it will eventually break and the camera goes through the wall. I could use some help in either figuring out a better way or modifying what I have to be less buggy. Here is the code that uses the raycast
if (scroll.isActivated())
{
position = transform.position;
float translateZ = Input.GetAxis(scrollAxisName) * scroll.sensitivity;
transform.Translate(0, 0, translateZ);
if (position.y < 12284)
{
position.y = 12284;
transform.position = position;
}
Ray ray = GetComponent<Camera>().ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
// the object identified by hit.transform was clicked
// do whatever you want
Debug.LogWarning(hit.distance);
if ((hit.distance < 1.5) && (hit.distance > 1))
{
Debug.LogWarning("past 1");
originalRayPos = transform.position;
originalRayRot = transform.rotation;
}
if(hit.distance < 1)
{
transform.position = originalRayPos;
transform.rotation = originalRayRot;
}
}
}
Comment