Search Unity

Question Need Help with Raycasting

Discussion in 'Visual Scripting' started by anmicgriff, Jan 20, 2021.

  1. anmicgriff

    anmicgriff

    Joined:
    Dec 28, 2020
    Posts:
    1
    I'm trying to make a script to aim a projectile with raycasting, and I've watched several tutorials and I just don't see what I'm doing wrong. You can see in the image below where it's stopping. The bottom bit is creating a ray with a game object set as the origin and the mouse position as the direction. I click on the asteroid and nothing happens. If anyone could help I'd be super thankful, I'm completely out of ideas. battlepack08_risen.png
     
  2. mintman

    mintman

    Joined:
    Nov 28, 2013
    Posts:
    4
    The mouse position is where the mouse is in the Screen Space for the game. (That is, the point of the mouse within the window used by the game, measured from the bottom left corner.) So - it returns a value that isn't related to the camera or the camera's position in the world in any way. It also has no depth.

    You'll need to use Camera.ScreenToWorldPoint to transform the 2D screen-space position to 3D. Additionally, you'll need to add the Camera's Forward Vector (multiplied by some suitable distance that moves the point beyond the ship) to get a point that isn't directly on the camera's surface. (Alternatively, you can set a Z value on the screen-space position of the mouse prior to putting it into ScreenToWorldPoint.)

    There is also a direct raycast that you can do from the camera: Camera Rays. I could imagine a situation where you raycast from the camera to get the point on the surface of the asteroid, and then create a ray that goes from the ship to *that* point. You would need a direction, so you can use AsteroidSurfacePoint - RayOrigin (Vector subtract) to get it.
     
    anmicgriff likes this.