- Home /
Raycast won't work after Camera transforms position. Please help!
I'm making a space ship game. I have a raycast shooting script attached to the main and only camera. It works fine and destroys the object that the raycast hits. When the player hits a wall and dies; the camera and ships transforms position to a set location at the beginning of the level. However, the raycast section of the shoot script no longer works and I have no idea why. Below is the shoot script.
using UnityEngine; using System.Collections;
public class Shoot : MonoBehaviour
{
bool isShowingLaser = false;
public GameObject Lazer;
void Start()
{
Lazer.renderer.enabled = false;
}
void Update()
{
if(Input.GetMouseButtonDown(0))
{
fireLaser();
}
}
void showLaser()
{
if( isShowingLaser ) return;
isShowingLaser = true;
Lazer.renderer.enabled = true;
Invoke("resetLaser",0.05F);
isShowingLaser = false;
}
void resetLaser()
{
Lazer.renderer.enabled = false;
}
void fireLaser()
{
showLaser();
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); //raycast in direction of mouse position
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100.0f))
{
if(hit.transform.gameObject.tag == "Shootable") //destroy object with tag "Shootable"
{
Destroy(hit.transform.gameObject);
}
}
}
}
When you get a bug like this, put in some Debug.Log() statements to figure out what is going on. Is the raycast failing or is the raycast hitting something that is not Shootable? Output the name and the the tag inside the raycast.
Debug.Log(hit.collider.name + " , " + hit.collider.tag);
I usually prefer to just Debug.DrawRay
the ray with the distance of the hit, so I can both see what it's hitting and what direction it travels :)
Answer by gRntaus · Apr 11, 2013 at 05:38 AM
Assuming that the object is in fact close enough to hit the object and you're still getting no luck perhaps try adding a direction to the vector in case it is going in some weird direction?
It's either something along the line of:
if (Physics.Raycast(ray, ray.direction, out hit, 100.0f));
Or
if (Physics.Raycast(ray, Camera.main.direction, out hit, 100.0f));
I don't have access to Unity right now but I've seen similar responses around here. I'd also suggest drawing the ray. I found when I rotated my camera that using Vector3.down still took into account the camera rotation so the ray wasn't going where I expected, I had to change the rotation accordingly.