- Home /
How do I move camera towards the mouse while anchoring it to the player?
I'm making a 2d top-down space shooter game where you use the keyboard to move the player ship and the mouse to rotate the player. I currently have a main camera exactly follow the player, however I want the camera to move a bit forward in the direction of the mouse pointer. For example, if I put the mouse pointer near the bottom of the screen, the camera would slowly move down a bit.
I spent quite a bit of time trying to get this to work and this is what I currently have:
mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
moveTrans = Vector3.SmoothDamp(transform.position - player.transform.position, mousePos.normalized * Mathf.Clamp(Vector2.Distance(moveTrans, mousePos), -4f, 4f), ref velocity, 2f);
transform.position = Vector3.SmoothDamp(player.transform.position + transform.position, mousePos.normalized * Mathf.Clamp(Vector2.Distance(moveTrans, mousePos), -4f, 4f), ref velocity, 2f);
The above code makes the camera slowly move forward in the direction of my mouse pointer to a certain amount, which is what I want. However, the camera moves super, super fast and goes completely off screen when the player begins moving.
How do I make it so that it works when the player is also moving?
Your answer
Follow this Question
Related Questions
How do I invert mouse movement for a specific section of my game? 3 Answers
How to keep player in bounds? 1 Answer
How to create a cinemachine custom camera offset in the aiming direction 0 Answers
Shake problem when colliding to walls Top Down (via MousePos) 0 Answers
character shaking when it moves 0 Answers