Question by
PickyBerry · Jul 19, 2020 at 11:49 AM ·
cameracamera rotateraycasthitlinecast
Linecast not working properly for camera
I was making a 3d camera rotation+zoom script plus the autozoom if the camera hits something so that it doesn't go through objects and terrain. Everything worked properly except the autozoom which I did with linecast. Here is a part of the script:
void Update()
{
x += Input.GetAxis("Mouse X") * xSpeed * distance * 0.02f;
y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
y = ClampAngle(y, yMinLimit, yMaxLimit);
Quaternion rotation = Quaternion.Euler(y, x, 0);
distance = Mathf.Clamp(distance - Input.GetAxis("Mouse ScrollWheel") * 5, distanceMin, distanceMax);
if (Physics.Linecast(Player.transform.position, MainCamera.transform.position, out hit))
{
distance = hit.distance;
Debug.Log("Hit!");
}
Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
Vector3 position = rotation * negDistance + Player.transform.position;
MainCamera.transform.rotation = rotation;
MainCamera.transform.position = position;
}
`` For some reason the "if" is never true whatever I do and whatever I place between the camera and the player. And the camera still always goes through. However if I Debug.DrawLine between the camera and the player, the ray clearly goes through these objects. The player has rigidbody and box collider applied to it. How do I fix this? Many thanks!
Comment