- Home /
Question by
ayockel90 · Oct 30, 2021 at 06:00 PM ·
2dmouseposition
How to shoot towards mouse position in 2d?
I'm using the below code in an attempt to shoot an arrow toward the mouse cursor but the arrow just shoots upwards and to the left. How can I get it to shoot toward my cursor?
public void shootArrow(float scaler) {
Vector2 vectorToTarget = Camera.main.ScreenToWorldPoint(Input.mousePosition) - center.transform.position;
arrow = Instantiate (arrowPrefab, center.transform.position, Quaternion.identity) as GameObject;
arrow.GetComponent<Rigidbody2D>().AddForce(vectorToTarget * shootStrength * scaler, ForceMode2D.Impulse);
}
Comment
Answer by logicandchaos · Oct 30, 2021 at 11:50 PM
You use vector math! If you get the mouse coordinates you can subtract them from the player position and then normalize it to get the direction, then you use that direction calculating the velocity for the arrow.
I've added the normalize but it makes no difference. Is this what you're talking about?
public void shootArrow(float scaler) {
Vector2 vectorToTarget = Camera.main.ScreenToWorldPoint(Input.mousePosition) - center.transform.position;
vectorToTarget.Normalize();
arrow = Instantiate (arrowPrefab, center.transform.position, Quaternion.identity) as GameObject;
arrow.GetComponent<Rigidbody2D>().AddForce(vectorToTarget * shootStrength * scaler, ForceMode2D.Impulse);
}