How can I make my Raycast ignore my player, but have other player's Raycasts be able to hit it?
So I'm fiddling around with Raycasting in a third-person shooter project and currently, I have a Raycast for my camera collision detection, and I also have another one directed out of the center of my camera for my shooting function. My problem is that if the camera gets too close to the player, I can end up shooting myself. Placing the player in the IgnoreRaycast layer solves the problem, but if I ever want to implement a multiplayer function, won't other player's Raycasts be ignored by my player? I'm not sure if I'm thinking about this correctly, but what do you think is my workaround for this?
Answer by DCordoba · Jan 12, 2016 at 06:39 AM
I see two ways to do this
first (hard an order) create a layer (for example "EnemyLayer"), go to layers ->EditLayers
so put all the enemies on this layer then set the Physics.Raycast to just hit this layer, to do this you have to set a layer mask, a layer mask is like a bitmap, have 0 in the number of layers to you not want hit, an 1 in the layers you want to collide so if you just want to collide a "EnemyLayer" layer you just have to set as one the number of this layer have 7 default layers, so if its the first layer you do it will be the number 8, to just take with a racast only for the layer 8
// Bit shift the index of the layer (8) to get a bit mask
int layerMask = 1 << 8;
RaycastHit hit;
//supposed the camera of the player is the main camera
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
//this is the max distance to you can shoot
float maxDistance = 2475.0f;
// the ray will just hit gameObjects from the EnemyLayer
if (Physics.Raycast (ray, out hit, maxDistance, layerMask) ){
print("I pointing one!");
}
read more about Layers in http://docs.unity3d.com/Manual/Layers.html
the other (easy and dirty) is "move" the ray a bit foward from the camera, out of player body, this allows you to ignore the enemy accidentally cross between player and camera, to do this, change the variable origin of the ray, jchange the origin to a other point on the forward (take the pont in the ray with GetPoint ()) here an example
RaycastHit hit;
//supposed the camera of the player is the main camera
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
//change the origin of the ray, hope the dude is more closest than 3!
ray.origin = ray.GetPoint (3.0f);
//this is the max distance to you can shoot (-3)
float maxDistance = 2474.0f;
// the ray will just hit gameObjects from the EnemyLayer
if (Physics.Raycast (ray, out hit, maxDistance) ){
print("I pointing one!");
}
read more about ray in http://docs.unity3d.com/ScriptReference/Ray.html
thats all, hope this helps!
Your answer
Follow this Question
Related Questions
Cant Kill enemy with Raycast C# (SOLVED) 1 Answer
Any way to increase raycast range? 0 Answers
Make a Raycast pass through a layer? 0 Answers