- Home /
Moving Rigidbody in fixed update
Hi,
So RB should be moved in FixedUpdate. Is this the case whether it is moved by AddForce, or MovePosition, or both?
My RB is following a NavMesh waypoint path. What I'm trying to do is move my RB a shunt to its right or left on press of a key:
public float shuntTimer, shuntForce;
void Update()
{
if (Input.GetKeyDown(KeyCode.P))
{
if (shuntTimer>0) // trigger in Update by virtue of the timer != 0
{
// apply a force with magnitude shuntForce; cease the force when the timer expires
rigidbody.AddForce(transform.right*shuntForce*shuntTimer);
// reduce the timer and also the duration of the force
shuntTimer -= Time.deltaTime;
}
}
So this doesn't work. Not sure why not.
Vector3 velocity;
void Update()
{
if (Input.GetKeyDown(KeyCode.P))
{
velocity = Vector3.Lerp(velocity, transform.right*shuntFactor, Time.deltaTime);
}
}
void FixedUpdate()
{
rigidbody.MovePosition(rigidbody.position + velocity * Time.deltaTime)
}
And this doesn't either. Again, not quite sure why not.
When I say "doesn't work", neither of these approaches moves the RB at all.
Any help please?
Is the script attached to an active gameObject?
Are the values of
shuntForce
andshuntTimer
big enough?Have you tried to call a simple
Debug.Log
inside the various functions (`Update` andFixedUpdate
) and conditions (`if`) to see whether the functions are called and ifvelocity
or the force you apply are not too close to0
?
1) yes, and it has an RB. 2) yes, in testing I have set them to many orders of magnitude higher than need be 3) yes, the functions are being called.
Are you basically saying the code should work?
Is the fact that the object is a Nav$$anonymous$$esh object and is "patrolling" (setdestination) to waypoints interfering with the application of this code?
The two versions of your script work here, but I have a single cube with a Rigidbody, no Nav$$anonymous$$eshAgent, and I believe the latter is interfering with this script, indeed.
Answer by cs120319992 · May 30, 2019 at 12:19 PM
Vector3 velocity;
void Update()
{
if (Input.GetKeyDown(KeyCode.P))
{
velocity = velocity == -1 ? 1 : -1;
}
}
void FixedUpdate()
{
rigidbody.transform.position += Vector3.right * velocity * Time.deltaTime;
}
Answered to "When I say "doesn't work", neither of these approaches moves the RB at all."
I have indicated 3 hours ago The two versions of your script work here, but I have a single cube with a Rigidbody
rigidbody.AddForce(transform.right*shuntForce*shuntTimer, Force$$anonymous$$ode2D.Force or Impulse);
Your answer
Follow this Question
Related Questions
What is the best way to move the player with physics without using MovePosition? 0 Answers
Can an accelerometer be used for a RigidBody based movement? 0 Answers
AddForce vs MovePosition Rigidbody. 2 Answers
AddForce to position on Rigidbody 2 Answers
MovePosition not as precise as Translate with Kinematic rigidbodies (example unitypackage included) 1 Answer