Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Move object in direction of random point within camera viewport

Discussion in 'Scripting' started by Flynn_Prime, Oct 1, 2021.

  1. Flynn_Prime

    Flynn_Prime

    Joined:
    Apr 26, 2017
    Posts:
    383
    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.
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
  3. Flynn_Prime

    Flynn_Prime

    Joined:
    Apr 26, 2017
    Posts:
    383
    Thanks for the reply. This is what I'm attempting but for some reason the ray doesn't get drawn on screen.
    Code (CSharp):
    1.         heading = new Vector3(Random.Range(0, Screen.width), Random.Range(Screen.height, 0));
    2.         Ray ray = Camera.main.ScreenPointToRay(heading);
    3.         Debug.DrawRay(ray.origin, ray.direction * 1000, Color.yellow, 100f);
    EDIT: I managed to get the raycasting to work with this:
    Code (CSharp):
    1.         float randomX = Random.Range(0.05f, 0.95f);
    2.         float randomY = Random.Range(0.05f, 0.95f);
    3.         Ray ray = Camera.main.ScreenPointToRay(new Vector3(randomX * Camera.main.pixelWidth, randomY * Camera.main.pixelHeight, 10f));
    4.  
    I now face the problem of determining the Vector2 for the point that has been "hit" on the screen.
     
    Last edited: Oct 2, 2021
  4. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    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?
     
  5. Flynn_Prime

    Flynn_Prime

    Joined:
    Apr 26, 2017
    Posts:
    383
    Doh, that's my fault entirely. My game is 2D, thought I had mentioned that. Apologies
     
  6. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    This should work then:
    Code (csharp):
    1.  
    2. Camera camera = Camera.main;
    3.  
    4. Vector3 randomScreenPosition = new Vector3(Random.Range(0f, camera.pixelWidth), Random.Range(0f, camera.pixelHeight), camera.nearClipPlane);
    5. Vector3 randomWorldPosition = camera.ScreenToWorldPoint(randomScreenPosition);
    6.  
    (Typed it here, there may be syntax errors)