- Home /
Physics2D Raycast not detecting wall colliders
I've been trying to make an enemy that patrols back and forth, turning around when it either hits a wall or runs out of ground to walk on. I'm using a raycast pointed down to detect the ground, and a forward pointed raycast to detect walls. This should be super simple, but for some reason only the ground detection is working. As you can see in the image, the enemy is touching both ground and a wall, but is only detecting the ground.
https://imgur.com/a/yJ9S7i8 (Here is a link to the image, for some reason Unity Answers won't let me attach a jpeg at the moment)
Here is the code that handles the raycasts:
groundDetected = Physics2D.Raycast(groundCheck.position, Vector2.down, groundCheckDistance, whatIsGround);
wallDetected = Physics.Raycast(wallCheck.position, transform.right, wallCheckDistance, whatIsGround);
if (!groundDetected || wallDetected)
{
Flip();
} else
{
movement.Set(movementSpeed * facingDirection, aliveRb.velocity.y);
aliveRb.velocity = movement;
}
Answer by Vylax · Jun 22, 2020 at 09:35 AM
I think you're missing a 2D line 2: replace
wallDetected = Physics.Raycast(wallCheck.position, transform.right, wallCheckDistance, whatIsGround);
with
wallDetected = Physics2D.Raycast(wallCheck.position, transform.right, wallCheckDistance, whatIsGround);
just like you did on the first line
Wow, of course it was something so simple. Thanks! I guess all it takes sometimes is a second pair of eyes to catch those dumb mistakes.
Your answer
Follow this Question
Related Questions
Bitmask/LayerMask used in raycast not working 2 Answers
2D Raycasting to check if grounded not working 1 Answer
Small overlap in ColliderDistance2D after moving collider to RaycastHit2D.centroid 0 Answers
Raycasting not behaving as expected? 2 Answers
Unity Physics2D.Raycast always returns “the invoker” as hit 2 Answers