- Home /
How do I keep bullet speed fixed while keeping its travelling rotation? (2D Topdown)
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;
}
}
}
Answer by Whitewalkergp · Mar 05 at 07:43 AM
maybe it is because you are using
relativeship = camera.transform.InverseTransformDirection(mousepos - camera.transform.position);
and the relativeship is depended on mousepos(Mouse Position) and it also effects your bullet speed.
Your answer

Follow this Question
Related Questions
how to have bullets produce particles? 2 Answers
RayCast Shooting And Errors 1 Answer
How to detect which player shot the bullet? 1 Answer
Firing different bullets 2 Answers
bullets flying through enemy 1 Answer