- Home /
Converting angle and force, into a force applied to X and Y
Hi, I really need some help with this one! I need to apply force to a character, but because I use my 2D controller, not physics, I apply my forces in X & Y based on the input. However, I need to apply recoil kickback from the characters gun, in the opposite direction that the gun is facing.
I have the rotation of the transform for the gun, its calculated as per below.
Vector2 mousePos = Input.mousePosition;
Vector2 screenPos = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, transform.position.z - Camera.main.transform.position.z));
gun.transform.rotation = Quaternion.Euler(0,0,Mathf.Atan2((screenPos.y - transform.position.y), (screenPos.x - transform.position.x)) * Mathf.Rad2Deg);
So my question is, how can I translate that into a force to be applied to the X & Y of the parent object.
For example, if the angle is 45 degrees and I want to apply 20 force. How do I work out how to split that force between the X & Y coords, based on the angle above?
Answer by NoBrainer-David · May 17, 2017 at 08:39 AM
Assuming you have the GameObject of the character in "character", you can use the dot product to calculate those force magnitudes, like so:
float xForce = force * Vector3.Dot(character.transform.up, -gun.transform.right);
float yForce = force * Vector3.Dot(character.transform.right, -gun.transform.right);
This assumes that "right" is forward for your gun but it might be "up", depending on your set up.
A little more detail: The dot-product gives you the magnitude of vector A projected onto vector B. So in our case, we want to project the reverse direction the gun is pointing at onto the forward and right direction of the character. In a 2D scene, the z-axis (which is usually forward) is not used, so right or up becomes forward.
Thanks very much, I tried that but it doesnt work, it pushes all in the same direction, irrespective of whether I use right or up... im using 2D so its only X & Y and Z for rotation, if that makes any difference?
Okay, so I'm guessing that your gun and your character might always face the same direction? And your input is relative to the world space and not the character?
Then you could try to use Vector3.up and Vector3.right, ins$$anonymous$$d of character.transform.up and character.transform.right.
Actually it works perfectly, it helps when you arent a muppet when implimenting the solution given to you ;)
Thanks man, really appreciate the help :)
Your answer
Follow this Question
Related Questions
How to do relativte offset rotation 0 Answers
Random perpendicular vector3 after rotation 1 Answer
How can I set a ConstantForce's force to move the object towards another object? 1 Answer
How do I add force to an object based on my Camera's cureent Y rotation (C#) 2 Answers
Quaternion and rotation angles 2 Answers