How to get the CFrame hit of a ray

Hello, I am trying to create a Third Person gun script, and the way I planned to create the bullet would be like this:

  • Cursor is locked center, but for mobile players I have to use a ray created from the center of the Camera object and cast it into workspace

  • I’d check to see where the CFrame/Vector3 of the ray from the camera hit (This is where the problem is)

  • Create a new ray from the barrel of the gun to the spot on the map where the camera ray hit

  • After that, I’d be good to go on creating a bullet following the path of the ray from the ballel to the hitpos.

The problem is that, I don’t know how to get the CFrame of the camera ray in workspace. What I mean by this is that, If there’s a way to call FindPartOnRay but return the CFrame of the hit rather than the object the ray hit, that’d be very helpful. Any other ideas on how I can do this, or if it’s not an option, how can I get around it?

Visual representation:

To be honest, it feels hacky at the moment :stuck_out_tongue: Any suggestions?

4 Likes

Do you think ViewPortPointToRay would help? You give it a point on the screen viewport and it converts it to a ray with a “length” of 1.

So I’m not 100% if this is what you’re asking, but :FindPartOnRay will give you 4 values that you can read: Object, Position, Normal, and Material. The object is the object the ray hit (if there was one), position is the Vector3 position of the hit or the end of the ray if there’s no hit, normal is the Vector3 direction of the surface that the ray hit, and material is the terrain material that was hit.

You can acquire these values like this:

local Hit, Position, Normal, Material = workspace:FindPartOnRay(...)

http://wiki.roblox.com/index.php?title=API:Class/Workspace/FindPartOnRay

12 Likes

Adding on, you can use the second value (the position) to create a CFrame if you didn’t know already. [CFrame.new(Position)]

3 Likes

Ah - Stupid mistake, I should’ve checked the object browser so i’d know findpartonray gave the vector of the ray hit. Thank you for pointing that out.

1 Like
CFrame.new(pos,pos+norm)

In your case however you can just keep a saved bullet direction and move forward by step*direction

1 Like