- Home /
Many cameras with Camera.main.ScreenToWorldPoint trouble.
Hey, I make a 2D game where you drive car and i based riding mechanics on Camera.ScreenToWorldPoint. I want to change camera when player rides off certain zone. When i added more than 1 camera the script stopped working and my car drive off somwhere. Can somone help?
Code: {
public Rigidbody2D rb;
public float sp;
private void Update()
{
Vector3 mspos = Input.mousePosition;
mspos = Camera.main.ScreenToWorldPoint(mspos);
Vector2 dr = new Vector2(
mspos.x - transform.position.x,
mspos.y - transform.position.y
);
transform.up = dr;
rb.AddForce(dr * sp);
}
}
Answer by xxmariofer · Jan 15, 2019 at 10:56 AM
Dont really understand the issue, but probably your problem is with Camera.main since thats only referencing the camera with the Camera Main tag assigned, if you want both cameras to work the same you need to pass both camera reference, not sure if that was the question.
Answer by Hellium · Jan 15, 2019 at 11:58 AM
As indicated in the documentation, Camera.main
returns the first enabled camera tagged "MainCamera". If you duplicated the Main Camera, you may have this kind of behaviour because Camera.main
retrieves the incorrect camera.
In order to fix this, you can declare a public Camera
and drag & drop the camera you want in the inspector. With this, you are sure the correct camera will be used (and performance will be improved, indeed, Camera.main
is a costly function)
public Rigidbody2D rb;
public float sp;
public Camera Camera; // Drag & drop the camera in the inspector
private void Update()
{
Vector3 mspos = Input.mousePosition;
mspos = Camera.ScreenToWorldPoint(mspos);
Vector2 dr = new Vector2(
mspos.x - transform.position.x,
mspos.y - transform.position.y
);
transform.up = dr;
rb.AddForce(dr * sp);
}
Your answer
Follow this Question
Related Questions
Smooth camera script looking at left hand side of character. 0 Answers
Main Camera child under player, causes flip 3 Answers
2D camera panning and can't click UI buttons 0 Answers
How to adjust camera position/rotation when player looks up or down? (Third Person Camera) 1 Answer
Problem with the camera, 2D. 0 Answers