2D Shooting to mouse position
I'm currently trying to get a bullet shooting towards mouse position, but nothing seems to work, I've tested almost every solution I found in tutorials or forums, but nothing helped... With some codes, the bullet flies, but not toward mouse position. From logic, the camera.main.ScreenToWorldPoint solution, which is mentioned in almost every post I've read, seems like a simple solution, but it just doesn't work.
Some of the scripts I tested(and which all didn't work): 1. http://answers.unity3d.com/questions/1101912/shoot-bullet-towards-mouse.html 2. http://answers.unity3d.com/questions/733840/2d-shoot-at-mouse-position-how-to-rotate-towards-t.html 3. https://www.youtube.com/watch?v=1KdS0QzyhCg
With camera.main.ScreenToWorldPoint, it returns (0.0, 0.0), the bullet flies always to one point; without camera.main.ScreenToWorldPoint the Debug.Log returns values which seem to be right, but the bullet still flies somewhere else (tested with script 1)
Answer by JesusAlex · Apr 25, 2016 at 12:15 PM
Did you put in brackets after, "(Input.mousePosition);?" This is one way of doing it:
using UnityEngine; using System.Collections;
public class GotoMouse : MonoBehaviour {
public float speed = 1.5f;
private Vector3 target;
void Start () {
target = transform.position;
}
void Update () {
if (Input.GetMouseButtonDown(0)) {
target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
target.z = transform.position.z;
}
transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612075557im_/https://answers.unity.com/themes/thub/images/avi.jpg)