Shooting towards mouse cursor

Trying to have a mouse shoot the ball at the cursor in a top down 3d game (not 100% top down, closer to diagnal down).

There is a laser pointer on the player so you know where they are aiming, and they shoot along that laser pointer path.

This works initially:

Vector3 lookAt = camera1.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, (transform.position - camera1.transform.position).magnitude));
lookAt.y = this_laser_pointer.transform.position.y;
transform.LookAt(lookAt);

But when the player moves at all, they start looking up/down and the player angle is changed, which results in the aiming being off. The rotation constraints don’t seem to effect this. Is there a way to have lookAt result in only looking at that one axis to keep the player’s aim even?

This code corrects the player angle and aiming issues, but the player’s facing direction has a very hard time following the mouse cursor:

Vector3 lookAt = camera1.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, (transform.position - camera1.transform.position).magnitude));
lookAt.y = this_laser_pointer.transform.position.y;
motor.facingDirection = lookAt;

Thank you in advance.

maccabees linked code creates a ray you can use to do a raycast with.since your game camera is at an angle you need to somehow map the cursor position into the world in relation to the player. with the raycast you could for example hit the ground in front of the player, which gives you a better position to look at. this position, with the y value if the players position then aligns your aim with the player:

  • ScreenPointToRay
  • Physics.Raycast
  • result.y = player.position.y

that’s the steps

Thank you @hexagonius for the explanation.

I just found this answer on another forum which seems to work well:

Vector3 lookAt = camera1ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, (transform.position - camera_ball.transform.position).magnitude));
lookAt.y = this.transform.position.y;
 this.transform.LookAt(lookAt) ;

I was using the laser pointer y instead of the player y, and the lookat ignored the collision constraints of the rigidbody which was allowing the player’s rotation to go whacky.