I have this scripts, that is a weapon that shots prefabs bullets, but all work correclty in the main, camera, when i reach the boss and the camera switches to him (his room in total) the gun dissapears and doesnt shoot. I found the problem in this line of code:
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position
It only works under the main camera. How can i alter it slighly to work under any camera i have in the game? been trying usuccesful, probably to simple and right down my nose but cant find it… please help me sorry english is not my native language
public GameObject projectile;
public Transform shotPoint;
public Animator camAnim;
public int rotationOffset;
public float shotDelay;
public float shotDelayCounter;
private void Update()
{
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotZ + rotationOffset);
if(Input.GetMouseButtonDown(0))
{
camAnim.SetTrigger("shake");
Instantiate(projectile, shotPoint.position, transform.rotation);
shotDelayCounter = shotDelay;
}
if(Input.GetMouseButton(0))
{
shotDelayCounter -= Time.deltaTime;
if(shotDelayCounter <= 0)
{
shotDelayCounter = shotDelay;
Instantiate(projectile, shotPoint.position, transform.rotation);
}
}
}
}
The “dirty way”: Finding the camera when the main one is disabled
private Camera camera;
private Camera Camera
{
get
{
if( camera == null || !camera.gameObject.activeInHierarchy )
{
camera = Camera.main ;
// You may want another way to retrieve the correct camera
if( camera == null || !camera.gameObject.activeInHierarchy )
camera = FindObjectOfType<Camera>();
}
return camera;
}
}
private void Update()
{
Vector3 difference = this.Camera.ScreenToWorldPoint(Input.mousePosition) - transform.position;
// ...
}
The cleaner way: Using events
// In your boss manager script
public UnityEngine.Events.UnityEvent OnBossBattleStarted;
public UnityEngine.Events.UnityEvent OnBossBattleEnded;
private void StartBossBattle()
{
// Your code ...
Camera.main.gameObject.SetActive( false ) ;
BossCamera.gameObject.SetActive( true ) ;
if( OnBossBattleStarted != null )
OnBossBattleStarted.Invoke();
}
private void EndBossBattle()
{
// Your code ...
Camera.main.gameObject.SetActive( true) ;
BossCamera.gameObject.SetActive( false ) ;
if( OnBossBattleEnded != null )
OnBossBattleEnded.Invoke();
}
Then, in your player code
public Camera Camera
{
get; set;
}
private void Update()
{
Vector3 difference = this.Camera.ScreenToWorldPoint(Input.mousePosition) - transform.position;
// ...
}
Finally, add listeners to the OnBossBattleXXX events and assign the correct camera in your player script