I’ve been trying to make a raycast fire in the mouse’s 2d position, but I can’t figure out how and where to start. Here is the ray and part code. For example, I want the ray’s z axis (or what its called) to always be the player’s hat’s handle position, and I only want the ray’s y and x axis to change.
You can either use Mouse.Hit, or use your own Raycast like so:
local userInput = game:GetService("UserInputService")
local cam = workspace.CurrentCamera
-- Get mouse position:
local mousePos = userInput:GetMouseLocation()
-- Get the ray from the mouse and project it forward:
local mouseRay = cam:ViewportPointToRay(mousePos.X, mousePos.Y)
mouseRay = Ray.new(mouseRay.Origin, mouseRay.Direction * 1000)
-- Cast the ray:
local target, hit = workspace:FindPartOnRay(mouseRay)
This will cast a Ray based off of the relativity between the camera viewport to mouse 2d position. Doing it custom like this allows for more options later on, such as whitelisting/blacklisting objects, and applying randomness.
I’m a little bit confused by what you mean by lock the Z axis. The origin of the Ray will always be the head’s position the way you are doing it.
If you want to set one of the axis of the LookVector to stay locked to the character’s, you can just set it to the according LookVector value of the Character’s HumanoidRootPart.
UnitDirection = (mouse.p -player.Character.Hat.Handle.Position).Unit
Direction = Vector3.new(UnitDirection.X, UnitDirection.Y, HumanoidRootPart.CFrame.LookVector.Z) -- sets Z direction to HumanoidRootPart CFrame LookVector
local UnitRay = Ray.new(player.Character.Hat.Handle.Position, Direction * 100)
Im trying to make the ray’s z axis (or what its called) to always be the player’s hat’s handle position, and I only want the ray’s y and x axis to change. Mouse.Hit.p, changes in every axis, so i want to know where i could start to only calculate the x and y
I just went with the method he used in the original post for simplicities sake. While this is the correct format, we are just trying to help him understand the math here.