LinearVelocity not going towards accurate mouse position

Hey guys, so I am making a laser gun, but when I shoot a bullet, the linear velocity goes backwards. I tried making the values negative, but still doesn’t achieve any accuracy. Here is my code:

local tool = script.Parent
local fire = tool.Handle.Fire
local hitFade = tool.Handle.HitFade
local reload = tool.Handle.Reload

local function main(player, location)
	local bullet = Instance.new("Part")
	bullet.BrickColor = BrickColor.new("Toothpaste")
	bullet.Material = Enum.Material.Neon
	bullet.Size = Vector3.new(0.1, 0.1, 0.5)
	bullet.Position = 	tool.Handle.Position
	local cf = CFrame.lookAt(bullet.Position, Vector3.new(location.X, location.Y, bullet.Position.Z))
	bullet.CFrame = cf
	bullet.CanCollide = false
	bullet.Parent = workspace
	
	local attachment = Instance.new("Attachment")
	attachment.Parent = bullet
	
	local lv = Instance.new("LinearVelocity")
	lv.Attachment0 = attachment
	lv.MaxForce = math.huge
	lv.VectorVelocity = Vector3.new(cf.X, cf.Y, cf.Z)
	lv.Parent = bullet
	
	bullet.Touched:Connect(function(hit)
		if hit.Parent:FindFirstChildWhichIsA("Humanoid") and hit.Parent ~= player.Character then
			local highlight = Instance.new("Highlight")
			highlight.FillTransparency = 0
			highlight.FillColor = Color3.fromRGB(0, 255, 255)
			highlight.Parent = hit.Parent
			hitFade:Play()
			for i = 0, 1, 0.1 do
				highlight.FillTransparency = i
				task.wait(0.1)
			end
			highlight:Destroy()
			hit.Parent.Humanoid:TakeDamage(100)
		end
	end)
	
	fire:Play()
	tool.Enabled = false
	task.wait(3)
	tool.Enabled = true
	reload:Play()
end

tool.HyperLaserEvent.OnServerEvent:Connect(main)

P.S: location is a value that I got from UserInputService:GetMouseLocation()

And some footage as well:
robloxapp-20240209-1105150.wmv (1.3 MB)

2 Likes

you need to calculate the direction vector from the bullet’s position to the target location and use that to set the velocity

local direction = (location - bullet.Position).unit
lv.VectorVelocity = direction * bulletSpeed -- Adjust bulletSpeed as needed

the location is a vector2, so it will error. did you read the full post?

2 Likes

guys, the location variable is a Vector2! keep that in mind!

1 Like