- Home /
2D C# top down shooter, adjusting the projectiles angle
Hello, so im as my first game trying to make a 2d top down shooter. I have a projectile (an arrow) that my character shoots but I have problem making this arrow point towards the direction I'm shooting. The player character is not turning at all in this game.
public class Fire : MonoBehaviour
{
public GameObject projectile;
public float fireRate = 2f;
private float nextFire = 0f;
private Vector3 target;
void Start()
{
target = transform.position;
}
void Update()
{
GameObject projectileObject;
if (Input.GetButton("Fire1") && Time.time > nextFire && Time.timeScale == 1)
{
nextFire = Time.time + fireRate;
target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Quaternion rotation = Quaternion.LookRotation(target - transform.position, Vector3.forward);
Quaternion targetRotation = new Quaternion(0, 0, rotation.z, rotation.w);
projectileObject = Instantiate(projectile,
new Vector2(transform.position.x + 0.4f, transform.position.y + 0.2f),
targetRotation) as GameObject;
}
}
}
I want to get the angle from the player (transform) to the position where I click (target) and then set the angle of the arrow.
The current solution you see above does change the angle of the arrow depending on where I aim but not correctly.
Answer by Pyrian · Jul 19, 2014 at 05:58 PM
You'll want Mathf.ATan2. The various Look* functions don't work in 2D (they point the Z-axis). Something like:
Quaternion rotation = Quaternion.Euler(0.0F, 0.0F, Mathf.Atan2 (Y, X) * Mathf.Rad2Deg)
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
How can I limit the rotational speed of a gameObject tracking my mouse? 1 Answer
Detect Full 360 rotation of an object when direction changes and change it's color. 2 Answers
How to get rotation for projectile to fire at cursor? 1 Answer
Issues calculating angle in 2D 0 Answers