I have been tasked to create a small Unity project that requires me to change the colour of an object when the camera is directly pointing at it without the use of raycasts/colliders/triggers. I feel like I could definitely do it using raycasts as this is something we have dealt with before but unsure how to do it without them.
have you considered using a vector3 dot product between the forward vector of the camera and the direction to the object to detect when the camera is facing in a similar direction to the direction of the other object (with margin for error)?
for example (I haven’t tested the code, but it gets the main idea across anyway):
Vector3 cameraForwardDir = cameraObject.transform.forward;
Vector3 objectPositionRelativeToCamera = otherObject.transform.position - cameraObject.transform.position;
if (Vector3.Dot(cameraForwardDir, objectPositionRelativeToCamera.normalized)>0.9f) // 0.9 allows for a margin for error
{
//this code is executed when the "cameraObject" is looking at the "otherObject" with some margin for error.
}
What exactly does that mean? Does that mean when the camera is pointing exactly at the object’s pivot? Or when its center does overlap with the collider or mesh of the object? What margin of error is acceptable?
There are several approaches but the result is of course different than a raycast against the actualy shape of the object. One way would be to use InverseTransformPoint with the camera transform so you can get the target objects position in camera space to figure out how far it is away from the center. Camera.WorldToScreenPoint would also be an option.
Why exactly do you want to avoid a raycast? This seems rather arbitrary.