- Home /
How to add force towards an object with variable degree accuracy 2d
I have a game where I am creating meteors to launch towards a planet in the middle of the screen. Right now I am creating meteors and adding force towards the center of the planet.
What I want to happen is that they should be launched with a random angle (within a certain amount), so they will potentially not even hit the planet. Basically I want to be able to change its direction to 30 or so degrees to the right or left of the planet. But I am having trouble finding out how I would do that. Here is what I currently have for launching a meteor straight at the planet:
GameObject m = Instantiate(obj, vect, Quaternion.identity);
m.GetComponent<Rigidbody2D>().AddForce((Planet.transform.position - m.transform.position).normalized * 500);
m.GetComponent<Rigidbody2D>().AddForce(transform.right * 200);
So I want to: 1. Spawn a meteor object 2. Aim meteor at the planet and add a variable angle accuracy 3. Addforce to the meteor in that direction
Thank you in advance for any help. Here is a quick illustration as well. The green circle is the planet and the purple circle is a meteor.
(Also I couldn't space out this write up in the format I wanted, at least in the preview so I apologize if its jumbled)
Answer by hectorux · Nov 15, 2018 at 02:35 PM
You just need to create a Vector3 dir, this is equal to the direction to the center of your planet. Then you can make your forward equal to this vector, use transform.Rotate(0,x,0)(choose your axis rotation), and then add the force based on your forward (m.GetComponent().AddForce((meteor.forward * 500);)
Your answer
Follow this Question
Related Questions
Enemy shoot at player in 2D game 3 Answers
Vector2.angle - how do i get if it's CW or CCW ? 5 Answers
Turn 2D object toward Vector2 position? 1 Answer
Using Lerp with 2d only moving partially 1 Answer
Deteriorating force on object? 0 Answers