Bullets firing behind target and not what's in the way

I’m having an issue with my bullet system. When the bullet fires, it doesn’t go to what’s in the way of the camera’s lookvector.

I’ve tried changing up the code a lot but nothing seems to work. I create 2 rays but it still doesn’t work.

GIF: https://gyazo.com/06782ad38fc57af2e4e860d5115a1562

Code for firing the bullet:


local endpos = nv
local ray = newray(Cam.CFrame.p, Cam.CFrame.lookVector * 999)
local h,p,n = workspace:FindPartOnRay(ray, Character)
local startpos = Cam.CFrame.p
local r = newray(startpos, (p - startpos))
local _,pos = workspace:FindPartOnRayWithWhitelist(r, {Character})
endpos = p
				
print("dist from "..tostring(h)..": "..tostring((endpos - Cam.CFrame.p).magnitude))
				
local data = {
	StartPosition = t.Muzzle.Position,
	TargetPosition = endpos,
	Direction = (pos-startpos).unit,
	BulletType = self.data.BulletType,
	Speed = self.data.BulletSpeed,
	Damage = self.data.Damage,
	Player = Player,
	Character = Player.Character,
	Model = t,
}
Bullet.new(data)

Code that moves the bullet:


function self.step(dt)
			
	local f = 1 * speed
	local newpos = self.position + v3(direction.x * (dt * (f)), direction.y * (dt * f), direction.z * (dt * f)) * speed
	self.oldpos = self.position
	self.position = newpos
	local hit, pos, norm, collided = self.getcollision()
	local distance = (self.position - startpos).magnitude
	if not collided and distance <= 1000 then
		attach0.CFrame = cf(newpos)--* cf(0, 0.15, 0) 
		attach1.CFrame = cf(newpos)* cf(0, -0.3, 0)
	elseif collided and distance <= 1000 then
		self.onhit(hit, pos, norm)
		self:destroy()
	else
		--self.onhit(hit, pos)
		self:destroy()
	end
end

If you can, please help!