I’m trying to make a simple gun, but everyone seems to be using player:GetMouse() to do it. However, it’s a legacy function and not cross-platform. I think it deserves to get removed to stop people from using that disgusting function.
I’ve been trying to do the same with UserInputService for the past 3 hours ffs. And I still can’t figure out how to do it.
local raycastResult = workspace:Raycast(self._gunTip.Position, unitRay.Direction, raycastParams)
if raycastResult then
if raycastResult.Instance.Parent:FindFirstChildOfClass("Humanoid") ~= nil then
local humanoid = raycastResult.Instance.Parent:FindFirstChildOfClass("Humanoid")
humanoid:TakeDamage(self.DamagePerBullet)
end
end
I have this code, with unitRay being the ray from Camera:ScreenPointToRay(). It’s not working because the unitRay.Direction is somewhere random. And I don’t know anything about that function nor math with Vector3.
The definition of a unit ray is a ray with a magnitude of 1. You need to lengthen the ray to the range of the gun. You can do so with scalar multiplication: unitRay.Direction * RANGE.
self.MouseConnectionBegan = UserInputService.InputBegan:Connect(function(input: any, gameProcessedEvent: bool)
if input.UserInputType == Enum.UserInputType.MouseButton1 then
local mouseX, mouseY = input.Position.X, input.Position.Y
local unitRay = camera:ScreenPointToRay(mouseY, mouseY)
GunService:Shoot(unitRay)
end
end)
It would be useful to know what “not working” means. You should print out what the raycast is hitting or if it is hitting anything at all. It might also be useful to describe what you want it to do. Is this a first person system? Do you want the bullet to go straight out of the gun or do you want it to shoot at a specific point?
(also, yes, the input object does give you the mouse position)
Yeah, that makes sense. It would probably hit if you move the mouse to the left more.
What you probably want to do is either raycast from the gun in the direction the gun is facing OR raycast from the camera in the direction of the camera.
What you are currently doing is raycasting from the gun in the direction of the camera, which is going to go off to the right of the mouse and the right of where the gun is facing.
It sounds like you may have a bug elsewhere. You should put some print statements in various places to make sure each section of the code you expect to execute is actually getting executed. Make sure the raycast is actually occurring, then check that the raycast can hit things (make a big wall that you can’t miss and shoot at that). That should narrow down the problem.