- Home /
Why can't my Physics.Raycast work
I'm making 2D games (well, i'm really new), and I use this UnityScript code (frankly speaking, it's from the tutorial) inside a gun sprite without collider in (0,0,0). I put some objects with box collider next to the gun (around (5,0,0)). When I click the mouse, the "shoot shoot!" shows up in the log, but the shootHit.point doesn't. I have set every layer but the gun as "Shootable" and no result yet.
Could anyone tell me why?
#pragma strict
var fireSpeed : float = 0.4f;
var range : float = 100f;
private var timer : float;
private var shootRay : Ray;
private var shootHit : RaycastHit;
private var shootableMask : int;
function Awake () {
shootableMask = LayerMask.GetMask("Shootable");
}
function Update () {
timer += Time.deltaTime;
if(Input.GetButton("Fire1") && timer >= fireSpeed){
Shoot();
}
}
function Shoot () {
timer = 0f;
Debug.Log("shoot shoot!");
shootRay.origin = transform.position;
shootRay.direction = transform.right;
if(Physics.Raycast(shootRay, shootHit, range, shootableMask)){
Debug.Log(shootHit.point);
}
}
Some objects in your scene must have the "Shootable" layer, is it the case ?
Answer by sparkzbarca · Apr 03, 2015 at 12:34 PM
your code is correct and should function.
do this
shootRay.origin = transform.position;
shootRay.direction = transform.right;
Debug.DrawLine(shootRay.origin, shootRay.direction * 100 , Color.red, 15f);
that will draw a line out to 100 units from the object. Basically if you have gizmos turned on in the editor once you press play you'll be able to see the line and actually see the ray being casted.
Hmm, I've tried to debug, and the line is drawn properly. Then is the problem the layer? Thank you by the way..