I’m trying to shoot a bullet towards where I’m looking trough using my mouse cursors position, though the farther out I hold my mouse the faster my bullets travel. How could I make it so all my bullets travel at the same speed?
The code im using is:
public class BulletMove : MonoBehaviour
{
[SerializeField] private GameObject bullet;
[SerializeField] private GameObject ship;
[SerializeField] private GameObject camera;
public Vector3 mousepos = Input.mousePosition;
public Vector2 shippos = new Vector2();
public Vector3 relativeship = new Vector3();
void Start()
{
shippos = ship.transform.position;
mousepos = Input.mousePosition;
mousepos.x = mousepos.x - Screen.width / 2;
mousepos.y = mousepos.y - Screen.height / 2;
relativeship = camera.transform.InverseTransformDirection(mousepos - camera.transform.position);
}
// Update is called once per frame
void Update()
{
Vector2 newPos2 = bullet.transform.position;
newPos2.x = newPos2.x + (relativeship.x / 10f) * Time.deltaTime;
newPos2.y = newPos2.y + (relativeship.y / 10f) * Time.deltaTime;
bullet.transform.position = newPos2;
}
}
and my code to spawn(if it helps) the bullet is:
public class Shoot : MonoBehaviour
{
[SerializeField] private GameObject bullet;
[SerializeField] private GameObject ship;
[SerializeField] float cooldown = 1;
void Update()
{
cooldown -= (3f * Time.deltaTime);
if (Input.GetKey(KeyCode.Mouse0) && cooldown < 0f)
{
Vector2 newPosition = ship.transform.position;
GameObject shot = Instantiate(bullet, newPosition, ship.transform.rotation);
cooldown = 1f;
}
}
}