I’m writing a script that would allow a player to “carry” an object similar to how objects are carried with the gravity gun in Half Life 2. Since these objects are quite big, I have to worry about them not clipping through the floor, so I can’t just change the position. I have tried many approaches such as addForce and parenting, but the best way I have so far is changing the velocity on each step. But this has it’s own problems as the box appears jumpy when walking, and collisions with walls makes the box go crazy. Here is what I have so far:
The carry loop (in C#):
IEnumerator carry(Transform obj) {
obj.rigidbody.useGravity = false;
while (carrying) {
Vector3 center = transform.position + (transform.forward* 4);
Vector3 objPos = obj.transform.position;
if (Vector3.Distance(objPos, center) > 1.5F) {
break;
} else if (Vector3.Distance(objPos, center) > .1F) {
Vector3 Dir = center - objPos;
obj.rigidbody.velocity = Dir * 50;
} else {
obj.rigidbody.velocity = Vector3.zero;
}
yield return null;
}
obj.rigidbody.velocity = obj.rigidbody.velocity * .5f;
obj.rigidbody.useGravity = true;
}
How it is called:
public void Update() {
//If pressed E and not carrying
if (Input.GetKeyDown(KeyCode.E) && !carrying) {
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, out hit, 8)) {
if (hit.rigidbody && !hit.rigidbody.isKinematic) {
carrying = true;
StartCoroutine(carry(hit.transform));
}
}
} else if (Input.GetKeyDown(KeyCode.E) && carrying) {
carrying = false;
}
}
Any ideas on how to make this more smooth? Or is there a better way to do it rather than changing the velocity each call (which I know messes with the physics)