Search Unity

Problem: Character lags using raycast to grab an object

Discussion in 'Scripting' started by devprincess, Jan 29, 2013.

  1. devprincess

    devprincess

    Joined:
    Sep 7, 2012
    Posts:
    116
    Hi guys, I'm having trouble with raycast, I've put it in my third person controller script to grab objects around the scene. anyway it looks like the character lags whenever he gets closer to the object. I've set the mesh collider to my objects and anyway my character always lags.

    I leave my raycast part code so you can see it clearly, maybe I'm wrong with the code? Thanks in advance!


    Code (csharp):
    1.  
    2.  
    3. //This is done inside the Update() function in ThirdPersonController Script.
    4.  
    5.     if(Physics.Raycast (transform.position,transform.forward, hit, 10))
    6.     {
    7.         Debug.Log("choca contra:"+hit.collider.gameObject);
    8.         if(hit.collider.gameObject  Input.GetMouseButtonDown(0)  grabObj == false)
    9.         {
    10.                 hitObj = hit.collider.gameObject;
    11.                 Debug.Log("Clickea en el pastel");
    12.                 grabObj = true;
    13.         }
    14.         else
    15.         if(Input.GetMouseButtonDown(0)  grabObj == true)
    16.         { grabObj = false;}
    17.  
    18.     }
    19.  
    20.     if(grabObj){
    21.         //Moving object with player, 2 units in front of him cause we want to see it.
    22.     hitObj.transform.position.x = gameObject.transform.position.x;
    23.     hitObj.transform.position.y = gameObject.transform.position.y;
    24.     hitObj.transform.position.z = gameObject.transform.position.z+2;
    25.         }
     
  2. Ruthra

    Ruthra

    Joined:
    Feb 3, 2013
    Posts:
    12
    Hi, I think you should do your raycasting after the GetMouseButtonDown test.

    This way you would not be doing physics every frame but only once when mouse button is clicked.
     
  3. devprincess

    devprincess

    Joined:
    Sep 7, 2012
    Posts:
    116
    Thanks ozwizart, you are right! :)