- Home /
Pickup and carry rigidbody
I am trying to pickup and carry a rigidbody weapon, where it will move to a point in front of the player, and move with the player like a child object would, but still react to physics. Right now, I am simply setting the velocity to move towards the position, and adding the player's rigidbody velocity to the weapon movement velocity. When I do this, the weapon moves to the correct spot, but when I move around, the weapon jerks around. I want it to stay at the spot once it gets to that point. Here's a video showing the problem. This is the code I have...
void FixedUpdate()
{
if (beingHeld)
{
rb.velocity = ((holdPosition - rb.position + (playerObj.GetComponent <Rigidbody>().velocity / Time.deltaTime / 1500)) * Time.deltaTime * 1500);
}
}
Answer by WarmedxMints · Mar 06, 2019 at 09:07 PM
Take a look at this open source project I worked on. We made a physics gun similar to that found in garrys mod. github What I did was create a vector at a point where the gun grabs the object and then calculate the direction and force to get the object to that point.
@Warmedx$$anonymous$$ints I tried this out, and the problem that I'm having is that the rigidbody is lagging behind the point, so when I move while ai$$anonymous$$g down my sights, the sight is never in the middle of the screen, is this something that occurred in your project?
Not really. I set it up so the rigidbody mass effects how quickly it moves to the grab point. Something with a mass of 1 will move almost instantly whereas something will mass of 10 will get dragged and move slower. That was intentional in the gun project. Fork the git and try it out.
Hm I'm still not sure, I have the mass of the weapon object set to 1, and I use this code to move the object...
void FixedUpdate()
{
if (beingHeld)
{
Vector3 holdPosition = positionTo$$anonymous$$oveTo;
Vector3 toPos = holdPosition - transform.position;
Vector3 forcePos = toPos / Time.fixedDeltaTime / rb.mass;
rb.velocity = Vector3.zero;
rb.AddForce (forcePos, Force$$anonymous$$ode.VelocityChange);
}
}
It looks like it moves instantly to the position, but then when I walk around it's lagging behind. Am I doing this correctly?