Pages

Sunday, July 10, 2011

How to use Physics.Raycast in your game

Physics.Raycast    

Syntax :  

static function Raycast (origin : Vector3, direction : Vector3, distance : float = Mathf.Infinity, layerMask : int = kDefaultRaycastLayers) : bool

Parameters



originThe starting point of the ray in world coordinates.
directionThe direction of the ray.
distanceThe length of the ray
layerMaskA 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

3 comments:

  1. If i use "if(Physics.Raycast (ray, out hit));"
    is there a way i can put an else block to detect if it doesnt hit an object?

    ReplyDelete
    Replies
    1. I use..

      Physics.Raycast(ray,out hit);
      if(hit.collider){

      }

      so Possibly with..

      if(!hit.collider){
      }

      Delete