- Home /
Having trouble with raycast rigidbody object childing for tractor beam
I'm working on my first game, so forgive any noobish mistakes.
So I have this spacecraft and I've been working on this 'tractor beam' of sorts where I can use a laser Raycast to detect an object in a certain distance in front and then drag that physics object with my spacecraft around and be able to also detach it when mouse if released.
Here's my code so far.
bool laser = Input.GetMouseButton(0);
RaycastHit hit;
Debug.DrawRay(transform.position,transform.forward * 50);
if (laser == true) {
if(Physics.Raycast(transform.position,transform.forward, out hit,50)) {
rayhit.text = "LOCKED ON";
hit.collider.transform.parent = transform.parent;
}
else {
rayhit.text = "Ready";
}
}
The problem being the target won't mimic my spacecraft's movements once it has "locked on". I've been trying to make it a child of my spacecraft, but that doesn't seem to work.
Note: Not sure if this effects it, but both objects are rigidbodies and the spacecraft moves around using AddForce with keyboards (like thrusters).
Your parent/child approach sounds ok to me, perhaps the issue is that once locked on, you need to stop all forces affecting the target object
rigidbody.velocity = Vector3.zero
That didn't really work. I managed to get some movement using addRelativeForce, but that ends up shooting the object if it loses the tractor beam.
Answer by Lo0NuhtiK · Mar 24, 2014 at 01:32 AM
Change the caught objects rigidbody to isKinematic while it's caught and try that. Something like this :
RaycastHit hit ;
Transform caughtObj ;
Rigidbody caughtRig ;
Transform myTrans ;
Rigidbody myRigid ;
void Start()
{
myTrans = this.transform ;
myRigid = this.rigidbody ;
}
void Update()
{
GrabStuff() ;
}
void GrabStuff()
{
if(Input.GetMouseButtonUp(0)) //if we let go of this thing, drop it
{
//rayhit.text = "Ready" ;
if(caughtObj)
{
caughtObj.parent = null ;
if(caughtRig)
{
caughtRig.isKinematic = false ;
caughtRig = null ;
}
caughtObj = null ;
}
}
if(caughtObj) //early-out if already caught something
return ;
if(Input.GetMouseButton(0)) //if we're trying to grab something
{
Debug.DrawRay(myTrans.position, myTrans.forward * 50f) ;
if(Physics.Raycast(myTrans.position, myTrans.forward, out hit, 50f))
{
//rayhit.text = "Locked On" ;
caughtObj = hit.transform ;
caughtObj.parent = myTrans ;
caughtRig = caughtObj.rigidbody ? caughtObj.rigidbody : null ;
if(caughtRig)
caughtRig.isKinematic = true ;
}
}
}
If this helps you I'll convert this post to an answer.