Shooting bullet towards mouseposition 2D.

Ive been trying to piece out how to fire a bullet in the direction of the mouse, but the bullet goes no where.

			GameObject energyBall = Instantiate (Prefabs.EnergyBall) as GameObject;
				energyBall.transform.position = transform.position;
				var mousePos = Input.mousePosition;
				
				mousePos.z = (transform.position.z - Camera.mainCamera.transform.position.z); //The distance from the camera to the player object
				var worldMousePosition = Camera.main.ScreenToWorldPoint (mousePos);
				energyBall.transform.LookAt (worldMousePosition, Vector3.forward);
	
				energyBall.rigidbody2D.AddForce (Vector3.forward * 5000);

You’ve got two problems here. The first is that Rigidbody2D operates on the XY plane. It will ignore any force added in the Z direction. In fact it takes a Vector2, so the ‘Z’ component of a Vector3 is tossed away. So the use of Vector3.forward (which is (0,0,1)) will do nothing in a Rigidbody2D.AddForce() call. The second likely problem is how you’ve handled the rotation code. For a 2D sprite, you don’t want to face the ‘Z’ direction towards the LookAt(). Instead you want whatever side of the sprite represents forward to be pointed at the correct direction. Here is a bit of (untested) code. Replace your code starting with line 6:

var worldMousePosition = Camera.main.ScreenToWorldPoint (mousePos);
var direction = worldMousePosition - transform.position;
var angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Atan2;
energyBall.transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
energyBall.rigidbody2D.AddForce (energyBall.transform.right * 5000);

This code assumes the ‘forward’ of your sprite is the right side. It would take a bit of fixup if the ‘forward’ of your sprite is the ‘up’ side.

So for 2D games I’ve found to get the world position of the mouse is really simple! Just use the code below! The only issue with this code is that when the bullet reaches the mouse it stops… i quickly came up with this code and am going to to figuring out how to fix it. I’m assuming it has something to do with the “Vector2.MoveTowards” part.

using UnityEngine;
using System.Collections;

public class BulletBehaviors : MonoBehaviour {
	public Vector2 mousePosition;
	public float bulletSpeed;
	private float step;


	// Use this for initialization
	void Start () {
		mousePosition = Camera.main.ScreenToWorldPoint (Input.mousePosition);
	}
	
	// Update is called once per frame
	void Update () {
		step = bulletSpeed * Time.deltaTime;

		transform.position = Vector2.MoveTowards (transform.position, mousePosition, step);
	}
}