Player doesn't move towards object recognized by raycasthit2D eventhough raycast is drawn correctly

Heya,


I’m making a rough pac-man clone game to test some basic coding knowledge I’m learning on a C# Unity course. Normally I can ask the questions concerning the course at the course portal, but since this is a personal venture to test my knowledge, I figured I’d post it here. I’ve looked around to see if I could find an answer to my problem on these pages but haven’t found it, so here goes.

In the image above you see the game board. The squares on each corner or intersection are Intersection game objects. The yellow cube on the right is the player. To move the player around I draw a raycast in the direction the player is pressing. If the raycast hits an object with layermask Intersection, the player should move towards the location of that intersection.


Here’s the code I’m using:


The problem I’m having is that the input and raycasts get through, but the player doesn’t always move, but sometimes it does. In the image above, If I press left, the player goes to intersection 1. Once there, I can press right, or down, and the input will be recognized and the raycast will be drawn, but the player won’t move in those directions. However, if I press left, it does go left again. Same goes for intersection 2, I can only go left. At intersection 3 I can’t go anywhere.


Unity doesn’t fire off any errors or warnings. I’ve been staring at this problem for ages and can’t get it fixed. Hopefully somebody here can help me out on this.


Thank you so much in advance! Cheers!

I’ve found the answer. I should have used && instead of || in my if/else statements! D’oh!

I’m not the greatest of coders but what I would do if I had this issue is play around with certain things such as:

(Input.GetKey(KeyCode.A))

//instead of

(Input.GetKeyDown(KeyCode.A))

//---------------------------------------------------------------------------------

 leftRay = Physics2D.Raycast(transform.position + transform.left * offset, Vector2.left, 20f, intersectionMask);

//Instead of 

 leftRay = Physics2D.Raycast(transform.position - transform.right * offset, Vector2.left, 20f, intersectionMask);

But if you say your raycasts are getting through maybe change the layout of the Move function into something that isn’t all Else Ifs, that could be whats throwing it?