Hi all. Just wanted some advice as to how I should best handle this?
I essentially have various spawners off camera, spawning objects. I’m trying to figure out how I can direct these objects towards the cameras viewport. Moving them isn’t the problem, but I’m struggling with the coordinates and at the moment they spawn and fire off in seemingly random directions. I’m afraid I’m unable to post my current code at the moment but will do so when I get the chance. I’ve been playing around with various methods such as Camera.main.ViewportToWorldPoint but all attempts have failed in a similar fashion. Any help would be appreciated.
Shoot a ray with a random screen point out from the camera and move towards the impact point?
Thanks for the reply. This is what I’m attempting but for some reason the ray doesn’t get drawn on screen.
heading = new Vector3(Random.Range(0, Screen.width), Random.Range(Screen.height, 0));
Ray ray = Camera.main.ScreenPointToRay(heading);
Debug.DrawRay(ray.origin, ray.direction * 1000, Color.yellow, 100f);
EDIT: I managed to get the raycasting to work with this:
float randomX = Random.Range(0.05f, 0.95f);
float randomY = Random.Range(0.05f, 0.95f);
Ray ray = Camera.main.ScreenPointToRay(new Vector3(randomX * Camera.main.pixelWidth, randomY * Camera.main.pixelHeight, 10f));
I now face the problem of determining the Vector2 for the point that has been “hit” on the screen.
I was operating under the assumption your game was 3D, and you’re trying to get your monsters to move somewhere along terrain or something like that. Is your game 2D?
Doh, that’s my fault entirely. My game is 2D, thought I had mentioned that. Apologies
This should work then:
Camera camera = Camera.main;
Vector3 randomScreenPosition = new Vector3(Random.Range(0f, camera.pixelWidth), Random.Range(0f, camera.pixelHeight), camera.nearClipPlane);
Vector3 randomWorldPosition = camera.ScreenToWorldPoint(randomScreenPosition);
(Typed it here, there may be syntax errors)