- Home /
Getting x and y from an angle. (Unity 2D)
I have a top-down 2D space shooter. To rotate my ship I use angles. So to fire bullets I have to get x and y to use rigidbody2D.AddForce(). I use this code:
void Update () {
GameObject instance = (GameObject)Instantiate (Resources.Load ("Bullet"), bulletSpawn.transform.position, bulletSpawn.transform.rotation);
instance.rigidbody2D.AddForce (new Vector2 ((bulletSpawn.transform.position.x - transform.position.x)*shotPower, (bulletSpawn.transform.position.y - transform.position.y)*shotPower));
}
//bulletSpawn is the GameObject in the front of my ship, where I fire bullets from. Script is attached to the ship.
The code works fine. The only problem is that when the ship goes fast, the shots are fired not in the way they are intended to (they go more left the faster you go). Hope at least someone will understand this. Sorry for crude grammar.
Answer by highpockets · Feb 02, 2014 at 08:17 PM
I'm assuming that you want to fire the bullets on whatever angle that the ship is facing. In this case, you don't want to subtract the bulletSpawn.transform.position by the transform.position, but rather use rigidbody.AddForce( transform.up * shotPower ); assuming that your forward vector of your ship is originally facing the top of the screen.
I've found out the problem. When I move, for example, left and shoot upwards, bullets travel diagonally, because I move diagonally relatively to them. Nevertheless, thank you help.
Your answer
Follow this Question
Related Questions
Angles invert after flipping player by 180 on Y-axis in 2D. 0 Answers
How can i calculate angle ? 2 Answers
How to calculate angle in the triangle formed by screen touches 1 Answer
Get the gameobject to the left/right of current target, in field of vision? 0 Answers
calculate the angle live 0 Answers