Raycast Issue

Ok I asked this last night but didn’t give enough information, so here goes.

I use this code to make a gameobject kinematic when it is a certain distance from an object. it works fine but there is a small difference between the positions it stops at, 0.4 to be precise.

private var speed : float = 2000;
private var Range : float = 3.7;
private var DirectionRay : Vector3;
 
function Awake(){
     rigidbody.isKinematic = true;
}
 
function Update () {
 if(rigidbody.isKinematic){
       if(Input.GetKeyUp("up")){
             rigidbody.isKinematic = false;
             DirectionRay = Vector3.up;
                rigidbody.AddForce(Vector3.up * speed);
       }
     if(Input.GetKeyUp("down")){
             rigidbody.isKinematic = false;
             DirectionRay = Vector3.down;
                rigidbody.AddForce(Vector3.down * speed);
       }
    }
}
 
function FixedUpdate(){
 
var wall : RaycastHit;
 
Debug.DrawRay(transform.position, DirectionRay * Range, Color.blue);
 
if(Physics.Raycast(transform.position, DirectionRay, wall, Range)){
 
    if(wall.collider.gameObject.tag == "bound" && !rigidbody.isKinematic){
       rigidbody.isKinematic = true;
    }
}
}

I took a picture of the Debug Raycast and you can clearly see that the raycast goes into the gameObject at different lengths! Strange or am I missing something obvious?

You need to switch your Update and FixedUpdate functionality around. You should probably check the position and such every frame. And you should only use rigidbody.AddForce from within FixedUpdate. Switching around the function names should fix your problem :slight_smile:

[What fixed it]
When you raycast and get a hit, use the RaycastHit.point to set the position minus the half height of the green box. With those speeds I doubt it will be noticeable and you will get a precise position