- Home /
Bullet slightly off correct trajectory to mouse position
The game is a 2d sidescroller in a 3d environment. All collidable objects are put on the same z-axis position which is 0 in this case.
if(Input.GetButtonDown ("Fire1")) {
Rigidbody instantiatedProjectile = (Rigidbody)Instantiate(projectile,transform.position, transform.rotation);
// get target in world space, at same distance from camera:
Vector3 targetScreenPos = Input.mousePosition;
var targetPosition = Camera.main.ScreenToWorldPoint(targetScreenPos);
// calculate direction & velocity:
Vector3 targetDelta = (targetPosition-transform.position);
Vector3 launchVelocity = targetDelta.normalized * speed;
launchVelocity.z = 0;
instantiatedProjectile.velocity = launchVelocity;
The bullet currently goes in the same general direction as the mouse when fired but is slightly off from the mouse position.
A three ideas: For ScreenToWorldPoint(), the 'Z' parameter is the distance in front of the camera to calculate the position. You are leaving at 0 rather than the distance in front of the camera to the target.
Second idea: On line 12, you are setting the launchVelocity.z to 0, which may mess up your aim depending on the geometry of your game. A more typical solution to the ai$$anonymous$$g problem is to do:
instantiatedProjectile.transform.LookAt(targetPosition);
launchVelocity = instantiatedProjectile.transform.forward * speed;
or even:
instantiatedProjectile.transform.LookAt(transformPosition);
instantiatedProjectile.AddForce(instantiatedProjectile.transform.forward * some_force_factor);
Last idea: If you have gravity turned on in Rigidbody, then the projectile will drop as it travels and hit below your target.