AddForce changes behavior based om location.

I’m trying to make an enemy jump toward its target to attack using AddForce. but just how much force is added seems to depend greatly on where in the scene the entities are (see video: - YouTube ) and I can’t figure out what I’m doing wrong.

	void Start(){
		ani = GetComponent<Animation>();
		agent = GetComponent<NavMeshAgent>();
		rig = GetComponent<Rigidbody>();
		state = states.idle;
	}

	private void Attack(){
		state = states.attack;
		agent.enabled = false;
		ani.Play("attack3");
		Vector3 force = transform.forward * 300f;
		force.y = 750f;
		rig.AddForce(force);
	}

Hi

I can envisage 2 possible situation here:

first, it is possible that you are calling ‘Attack’ every frame from within an ‘Update’ function. Because ‘Update’ is not called at a fixed rate with respect to the physics, this would mean you applied more force if the frame rate was higher! The simplest (and arguably most correct) way to solve this would be to call your AddForce from within FixedUpdate, as it would then be correctly called once per physics step.

//adding a fixed amount of force (which internally is scaled
//by fixed time step) every FixedUpdate
void FixedUpdate()
{
    rigidBody.AddForce(new Vector3(0,10,0);
}

The other option is that your transform.forward is not in the xz plane. If that was the case, then the ‘flatter’ your transform.forward is, the more powerful your jump would be. This is because you override the y value, so only the xz bits are scaled. If we took it to the extremes, if your transform.forward was [0,0,1], you would get [0,750,300], but if your transform.forward was [0,1,0], you would get [0,750,0].

My guess is that its the first issue though. I suspect you’re calling AddForce every frame from within Update. If you do want a continuous (multi frame force), you’ll need to do it from within FixedUpdate. However if the bug is that you’re calling it every frame, then you should just use ForceMode.Impulse, and can call it from wherever you like.

I’d recommend reading up on FixedUpdate vs Update, and the different types of force mode. Here’s another similar question I answered a little while ago:

http://answers.unity3d.com/answers/1113442/view.html

-Chris

You might be getting some strange behavior because you have Rigidbody and NavMeshAgent enabled at the same time.

It is likely the velocity of the object is not zero when you disable the NavMeshAgent and that is causing the strange results.

Depending on what you are trying to do, you could set the Rigidbody to kinematic and only set it to non-kinematic when you need it.

You could also set to velocity to zero before the applying the force so the jump is consistent.