I’m making a platformer game. My enemies have rigidbodys attached to them. I’m directly controlling their velocity by accessing the rigidbody.velocity component.
The problem is, when I have them chase me, they don’t run into things and stop. I want them to hit other rigidbodys and try to push against them, but go no where. Do I need to use AddForce? Will AddForce with the VelocityChange force type give me enough control?
It’s not recommended to move rigidbodies by changing their velocity directly (per docs and per your results). Instead use AddForce(), as you guessed, to get reasonable interactions with other rigidbodies, if you want acceleration (one of the main reasons for using a rigidbody). With this, your rigidbody can also get decent interactions with any animated colliders that have “animate physics” turned on in the Animation component checkbox. If you just want to move it without inertia, you can use MovePosition() and this will cause correct interactions with other rigid bodies.
Make sure to use AddForce() in FixedUpdate() to get correct acceleration. Conversely, never check Input.GetButtonDown() in FixedUpdate, you might miss some events–use the regular Update() for that, where the button down / up event is guaranteed for one frame.
You can still mess with rigidbody velocity directly with reasonable results if you’re doing something instantly, i.e. one frame, and not constantly managing it, which seems to fight the physics engine.
ForceMode.VelocityChange will give you instant velocity change. It ignores mass and acceleration. To get a hang of the different force modes, a handy trick is to put the ForceMode type used in your public variables, so you can change it at runtime and see what it does.
If you really want direct and straightforward control, consider using a CharacterController (it’s not just for player characters). That’s the far less troublesome route unless you really need diverse and/or complex physics interactions with other rigidbodies. Often, it’s easier to use the CharacterController component and apply simple, custom physics as needed, including pushing against rigidbodies.
If you’re sure you want to use a rigidbody controller, you’ll have to go to some trouble to avoid floaty, tedious to tweak, slow-to-start or fast-to-overshoot movement. The best way to do this is to make a motor component which manages linear acceleration to a target speed and angular acceleration to a target facing. Then, you can have a controller give higher level orders to move it around. There is a good example of this in the Angry Bots demo. The same low-level motor is used for player and NPC AI characters.
I think using add force should solve your problem. If your enemy still doesn’t collide with other rigid bodies, make sure your colliders aren’t triggers and if your other rigid bodies are imported as a 3d model make sure import colliders is checked in your rigid body prefab. (: