- Home /
Shooting a bullet object toward the mouse position in a 2D.
I am looking everywhere for the code I can use to create this behavior and I just can't find it. I am making a top-down 2D shooter and I'm using c#. I just need the code to have the bullet object move in the direction of where the cursor was when the mouse button was pressed.
Here's my code: public class BulletBehavior : MonoBehaviour {
public float speed;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
private void OnTriggerEnter2D(Collider2D collision)
{
Destroy(gameObject);
}
}
I don't think you did look everywhere. This is a very common question: https://answers.unity.com/questions/736511/shoot-towards-mouse-in-unity2d.html
Answer by Priyanka-Rajwanshi · Apr 17, 2018 at 05:25 AM
Input.mousePosition would give you the position where you touched the screen. The direction of shoot can be found by subtracting the player position from touch position and normalizing that Vector. Apply velocity in this direction. The below code would be applied on the player at the position the bullet needs to be instantiated.
public GameObject bullet; // bullet prefab
public float bulletSpeed;
Vector3 myScreenPos; // screen position of player because Input.mousePosition gives screen coordinates
// Use this for initialization
void Start()
{
myScreenPos = Camera.main.WorldToScreenPoint(this.transform.position);
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
GameObject bulletShoot = (GameObject)Instantiate(bullet, transform.position, Quaternion.identity);
Vector3 direction = (Input.mousePosition - myScreenPos).normalized;
bulletShoot.GetComponent<Rigidbody2D>().velocity = new Vector2(direction.x, direction.y) * bulletSpeed;
}
}
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Destorying prefab and instanstiating again? 0 Answers
How do I make a 2d bullet object move towards the players original position when it is spawned? 2 Answers
Multiple Cars not working 1 Answer
How to move Instantiated 2D objects by 0.5 using arrows(or mouse) 1 Answer