I’ve got an issue with a projectile system of mine. Basically, you throw a ball, and it goes in the direction you’re aiming, right? I made this when my game was still forced first person, so it works fine for that. But, when you aim to far away whilst in first person, the throw goes off to the side.
I was, originally, using the camera’s CFrame position and LookVector for the throw. But, since this issue happened, I’ve been trying to make an accurate raycast alternative. I make it create a ray, but when I use CFrame.lookAlong with it’s direction, it can be inaccurate and go lower than expected. And when I use a raycast operation and get the result from that, it goes off sideways.
Here’s the code:
--script hidden because topic is solved
Any help is appreciated!
edit: bug is still here
edit 2: bug is still here so bump
By adjusting how the screen position converts to a 3D ray using ScreenPointToRay, the throw direction should now accurately follows the player’s aim
local function getThrowDirection(): CFrame
-- First, get a screen position to cast from
local posX: number?, posY: number?
if onPc then -- Use mouse location if on PC
local position: Vector2 = uis:GetMouseLocation()
posX = position.X :: number
posY = position.Y :: number
else -- Use label position if on mobile
local position: Vector2 = Vector2.new(420.200012, 164.700012)
posX = position.X :: number
posY = position.Y :: number
end
-- Convert the screen position to a 3D ray using the camera
local rayOrigin = workspace.CurrentCamera.CFrame.Position
local rayDirection = (workspace.CurrentCamera:ScreenPointToRay(posX, posY)).Direction
-- Perform a raycast to see if it hits something (optional, but useful for precision)
local raycastResult = workspace:Raycast(rayOrigin, rayDirection * 1000) -- Adjust the length as needed
if raycastResult then
-- Align the throw with the hit point (if there is any hit)
return CFrame.new(rayOrigin, raycastResult.Position)
else
-- If no hit, align with the ray direction
return CFrame.new(rayOrigin, rayOrigin + rayDirection)
end
end
The projectile fired quite low, but improved after I used ViewportPointToRay, it appears to be performing the same way as my code. I updated my own code and the projectile is more accurate, but it still seems to be a bit off-target.
It’d cause quite a lot of issues on mobile, so I just stick to a ray for now, or it doesn’t even need a ray; I’m trying to fix the raycasting for accuracy.
I used mouse before, and when I converted it I saw no behaviour difference.
I think it’s because the rotation is calculated from the cameras point of view. The camera is farther away, leading to less rotation than needed. Try calculating it from the player