I'm in the process of creating a 2D game where the player needs to click to shoot. Wherever the mouse cursor is on the screen is the direction to which the projectile will move. I was able to get the projectile to instantiate and to the mouse location, but the projectile follows the mouse which is not what I want.
public class LetterController : MonoBehaviour {
private List<GameObject> letters = new List<GameObject>();
public GameObject letterPrefab;
public float letterVelocity;
// Use this for initialization
private void Start()
{
}
// Update is called once per frame
void Update ()
{
Vector3 direction = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if (Input.GetMouseButtonDown(0))
{
GameObject letter = (GameObject)Instantiate(letterPrefab, transform.position, Quaternion.identity);
letters.Add(letter);
}
for (int i = 0; i < letters.Count; i++)
{
GameObject goLetter = letters[i];
if (goLetter != null)
{
goLetter.transform.Translate(direction * Time.deltaTime * letterVelocity );
Vector3 letterScreenPosition = Camera.main.WorldToScreenPoint(goLetter.transform.position);
if (letterScreenPosition.y >= Screen.height + 10 || letterScreenPosition.y <= -10 || letterScreenPosition.x >= Screen.width + 10 || letterScreenPosition.x <= -10)
{
DestroyObject(goLetter);
letters.Remove(goLetter);
}
}
}
}
}
I watched several YouTube videos and looked at a few Unity forums, but the solutions either gave me errors, or they gave me different problems like only shooting on one axis or shooting on the opposite axes