- Home /
How to use raycast when standing still.
I made a script that shoots a raycast through the Mouse point to hit a collider. The problem is that it only will contact the collider if my player is moving. function Start () { }
function Update () {
Screen.lockCursor = true;
if(Input.GetKey("l")){
Screen.lockCursor = false;
}
if(Input.GetMouseButtonDown(0)){
//Debug.Log("LEFT SWAGGER LOL");
var hit : RaycastHit;
var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray,hit,20.0)){
//print("ERMEHGERD YOU HIT SOMETHING");
if(hit.collider.tag == "Tree"){
Debug.Log("Tree Hit");
hit.collider.transform.GetComponent(scriptTree).hitCount();
}
else
{
Debug.Log("Nothing");
}
}
}
}
I think it has something to do with the Screen.lockCursor, but Im not sure. Thank you for your help!
Answer by AlucardJay · Nov 13, 2012 at 05:52 PM
If you are using Screen.lockCursor while playing in the Unity Editor, left mouse click breaks this. Then there are all sorts of problems with Input.mousePosition after that. If you are using Screen.lockCursor, then it would be safe to assume you always expect the mouse to be in the center of the screen. Try this :
var ray : Ray = Camera.main.ScreenPointToRay( Vector3( Screen.width * 0.5, Screen.height * 0.5, 0.0 ) );
Your ray will then always be cast from the center of the screen, even when Screen.lockCursor breaks in the editor (and webplayer!).
Sorry for really late reply but it still doesn't work for me if my character is standing still. Could this be because I'm using the first person controller.
In that case, start testing bit-by-bit. What happens when you use :
if ( Input.Get$$anonymous$$ouseButtonDown(0) )
{
var hit : RaycastHit;
var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray,hit,20.0))
{
Debug.Log( "$$anonymous$$ouseRay Hit : " + hit.collider.gameObject.tag );
if ( hit.collider.gameObject.tag == "Tree" )
{
Debug.Log("Tree Hit");
var treeScript : scriptTree = hit.collider.transform.GetComponent( scriptTree );
treeScript.hitCount();
}
else
{
Debug.Log("Nothing");
}
}
}
BTW you should really have your classes starting with a capitol, and your variables as camelCase :
var scriptTree : ScriptTree;
Right so it still has the same problem it shoots the Raycast but wont notice the tree until I am moving. Standing still and looking at tree ($$anonymous$$ouse Ray Hit: Untagged) $$anonymous$$oving and looking at the tree ($$anonymous$$ouse Ray Hit: Tree).
Gonna make a few debug objects in the scene and see if its just the mesh maybe.
If your tree has a collider, try using primitive colliders like a capsule collider. If using mesh colliders, make sure the import settings are set to convex. There is also a problem with mesh colliders culling the back (unseen) side, so again try with just a primitive collider
I have tried this before and had the same issue. I tryed using a capsule and a box collider.