- Home /
 
Ray Casting in 2D
I have been implementing a tutorial I found on youtube. Its a simple 2D game and allows you to move a sprite around the screen as follows:
     Vector2 movementVector = new Vector2 (Input.GetAxisRaw ("Horizontal"), Input.GetAxisRaw ("Vertical"));
     if (movementVector != Vector2.zero)
     {
         _anim.SetFloat("inputX", movementVector.x);
         _anim.SetFloat("inputY", movementVector.y);
     }
 
               Now I'm trying to introduce ray casting, and I think my Z index is causing me problems. I don't rotate on z axis at any point, so when I try to ray cast it points "up" (away from the screen in the 3d view).
How do I make it point forward (in the direction the sprite is facing) on a 2D plain? I get the impression this gets asked a lot but I'm having trouble implementing a fix.
I'm using the unity docs but I've hit a road block. This is the sort of code I'm aiming for:
     Physics2D.Raycast(transform.position, transform.forward, 10f);
     Vector3 forward = transform.TransformDirection(Vector3.forward) * 10;
     Debug.DrawRay(transform.position, forward, Color.green);
 
               Here's the tutorial I'm using for full reference: https://www.youtube.com/watch?v=XZDjkQ8wEd0
Check with this video.
Answer by Hellium · Jul 21, 2015 at 08:42 PM
Since you are in 2D you want the right vector instead of the forward vector. 
Converted to answer since this is true. For side-scrolling, use (-)transform.right. For top-down, use (-)transform.up. Transform.forward is positive z, so it goes into the background.
Your answer
 
             Follow this Question
Related Questions
How can I raycast the direction my 2D character is facing? 1 Answer
Layer Mask on raycast2d not working? 1 Answer
Raycast for a 2D objects 0 Answers
2D sidescroller shooting 1 Answer
Finding any objects below or above object at ANY POINT? 1 Answer