I’m trying to make a shooting script for my 2D game, but it’s not working. If the mousePos.x < playerPos.x the bullets just switch direction. I understand why this is happening, but I cannot find a fix. How can I make is so the bullets spawn with an initial unchanged speed and direction?
using UnityEngine;
using System.Collections;
public class bulletScript : MonoBehaviour {
public float bulletSpeed = 100f;
private Vector2 mousePos;
private Vector3 playerPos;
public GameObject bullet;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0)) {
Instantiate (bullet, playerPos, Quaternion.identity);
}
if (mousePos.x > playerPos.x) {
transform.position += Vector3.right * Time.deltaTime * bulletSpeed;
}
if (mousePos.x < playerPos.x)
{
transform.position += Vector3.left * Time.deltaTime * bulletSpeed;
}
mousePos = Camera.main.ScreenToWorldPoint(new Vector2(Input.mousePosition.x, Input.mousePosition.y));
playerPos = GameObject.Find ("squiddy").transform.position;
}
}