- Home /
How to block a raycast? (Java)
Hi, Im trying to implement a shield system for my project, the idea is that if the shield is being held up then it'll block any incoming attacks.
Now, when the enemy is in range it'll use a Raycast function to see if the player is in range and send a notification to damage him, here's the code that makes that work:
var hit : RaycastHit;
if (Physics.Raycast (transform.position, transform.TransformDirection(Vector3.forward), hit))
{
Distance = hit.distance;
// Checks if the raycasted object is in the range of attack
if (Distance < AttackRange)
{
// Calls the function "Apply Damage" on the object that's being hit
hit.transform.SendMessage("ApplyDammage", attackDMG, SendMessageOptions.DontRequireReceiver);
}
}
What Im wondering is if there's a way to effectively block this raycast if an object such as the shield is in the way. I tried giving the shield a collision box to see if that would stop the damage notification from reaching the player but that didnt work.
Is there any way to make that work? I know that I can probably make a condition to stop the player from receiving damage when the shield is up but I still want him to get damaged if he's hit on the back.
Answer by robertbu · Nov 28, 2013 at 08:29 PM
There are a number of ways of solving your problem. Which one to use will depend on your game:
1) Turn off the collider on your player when the shields are up.
2) Change the name or the tag on the player when the shields go up and check the name or tag in your raycast:
if (hit.collider.tag == "Player" && Distance < AttachRange) {
3) Use a child game object with a collider larger than your player. Enable the collider when the shields go up. Check the name or tag as in #3.
4) Use GetComponent() to get the player script and check the shields variable directly:
var player : PlayerScript = hit.collider.GetComponent(PlayerScript);
if (player != null && !player.shieldsUp && Distance < AttachRange) {
Thanks for the reply, I think any of those methods could work, but the problem is that they will block attacks co$$anonymous$$g from all directions, as I explained on my first comment I still want enemies to be able to attack the player from the back even if the shield is up.
I was hoping that if I add a collider to the shield then it would block the raycast co$$anonymous$$g from the enemy, but apparently it goes right through it and still hits the player.
Is there no way to block raycast co$$anonymous$$g from one direction only? From your examples it seems like it's all or nothing.
Actually, I've been experimenting and this does work, any object with a collider WILL block a raycast, it's just that the shield was a child of my character so the raycast was hitting him first. Im going to try to make it so when you press the shield button it enables an invisible collider in front of the player, as long as it is above the player's hierarchy this should work.
Thanks for the help though :)