Question by
Sorlaq · Nov 22, 2015 at 05:48 PM ·
2d gamemousepositiontopdownshootermovetowards
Shoot bullet towards mouse
Hi! I know that this question has been answered here million times, but I can't get any solution I found to work in my case. Please be aware, that I'm not very experienced in Unity and programming.
I'm trying to make 2D topdown shooter where you move with WASD and shoot with mouse, something like Alien Shooter and I don't know how to handle shooting mechanic. Now I'm using Vector2.MoveTowards to shoot bullet towards mouse cursor, but it just goes to point where cursor was when bullet was shot and stops there. My code looks like this:
Shooting:
using UnityEngine;
using System.Collections;
public class PlayerShoot : MonoBehaviour {
public bool ready = true;
public float cooldown;
public GameObject bullet;
void Update ()
{
if (Input.GetMouseButtonDown (0))
{
if (ready == true)
{
ready = false;
StartCoroutine (Recharge ());
Instantiate(bullet, transform.position, transform.rotation);
}
}
}
IEnumerator Recharge()
{
yield return new WaitForSeconds (cooldown);
ready = true;
}
}
Bullet contoller:
using UnityEngine;
using System.Collections;
public class FireballController : MonoBehaviour {
public float speed;
public float lifespan;
public Vector2 mousePosition;
void Start ()
{
StartCoroutine (Destroy ());
mousePosition = Camera.main.ScreenToWorldPoint(new Vector2 (Input.mousePosition.x, Input.mousePosition.y));
}
IEnumerator Destroy()
{
yield return new WaitForSeconds (lifespan);
Object.Destroy (this.gameObject);
}
void Update ()
{
transform.position = Vector2.MoveTowards (transform.position, mousePosition, speed);
}
}
Comment