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)
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:
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);
...