- Home /
 
               Question by 
               tohmjudson · Feb 09, 2014 at 03:22 AM · 
                raycastraycasthit2dcollider 2d  
              
 
              Raycast 2D not working as i hoped
I have changed this code a thousand times...
I want it to hit the collider and change direction. What am I doing wrong?
 using UnityEngine;
 using System.Collections;
 
 
 public class ZeroWaypointAi_2D : MonoBehaviour
 {
     public enum WalkDirection { WalkLeft, WalkRight }
 
     public float speed = 1f;
     private Vector2 moveDirection;
     private WalkDirection walkDir;
 
     protected void Start()
     {
         int rand = Random.Range(0, 2);
         if (rand == 0)
         {
             walkDir = WalkDirection.WalkLeft;
         }
         else
         {
             walkDir = WalkDirection.WalkRight;
         }
     }
     
 
     private void Update()
     {
         RaycastHit2D hit = Physics2D.Raycast(transform.position,transform.right, 1f);
 
         if (walkDir == WalkDirection.WalkLeft)
         {
             if (hit)
             {
                 walkDir = WalkDirection.WalkRight;
             }
 
             moveDirection.x = -speed * Time.deltaTime;
         }
 
         else if (walkDir == WalkDirection.WalkRight)
         {
             if (hit)
             {
                 walkDir = WalkDirection.WalkLeft;
             }
             moveDirection.x = speed * Time.deltaTime;
         }
         
         // move the AI
         transform.Translate(moveDirection);
     }
     
 }
               Comment
              
 
               
              I'm guessing a bit, but I believe that your problem is that you are not changing the direction the raycast is going when the character is changing direction. That is you want to use 'transform.right' or '-transform.right' depending on the direction the character is moving.
Your answer
 
 
             Follow this Question
Related Questions
Raycast Not Working 3 Answers
Raycasting in a 2D side scrolling shooter 2 Answers
My Raycasts seem to sometimes miss 0 Answers
2d Raycast not work 1 Answer
What is the best way to raycast mutliple rays over a line 1 Answer
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                