- Home /
RayCast2D problems on collision detection
Hello There, I was tryng, for learning purposes, to make a frogger-like game. For collision, instead of Rigidbodies i wanted to used Raycast2D. However things doenst react as expected:
as you can see from the image, i'm using Debug.DrawRay to draw the actual rays ( for now are both up and bottom ray). In the scene view, the box collider is just a boundary box used to negate the player going outside the "map". However, the collision with raycast is only detected in this situation :
can you tell me why please? This is driving me crazy.. Thanks
I'm using this code http://pastebin.com/itnKXhzU
Answer by hulahoolgames · Aug 29, 2015 at 06:38 PM
Is the raycast colliding with the black cube object? I would recommend to put a breakpoint in your collision code to see what collider the Raycast is returning is both cases.
Answer by tauqeerahmed · Aug 29, 2015 at 08:28 PM
Do you want to detect the collision between the car and the blackbox using raycast ??
Answer by Suddoha · Aug 29, 2015 at 09:56 PM
There is a mistake in your code and some other things that can or should be changed.
First of all, you set the booleans which indicate that a collision has occured always to false, whether or not the raycasts hit an object tagged 'Bounds'.
The methods return, update continues and you allow to move as long as the booleans are false, due to the inversion ( !collidingUp). Remember, you always set both to false in any case, thus this condition will always be true, because !false == true. The result: you can always move. You have to reset them at the beginning of the methods, not at the end, so that they will generally be false, as long as no raycast hit the bounds.
Moreover, you should specify a length for the raycasts, otherwise they will use Math.Infinity if i'm not mistaken, which means you'll always detect your bounds, which in turn means, you'll always 'collide'. You have to determine the length yourself, as i don't know the exact distances in your game.
And a last side not so far: You could also generalize the collision method so that you do not need one for every direction, but that's another thing. For example, you could have parameters for the direction to cast (Vector2 direction), a reference to the boolean you want to alter within the method (ref bool someName) and a length (float length).
Also note, that you may need to adjust the direction parameter for the Debug.DrawRay method, as the ray will be drawn from startPosition to startPosition + direction, at least that's what the description says.
Your answer
Follow this Question
Related Questions
Raycast exit point of collider 0 Answers
How do i get local Hit position of Raycast on a collider 1 Answer
Another Raycast Issue. 0 Answers
Raycast Not Drawing In Target Direction 0 Answers
Help with Raycast C# 0 Answers