Unity: How Do I Find The Point Of A Camera That Is A Certain Amount Of Units Away From A Player And Passes Through The Mouse?
I want to set the camera 7.5f units away from a player based on where the mouse is in relation to the player.
Warning: Before you answer the question or leave a reply, I ask that you view the picture that I put towards the end of the question so you have an idea of what I am asking for. It is a diagram in which "Point A" is where the camera should be. It is a "for instance," meaning it is an example of what could be an outcome of the mouse, player, and camera.
I found the distance between the mouse and the player:
//Distance: mouse -> player
D1 = Mathf.Sqrt(Mathf.Pow(mousePos.x - player.transform.position.x, 2)
+ Mathf.Pow(mousePos.z - player.transform.position.z, 2));
I set up the statement that will find the relation between the mouse and the player:
if(mousePos.x - player.transform.position.x >= 0)
{
CamX = //Put Code Here
}
if (mousePos.x - player.transform.position.x <= 0)
{
CamX = //Put code Here
}
if (mousePos.z - player.transform.position.z >= 0)
{
CamZ = //Put Code Here
}
if (mousePos.z - player.transform.position.z <= 0)
{
CamZ = //Put Code Here
}
Here are the variables that I am using:
private float D1;
private float D2;
private float D3;
private float CamX;
private float CamZ;
Here is the section of code that I am working on. Don't take it as my full work for it is merely a brainstorm of code:
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
mousePos = new Vector3(hit.point.x, 0.8f, hit.point.z);
//Distance: mouse -> player
D1 = Mathf.Sqrt(Mathf.Pow(mousePos.x - player.transform.position.x, 2)
+ Mathf.Pow(mousePos.z - player.transform.position.z, 2));
if(mousePos.x - player.transform.position.x >= 0)
{
CamX = //Put Code Here
}
if (mousePos.x - player.transform.position.x <= 0)
{
CamX = //Put code Here
}
if (mousePos.z - player.transform.position.z >= 0)
{
CamZ = //Put Code Here
}
if (mousePos.z - player.transform.position.z <= 0)
{
CamZ = //Put Code Here
}
//Distance: mouse -> camera
D2 = D1 + 7.5f;
//Distance: player -> camera
D3 = Mathf.Sqrt(Mathf.Pow(player.transform.position.x - CamX, 2)
+ Mathf.Pow(player.transform.position.x - CamZ, 2));
...
My Diagram
Here is a picture diagraming how I want everything to be positioned
My question is this:
How can I find the position of the camera (point(CamX, CamZ)) that is 7.5f units away from the player and passes through the coordinates of the mouse (point(mousePosX, mousePosZ)).
Your answer
![](https://koobas.hobune.stream/wayback/20220612145456im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How I can make my camera keep a distance between two objects? 0 Answers
Modify Draw Distance via Script? 1 Answer
Change Camera postion 1 Answer
Spawning 1 second away from a position 0 Answers
How to change camera on Android? 1 Answer