- Home /
Add force to player at a certain z angle in 2D
Hello, I want to add a force at a certain z angle(which is a moving arrow going in a circle). I have accessed the rotation of that arrow by using arrow.transform.rotation.eulerAngles.z
So now how do I add a force on the player at the above z rotation? Thanks a lot in advance!! ^_^
Note: This whole project is in 2D
Answer by Fuzzel_ · Jun 04, 2020 at 12:47 AM
If we talking about physics forces, your object needs a Rigidbody2D (and possibly a collider). With that, you can apply instant force onto your object using Rigidbody2d.AddForce()
rigidbody.AddForce(force, ForceMode2d.Impulse);
Note: ForceMode2d.Impulse
is used for calling it a single time and applying the full force vector. ForceMode2d.Force
is used to apply it "over time" when used inside Update()
. A handy table of the different force modes can be found here (This is for 3D Rigidbodies, but the two force modes of Rigidbody2D still apply).
To get the correct force vector force
(green) you need to get the vector that points in the direction you want to move your object. An easy way to get this vector is by subtracting the position from your object (blue) with the position of your arrow (blue), to get the orange vector and then normalizing it (to get green). You can then multiply that vector with any factor to change the amount of force you want to apply (which will in turn affect it's speed).
Vector2 force = (player.transform.position - arrow.transform.position).normalized;
force *= speed;
Keep in mind that this application of forces does consider the mass of the rigidbody, so a heavier object will need more force to get moving the same speed as a lighter rigidbody.
The 3D rigidbody offers ForceModes that also ignore the mass, but according to the Unity documentation that is not the case for Rigidbody2D. If you don't want to take mass into consideration a simpler method is to change the velocity
vector of the rigidbody directly. You can use the same force vector as above
rigidbody.velocity = force;
Aaah! Thanks a lot! I still had some bugs with it but I solved it anyways by using Quaternions(I've no clue as to what I did :P)