PcoWSkbVqDnWTu_dm2ix
Hit Detection with Lasers
Part 1 - Hit Detection with Lasers
Hit Detection with Lasers
Part 1 - Hit Detection with Lasers

In this course, you’ll learn how to cast a laser from the blaster in Creating Player Tools and detect whether or not it hits a player.

Raycasting to Find Collisions

Raycasting creates an invisible ray from a start position towards a given direction with a defined length. If the ray collides with objects or terrain in its path, it will return information on the collision such as the position and the object it collided with.

Raycast from A towards B colliding with a wall

Finding the Mouse Location

Before a laser can be shot, you must first know where the player is aiming. This can be found by raycasting from the player’s 2D mouse location on the screen directly forwards from the camera into the game world. The ray will collide with whatever the player is aiming at with the mouse.

  1. Open the ToolController script inside the Blaster tool from Creating Player Tools. If you haven’t completed that course yet you can download the Blaster model and insert it into StarterPack.

    Models can be added into your Inventory to be used between any game.

    1. In a browser, open the model page, click the Get button. This adds the model into your inventory.
    2. In Studio, go to the View tab and click on the Toolbox.
    3. In the Toolbox window, click on the Inventory button. Then, make sure the dropdown is on My Models.
    4. Select the Blaster model to add it into the StarterPack.

  2. At the top of the script, declare a constant named MAX_MOUSE_DISTANCE with a value of 1000.

  3. Create a function called getWorldMousePosition.

    local tool = script.Parent
    
    local MAX_MOUSE_DISTANCE = 1000
    
    local function getWorldMousePosition()
     
    end
    
    local function toolEquipped()
        tool.Handle.Equip:Play()
    end
    
    local function toolActivated()
        tool.Handle.Activate:Play()
    end
    
    -- Connect events to appropriate functions
    tool.Equipped:Connect(toolEquipped)
    tool.Activated:Connect(toolActivated)
  4. Use the GetMouseLocation function of UserInputService to get the player’s 2D mouse location on the screen. Assign this to a variable named mouseLocation.

    local UserInputService = game:GetService("UserInputService")
    
    local tool = script.Parent
    
    local MAX_MOUSE_DISTANCE = 1000
    
    local function getWorldMousePosition()
        local mouseLocation = UserInputService:GetMouseLocation()
    end

Now the 2D mouse location is known, its X and Y properties can be used as parameters for the Camera:ViewportPointToRay function, which creates a Ray from the screen into the 3D game world.

  1. Use the X and Y properties of mouseLocation as arguments for the ViewportPointToRay function. Assign this to a variable named screenToWorldRay.
    local function getWorldMousePosition()
        local mouseLocation = UserInputService:GetMouseLocation()
    
        -- Create a ray from the 2D mouse location
        local screenToWorldRay = workspace.CurrentCamera:ViewportPointToRay(mouseLocation.X, mouseLocation.Y)
    end

It’s time to use the Raycast function to check if the ray hits an object. This requires a start position and direction vector: in this example, you will use the origin and direction properties of screenToWorldRay.

The length of the direction vector determines how far the ray will travel. The ray needs to be as long as the MAX_MOUSE_DISTANCE, so you’ll have to multiply the direction vector by MAX_MOUSE_DISTANCE.

  1. Declare a variable named directionVector and assign it the value of screenToWorldRay.Direction multiplied by MAX_MOUSE_DISTANCE.
    local function getWorldMousePosition()
        local mouseLocation = UserInputService:GetMouseLocation()
    
        -- Create a ray from the 2D mouseLocation
        local screenToWorldRay = workspace.CurrentCamera:ViewportPointToRay(mouseLocation.X, mouseLocation.Y)
    
        -- The unit direction vector of the ray multiplied by a maximum distance
        local directionVector = screenToWorldRay.Direction * MAX_MOUSE_DISTANCE
  2. Call the Raycast function of workspace, passing the Origin property of screenToWorldRay as the first argument and directionVector as the second. Assign this to a variable named raycastResult.
    local function getWorldMousePosition()
        local mouseLocation = UserInputService:GetMouseLocation()
    
        -- Create a ray from the 2D mouseLocation
        local screenToWorldRay = workspace.CurrentCamera:ViewportPointToRay(mouseLocation.X, mouseLocation.Y)
    
        -- The unit direction vector of the ray multiplied by a maximum distance
        local directionVector = screenToWorldRay.Direction * MAX_MOUSE_DISTANCE
    
        -- Raycast from the ray's origin towards its direction
        local raycastResult = workspace:Raycast(screenToWorldRay.Origin, directionVector)

Collision Information

If the raycast operation finds an object hit by the ray, it will return a RaycastResult, which contains information about the collision between the ray and object.

RaycastResult Property Description
Instance The BasePart or Terrain cell that the ray intersected.
Position Where the intersection occurred; usually a point directly on the surface of a part or terrain.
Material The material at the collision point.
Normal The normal vector of the intersected face. This can be used to determine which way the face is pointing.

The Position property will be the position of the object that the mouse is hovering over. If the mouse isn’t hovering over any object within a distance of MAX_MOUSE_DISTANCE, raycastResult will be nil.

  1. Create an if statement to check whether raycastResult exists.
  2. If raycastResult has a value, return its Position property.
  3. If raycastResult is nil then find the end of the raycast. Calculate the 3D position of the mouse by adding screenToWorldRay.Origin and directionVector together.
local function getWorldMousePosition()
    local mouseLocation = UserInputService:GetMouseLocation()
   
    -- Create a ray from the 2D mouseLocation
    local screenToWorldRay = workspace.CurrentCamera:ViewportPointToRay(mouseLocation.X, mouseLocation.Y)
   
    -- The unit direction vector of the ray multiplied by a maximum distance
    local directionVector = screenToWorldRay.Direction * MAX_MOUSE_DISTANCE
   
    -- Raycast from the ray's origin towards its direction
    local raycastResult = workspace:Raycast(screenToWorldRay.Origin, directionVector)
   
    if raycastResult then
        -- Return the 3D point of intersection
        return raycastResult.Position
    else
        -- No object was hit so calculate the position at the end of the ray
        return screenToWorldRay.Origin + directionVector
    end
end

Next Page Firing Towards the Target