- Home /
Raycast always true after first hit
I wrote a script that checks if there's a wall in front of the player. It detects the wall and player stops where he needs to. However, when player turns around after the raycast hit and faces away from the wall, inspector still says that wallRay and wallInFront are true and they stay that way, so player is stuck and cannot move. I made a gizmo that shows the ray and it looks like it should work (it points where player is looking) except that the ray's length doesn't update anymore. Do I have to somehow manually reset the raycast after the hit? Also, player has been set to "Ignore raycast"-layer so the ray isn't hitting himself either.
Here is the code:
bool CanMoveInTargetDirection(Vector3 targetPos) {
Vector3 direction = (new Vector3(targetPos.x, transform.position.y, targetPos.z) - transform.position).normalized;
wallRayStart = new Vector3(transform.position.x, transform.position.y + 2f, transform.position.z) + direction * 1.1f; // Ray starts from where the player is looking
RaycastHit hitWall = new RaycastHit();
wallRay = Physics.Raycast(wallRayStart, direction, out hitWall);
if (wallRay) {
distanceToWall = Vector3.Distance(hitWall.point, transform.position);
wallInFront = distanceToWall < 10.0f ? true : false;
}
return !wallInFront;
}
I've tried replacing the "out hitWall" with 10.0f, removing the if statement and replacing return value with "return !wallRay;" but it behaves identically.
Answer by robertbu · Nov 30, 2013 at 11:15 PM
wallInFront appears to be a class variable. This means it preserves it value across function calls to CanMoveInTargetdirection(). But you only set it if 'wallRay' is true. So a quick fix would be to:
if (wallRay) {
distanceToWall = Vector3.Distance(hitWall.point, transform.position);
wallInFront = distanceToWall < 10.0f ? true : false;
}
else {
wallInFront = false;
}
Here is a bit of untested simplification of your code:
bool Can$$anonymous$$oveInTargetDirection(Vector3 targetPos) {
Vector3 direction = targetPos - transform.position;
wallRayStart = transform.position + Vector3.up * 2.0f;
if (Physics.Raycast(wallRayStart, direction, out hitWall)) {
distanceToWall = Vector3.Distance(hitWall.point, transform.position);
wallInFront = distanceToWall < 8.9f;
wallRay = true;
}
else {
wallRay = false;
}
return !wallRay;
}
If you are not using wallRay and distanceToWall outside of this function, it can be simplified further.
Your answer
Follow this Question
Related Questions
Raycasthit.point - same place every time! (Unity 3.5) 1 Answer
raycast question 1 Answer
Using RayCasting to check for floor and ceiling? 0 Answers
Instantiated bullet hole has wrong rotation 1 Answer
Improve ray detection? 0 Answers