Echi Echi - 1 year ago 69
C# Question

AddForce doesn't work

I have this following code in a FixedUpdate() method with a Input.GetMouseButton(0) condition:

public void playerAttack()
RaycastHit hit;
if (Physics.Raycast(player.transform.position, player.transform.forward, out hit, range)) //range = 7f
if (hit.rigidbody != null && hit.transform.tag == "Enemy")
Vector3 dir = new Vector3(hit.transform.position.x, hit.transform.position.y, hit.transform.position.z - 100f);
hit.transform.GetComponent<Rigidbody>().AddForce(dir * weaponPush * Time.deltaTime); //weaponPush = 1f


The enemy object has rigidbody on it and isKinematic is not selected. It still doesn't move when I am almost in front of it and click the left mouse button.

Answer Source

This not working could be because of many things:

  • your Rigidbody could be set to Kinematic
  • your Rigidbody drag value could be too high
  • your object could move but you don't see it because force is to low (may be cause of the use of Time.deltaTime)
  • if your object is located in [0.0f, 0.0f, 100.0f], the dir vector will be

Also as a side note I'd advise using Time.fixedDeltaTime inside FixedUpdate() (Time.deltaTime will return the same value but this way you remember working inside a "physics" frame).

Hope this helps,

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download