How to shoot ray in straight line on mobile

I’ve been working on a weapon system lately and now I’m trying to make it compatible with mobile devices. Basically I used ContextActionService to bind a function on pc, and it creates a small button for mobile devices. When the player clicks the button on mobile it will shoot where there touch was.

image

Where I want the bullet to fly straight ahead from the muzzle instead of where they touched. I tried to detect if they have a mouse enabled using UserInputService and changing the direction that way but here’s what I got.

local success, err = pcall(function()
	fromP = handle.Muzzle.Position -- tip of gun pos
	toP = mouse.Hit.Position
end)

if success then
	local rayCastParams = RaycastParams.new() -- RayCast Settings
	rayCastParams.FilterType = Enum.RaycastFilterType.Blacklist
	rayCastParams.FilterDescendantsInstances = {character:GetChildren(), viewModel:GetChildren()} -- ignore parts
	rayCastParams.IgnoreWater = false
	
	local direction
	
	if userInputService.MouseEnabled then
		direction = (toP - fromP).Unit * config.Range
	else
		direction = fromP.Unit * config.Range -- bassically what to put here to make it go in a straight line
	end
	
	local result = workspace:Raycast(fromP, direction, rayCastParams)

You could try cloning the muzzle attachment(I Am Assuming It is An Attachment, If Not You Can Add One Where The Muzzle Is) And Move It Infront Of The Muzzle A Stud Or Two, Rename It To ‘Muzzle2’ And Then Replace The Line

direction = fromP.Unit * config.Range -- bassically what to put here to make it go in a straight line

With

direction = (handle.Muzzle2.WorldPosition - fromP).Unit * config.Range
1 Like

Assume that your have a muzzle, use the muzzle’s CFrame.LookVector multiplied by the range. If that doesn’t work, it’s otherwise a negative direction or either UpVector or RightVector, depending on muzzle’s orientation.

2 Likes