Hi I have a script that should find point in 2D world space that is not visible from main camera. For example (red):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnCamera : MonoBehaviour
{
private GameObject cam;
public GameObject prefab;
private Vector3 playerObjectLocation = new Vector3(0, 0, 0);
// Start is called before the first frame update
void Start()
{
cam = GameObject.FindGameObjectWithTag("MainCamera");
InvokeRepeating("spawnEnemy", 2.0f, 1.0f);
}
private Vector3 getCornerWorldCoords()
{
Vector3 pos = cam.GetComponent<Camera>().ScreenToWorldPoint(new Vector3(0, 0, 1));
pos[2] = 0;
return pos;
}
private float calculateDistance()
{
Vector3 cornerPosition = getCornerWorldCoords();
float sq_x = Mathf.Pow(cornerPosition[0] - playerObjectLocation[0], 2);
float sq_y = Mathf.Pow(cornerPosition[1] - playerObjectLocation[1], 2);
return Mathf.Sqrt(sq_x + sq_y);
}
private Vector3 getSpawnPointOutOfCameraWithRandomAngle(float lengthFactor = 1.0f)
{
float radius = calculateDistance() * lengthFactor;
float angle = Random.Range(0, 360);
float x = radius * Mathf.Sin(Mathf.PI * 2 * angle / 360);
float y = radius * Mathf.Cos(Mathf.PI * 2 * angle / 360);
return new Vector3(x, y, 0);
}
private void spawnEnemy()
{
Vector3 spawnPoint = getSpawnPointOutOfCameraWithRandomAngle();
//Vector3 pos = Camera.main.ScreenToWorldPoint();
//Debug.Log(pos);
GameObject.Instantiate(prefab, spawnPoint, cam.transform.rotation, null);
}
// Update is called once per frame
void Update()
{
}
}
I assume that bottom left corner is point (0, 0) in camera view. I get world position of point (0, 0), and then calculate distance between center of world grid and corner (multipled by float to determine how far from screen border should object be spawned). Then I calculate point on circle which should be out of camera view or should be one of the corners of screen. But when I instantiate prefab it is spawned on black circle.
Does anyone see any issue in this script, that make this script instantiate objects to close to center?
Thanks.