So my team and I are making a first-person 3D game on Unity (who knew :p), and we are having a bit of an issue.
You see, we are trying to make our character’s cross hair collide with enemies and other objects within the game. The cross hair is done as a 2D texture. The crosshair turns red if its in range of an enemy, green if it is an interactive object (buttons, health packs, etc).
We have tried various ways, even adding a 3d box collider to the character that if he detects colision then the color of the crosshair changes (didn’t work), we also tried getting distance formula (didn’t work). Our last chance is to attempt a 2D on 3D collision but we just don’t know how to even get started.
Can someone out there show us a way to solve this?
You actually want to use Raycasting for this problem. Below is an example of how you could implement this though depending on how you identify an interactive object separate from an enemy or a regular object will change the conditions.
Keep in mind, I did this with the assumption that the crosshair is a child object attached to your player since that’s what you implied. If that’s the case, then this script would have to be attached to the crosshair object. If it’s a GUI element, then you would handle it slightly different but the form remains the same.
RaycastHit hit;
Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit);
if(hit) {
if(hit.transform.tag == "Enemy" && hit.distance <= 50) {
renderer.material.color = Color.red;
} else if (hit.transform.tag == "Interactive" && hit.distance <= 20) {
renderer.material.color = Color.green;
} else {
renderer.material.color = Color.white;
}
}
The way you normally do this is by using
screenpointtoray
Basically you convert a screen position (from the mouse cursor) into a ray that you use to verify collisions, and act consequently in the scene.
Otherwise, you can do the ‘inverse’ and trigger a “mouse cursor” (a plane gameobject always following the camera in a billboard, with a texture) change through the
OnMouseOver
function. Note that you need a collider and usually a rigidbody for onmouseover to work.