How to Make a Character Follow the Mouse Pointer in a 3D Game

How to Make a Character Follow the Mouse Pointer in a 3D Game

If you're building a 3D game and want to control your character by making it follow the mouse pointer, you'll need to convert the mouse position from screen coordinates to world coordinates. One way to do this is to use the Camera.ScreenToWorldPoint method, which takes a screen position and a depth value, and returns the corresponding position in world coordinates.

Here's some example code that demonstrates how to use ScreenToWorldPoint to make the character follow the mouse pointer:

Vector3 mousePosition = Input.mousePosition;

//Change the mouse position to the world's coordinates
mousePosition = Camera.main.ScreenToWorldPoint(new Vector3(mousePosition.x, mousePosition.y, 10));

// Update the character's position to follow the mouse
transform.position = Vector3.Lerp(transform.position, mousePosition, 6 * Time.deltaTime);


This code converts the mouse position to world coordinates, and then uses the Lerp function to smoothly move the character towards the mouse position over time.

By following these steps, you can easily make your character follow the mouse pointer in your 3D game. Good luck with your development!