Physics.Raycast
Syntax :
static function Raycast (origin : Vector3, direction : Vector3, distance : float = Mathf.Infinity, layerMask : int = kDefaultRaycastLayers) : bool
Parameters
origin | The starting point of the ray in world coordinates. |
direction | The direction of the ray. |
distance | The length of the ray |
layerMask | A Layer mask that is used to selectively ignore colliders when casting a ray. |
Returns
bool - True when the ray intersects any collider, otherwise false.
Description
Casts a ray against all colliders in the scene.
Use in Game :
First we need to declare it like this in our Script .
void Update ()
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out hit)&& Input.GetButtonDown("Fire1"))
{
Debug.Log(hit.collider.tag);
if(PreviousClick == 0)
{
if(hit.collider.tag == "Character")
{
Debug.Log("in if " + hit.collider.tag);
PreviousClick = 1;
sourceTag = hit.collider.name;
x_currPos =(int(hit.collider.gameObject.transform.position.x / tileSizeAdjustment);
y_currPos = (int)(hit.collider.gameObject.transform.position.y / tileSizeAdjustment);
hit.collider.gameObject.renderer.material.color = Color.red;
//hit.collider.gameObject.renderer.material.color = Color.green;
Debug.Log(sourceTag);
}
else if(hit.collider.tag == "PlaceHolder")
{
Debug.Log("Can't Move object ov there");
return;
}
}
}
Now you can Download Code From Here
--
Vivek P Shah
Game Developer in Unity3d And Cocos2d
Skype : viveks2012
If i use "if(Physics.Raycast (ray, out hit));"
ReplyDeleteis there a way i can put an else block to detect if it doesnt hit an object?
I use..
DeletePhysics.Raycast(ray,out hit);
if(hit.collider){
}
so Possibly with..
if(!hit.collider){
}
Very old post lol
Delete