Making a bullet spawn from a certain point while maintaining it's direction

In my game, I send the center of the screen to the server and fire projectiles based off of that.
Client

local currentCamera = workspace.CurrentCamera
local VIEWPORT_SIZE = currentCamera.ViewportSize
local unitRay = currentCamera:ViewportPointToRay(VIEWPORT_SIZE.X / 2, VIEWPORT_SIZE.Y / 2)
module.abilityEvent:FireServer("PrimaryFire", {unitRay.Direction, unitRay.Origin})

The server then handles the damage dealing and fires an event to the clients to handle the projectile.

Server

local simBullet = myCaster:Fire(origin, direction, weaponAttributes["Bullet_Speed"], CastBehavior)
RS.Remotes.visualEffect:FireAllClients({'ViviPrimary', myPlayer, origin, direction, weaponAttributes["Bullet_Speed"], weaponAttributes["Max_Distance"], myBools["Enchantment"]})

Client

myCaster:Fire(origin,direction,soeed,castBehaviour)

This is fine for actual gameplay, as the bullets go exactly where I want them to.
https://i.gyazo.com/b10600959ce12945fbedae9817ee23f6.gif

However visually I would want the bullet to spawn from somewhere else while still going in the same location. (For the example I would like it to spawn from the character’s right hand) However when I do this it messes up the trajectory. How would I be able to do this so it’s still accurate to what’s actually happening on the server?
https://i.gyazo.com/24dc369e9ab6e5b68670ccc3ea891014.gif

I am also using Fastcast if that plays into anything.

2 Likes

First we need to find the focal point. This can be done by casting a ray at the mouse’s location and getting its hit position. If it doesn’t hit anything, we can calculate it using the unit ray:

local unitRay = currentCamera:ViewportPointToRay(VIEWPORT_SIZE.X / 2, VIEWPORT_SIZE.Y / 2)
--raycast 1000 studs in front of the camera
local hitscan = workspace:Raycast(unitRay.Origin, unitRay.Direction*1000)
--default to 1000 studs in front if the ray hits nothing; otherwise use the hit position
local focalPoint = if hitscan then hitscan.Position else unitRay.Origin+unitRay.Direction*1000

Once we have the focal point, we just need to adjust the actual bullet direction to aim at that point. We can use CFrame.lookAt and then retrieve its LookVector:

--the origin would be the gun muzzle
local direction = CFrame.lookAt(ORIGIN, focalPoint).LookVector
module.abilityEvent:FireServer("PrimaryFire", {direction, ORIGIN})
4 Likes

Here is the code for the client side sending.

A:

I figured it out. I had to send the origin from the client, which by default is the center of the screen. I then had to offset the bullet position by half of the bullet size.

3 Likes

This is seriously awesome!! Thank you so much for your help! I was racking my brain trying to figure it out cuz I suck at math, I really appreciate this not only for the answer but also the explanation. Thank you again!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.