Advertisement
AlewAlow

Bullet Projectile

May 3rd, 2024
857
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.95 KB | None | 0 0
  1. local RunService = game:GetService("RunService")
  2. local ReplicatedStorage = game:GetService("ReplicatedStorage")
  3.  
  4. local Signal = require(ReplicatedStorage.Libs.Signal)
  5. local Trove = require(ReplicatedStorage.Libs.Trove)
  6.  
  7. local IS_CLIENT = RunService:IsClient()
  8. local DEFAULT_SPEED = 50
  9. local DEFAULT_PARAMS = RaycastParams.new()
  10.  
  11. local Bullet = {}
  12. Bullet.__index = Bullet
  13.  
  14. function Bullet.new(projectileProperties)
  15.     local self = setmetatable({}, Bullet)
  16.     self.Properties = projectileProperties
  17.     self.Position = projectileProperties.StartPosition
  18.     self.Params = projectileProperties.Params or DEFAULT_PARAMS
  19.     self.Speed = projectileProperties.Speed or DEFAULT_SPEED
  20.    
  21.     if IS_CLIENT then
  22.         self.Instance = script.BulletTemplate:Clone()
  23.         self.Instance.Name = "sigma"
  24.         self.Instance.Position = self.Position
  25.         self.Instance.Parent = workspace
  26.     end
  27.    
  28.     self.Hit = Signal.new()
  29.     self.Destroyed = Signal.new()
  30.     self.Destroyed:Connect(function()
  31.         if self.Instance then
  32.             self.Instance:Destroy()
  33.         end
  34.     end)
  35.    
  36.     local distance =
  37.         (projectileProperties.StartPosition
  38.         - projectileProperties.TargetPosition).Magnitude
  39.    
  40.     self.Lifetime = distance / self.Speed
  41.    
  42.     return self
  43. end
  44.  
  45. function Bullet:Update(_deltaTime)
  46.     local timePassed = workspace:GetServerTimeNow() - self.Properties.StartTime
  47.     local timePercentage = timePassed / self.Lifetime
  48.     if timePercentage > 1 then
  49.         self.Destroyed:Fire()
  50.         return
  51.     end
  52.    
  53.     local lastPosition = self.Position
  54.     local currentPosition = self.Properties.StartPosition:Lerp(self.Properties.TargetPosition, timePercentage)
  55.     local direction = currentPosition - lastPosition
  56.     local result = workspace:Raycast(
  57.         lastPosition,
  58.         direction,
  59.         self.Params
  60.     )
  61.    
  62.     if result then
  63.         self.Position = result.Position
  64.         self.Hit:Fire(result.Instance)
  65.         self.Destroyed:Fire()
  66.         return
  67.     end
  68.    
  69.     self.Position = currentPosition
  70.    
  71.     if self.Instance then
  72.         self.Instance.Position = self.Position
  73.     end
  74. end
  75.  
  76. return Bullet
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement