- Home /
How can I flip the direction of a Physics2D raycast?
In my player controller script, I have various checks that determine the state of a player (E.g. isGrounded, isTouchingWall, etc.)
For the ones like isGrounded and isTouchingCeiling, there is no need to invert them since the player can only flip on the Y axis, however, I'm having trouble flipping the isTouchingWall raycast.
The empty gameObject that the raycast takes as the start point flips as usual since it's a child of the player, but the direction of the raycast (transform.right) does not, so even if the player is looking left that raycast goes into the player and to the right.
A solution I thought worked was doing the following:
if(isFacingRight)
{
isTouchingWall = Physics2D.Raycast(wallCheck.position, transform.right, wallCheckDistance, whatIsGround);
} else {
isTouchingWall = Physics2D.Raycast(wallCheck.position, -transform.right, wallCheckDistance, whatIsGround);
}
However, that seemed to unable the entire raycast and now only returns a false value even if I'm next to a wall. This code is inside a method inside the FixedUpdate(); method, if that matters.
Any answers are greatly appreciated, and thanks in advance :)
It's kinda hard to understand what's happening here, can you tell me how "isFacingRight" changes and what exactly does "flipping" do?
Answer by Koishi-_- · Sep 14, 2021 at 04:41 PM
Hey so, after fiddling around with this problem and doing some research I came up with a rather simple solution to this problem, so I'll try my best to explain it:
private void CheckEnvironment()
{
linecastDistance = new Vector3(0.1f, 0, 0);
Vector2 wallCheckEndPos = wallCheck.position + linecastDistance * facingDirection;
RaycastHit2D wallHit = Physics2D.Linecast(wallCheck.position, wallCheckEndPos, whatIsGround);
if(wallHit.collider != null)
{
isTouchingWall = true;
} else {
isTouchingWall = false;
}
}
In a nutshell, Raycast directions cannot be changed during gameplay, at least as far as I know. As all I wanted to do was a simple boolean trigger, a linecast was more than enough. Linecasts behave in a similar way to raycasts, except they work by specifying a start and end point rather than a start, direction and length.
All I had to do then, was multiply the end point of the linecast by my facing direction (which was 1 or -1) and that would flip the linecast with the player.
It's also worth noting the fact that my CheckEnvironment(); method is called by the FixedUpdate(); method, make sure yours is too.
Hope it helped!
Answer by EliasMiettinen · Sep 14, 2021 at 11:51 AM
Try using this:
transform.left
instead of this:
-transform.right
at line 5
There is no difference at all bro, this isn't what the problem is.
Ok. Have you tried to get your child object transform. Like this:
childObj.transform.right