- Home /
RaycastHit2D not getting any information?
Hi again.
I try to make a character movement and control out of raycasting but now I got into a problem.
Its not hitting anything although there is a collider there. ![alt text][1]
![alt text][2]
And this is the script:
using UnityEngine;
using System.Collections;
public class Controller : MonoBehaviour {
public float OnGround = 2.5f;
//Planing to add ((public Rigidbody2D rb2D;))
void Start() {
//Planing to add ((rb2D = GetComponent<Rigidbody2D>();))
}
void FixedUpdate() {
transform.Translate (Vector2.down * 0.1f);
RaycastHit2D hit = Physics2D.Raycast(this.gameObject.transform.position, Vector2.down);
if (hit.distance <= OnGround) {
print ("Stop!");
transform.Translate (Vector2.zero);
}
}
}
As I said it doesn't detect the collider. any ideas?
Thanks for reading. -Coaster Mind
Thanks for the pictures. Perhaps you could add a DrawRay()
method in your FixedUpdate function, with a length of OnGround so that we can see exactly where the ray is ?(just to make sure we are not missing the obvious)
Thanks for re$$anonymous$$ding. I forgot to post this picture to. Hope it helps.
There's no collider on the raycast sprite.
Answer by Coaster-Mind · Apr 30, 2016 at 11:42 AM
Solved!
The transform.Translate (Vector2.down * 0.1f);
was first without a else
so the script didn't know that it did need to stop it when the ray gave information to do it.
Updated and working script: RaycastHit2D hit = Physics2D.Raycast(this.gameObject.transform.position, Vector2.down); if (hit.distance <= OnGround) { print ("Stop!"); transform.Translate (Vector2.zero); } else transform.Translate (Vector2.down * 0.5f);
Answer by Quertie · Apr 30, 2016 at 11:53 AM
Hello,
As it turns out, 3d Raycasting does not work with 2D colliders. A good alternative to raycasting could be to add a 2D collider to your character (or 2dTrigger, depending on how you plan on doing it).
Hope this works :)
Why does my raycast work on colliders then? ;) And yes, all 2d
I am glad it does ^^ Surprised though! The only thing is, I mistook the print("stop!");
line for a Debug.Log("Stop!");
line... So I thought you were supposed to get a "stop" message and you didn't, which would have been proof that no collision was detected ^^
Surprised? Really? **Physics**.Raycast() works with 3D physics and does not with 2D physics, **Physics2D**.Raycast() works with 2D physics and does not with 3D physics. Those are methods of different classes.
Oh I didn't realise this was a Physics2D Raycast ! Thanks for pointing that out; I was getting lost :)