Why won't my bullets accurately shoot in my mouse's direction?

124351-bm2.gif

As you can see from the image above, sometimes the bullet doesn’t fire in the mouse’s direction. What might be the cause of this problem? Below are the code I used for reference:
(For the movement)

  void Start () {
        target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    }
 
    void Update () {
        Vector3 velocity = new Vector3(Mathf.Sign(target.x), Mathf.Sign(target.y), Mathf.Sign(target.z)).normalized * speed;
        transform.Translate(velocity * Time.deltaTime, Space.World);
    }

For instantiating the bullets:

GameObject bullet= Instantiate(Bullet, gun.transform.position, Quaternion.Euler(gun.transform.eulerAngles));

Heyo!

Alrighty, so I think I figured out what the issue is. Unless you have some reason for using Mathf.Sign here, I don’t think it is necessary. That appears to be messing up your calculations causing this strange behavior. What you could do is inside of your start, where you calculate target, calculate the vector from the bullet’s initial position (or the bullet spawner, whatever you want) to the mouse position. Destination Vector - Origin Vector gives you the vector pointing from the origin to the destination. Sooo, you could use this to find the vector from projectile to the mouse, normalize that, and multiply it by your speed like this:

target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
velocityDirection = (target - transform.position).normalized;

// ...

Vector3 velocity = velocityDirection * speed;

Hopefully that solves your issue! Let me know if not.

You really should not calculate bullet direction inside bullet script, do it instead in your “Spawner”, then pass direction vector to your newly created bullet instance (make a public method inside bullet, smt like

public void SetDirection(Vector3 point) 
{
    this.direction = point - transform.position;
}

Note that direction vector should be a mouse position - bullet position

or you can pass ready direction vector:

var bullet = Instantiate(bulletPrefab);

Vector3 dir = (mousePosition - bullet.transform.position).normalized;

bullet.SetDirection(dir);

...

inside bullet:

void Update() {
    transform.Translate(this.direction * speed);
}