Raycast not working at pointblank
I am brand new to this, so I have a simple script, that when I left click the "rock" object it will eventually break, and spawn rubble.
It works as intended, except for when I am in point-blank distance to the "rock" object. Can anyone help me figure out why?
using UnityEngine;
using System.Collections;
public class RockHealth : MonoBehaviour {
public int Health;
public GameObject FallenRock;
public Camera myCamera;
void Start () {
myCamera = GameObject.FindObjectOfType<Camera>();
}
void Update ()
{
if(Health > 0)
{
if(Vector3.Distance(transform.position, myCamera.transform.root.transform.position) < 10f)
{
if(Input.GetKeyDown(KeyCode.Mouse0))
{
Ray ray = new Ray(myCamera.transform.position,myCamera.transform.forward);
RaycastHit hit;
if(Physics.Raycast(ray,out hit,10f))
{
if(hit.collider.gameObject == gameObject)
{
--Health;
}
}
}
}
}
if(Health <= 0)
{
Health =0;
Destroy(gameObject);
Instantiate(FallenRock,transform.position,transform.rotation);
}
}
}
Comment
your casting the Ray along the camera forward not through your cursor position (wouldn't matter if they are aligned at all times). use camera.screenpointtoray with the mouse position ins$$anonymous$$d of camera.forward