简体   繁体   中英

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.

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 Vector3.zero

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,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM