I’m trying to make a ray detect walls and stop the movement of the player. I don’t know why but it seams like the ray just wont cast at all and dose nothing no movement or anything, could someone please help me fix this, I’m not getting any bug errors or anything.
void Update () {
RaycastHit hit = new RaycastHit ();
//Move
if (Input.GetKeyDown (KeyCode.W)) {
if (Physics.Raycast (transform.position, Vector3.forward, out hit, 2.60f)) { //this is what I want it to do but nothing happens
if (hit.collider.gameObject.tag == "Wall") {
Debug.Log("Wall - No Move");
}else{
transform.Translate (Vector3.forward * Speed);
}
}
}
if (Input.GetKeyDown (KeyCode.S)) {
transform.Translate(Vector3.back * Speed); //this way works fine but gose through wall
}
}
I’m using C-Sharp.
It’s because you raycast in direction of Vector3.forward instead of transform.forward. You did the same mistake on your “transform.Translate”.
Vector3.forward = 3D world’s forward
transform.forward = Your object’s forward (this is what you want)
More of that : You need to put the “translate” also on the else of the if(Physics.Raycast), because if the raycast hits nothing, this method will return false, and if it return false, your code does nothing.
Should be something like this :
if (Physics.Raycast (transform.position, transform.forward, out hit, 2.60f)) {
if (hit.collider.gameObject.tag == "Wall") {
Debug.Log("Wall - No Move");
}
}else{
transform.Translate (transform.forward * Speed);
}
use this to draw the raycast and you can chcek that if your raycast is hitting the wall or not
Debug.DrawRay(transform.position, forward, Color.green);
I know it is quite an old post but the answer I think is that the distance, i.e. 2.60f is too small.
Unity counts in meters so it means that the ray you are casting or the gun you are shooting has a range of just 2.60 meters…
Try Mathf.Infinity instead of 2.60f, hopefully, it will solve someone’s problem.