Help with optimization

Hi.
Today I wrote an interactive grass system using OOP (Objective-oriented programming). It works like this:

Yes. It works. And it works very well.
But I would like to optimize my system. I understand that perfect optimization cannot be achieved, but still at least something

If anything, I’m not completely crazy, so I combined three or five blades of grass in a blender.
Here is a modular script:

local grassList = {}
local TweenService = game:GetService("TweenService")

local Grass = {} do
	Grass.__index = Grass
	
	function Grass:var(part,side)
		local Bone = part:FindFirstChild("Bone")
		local Tween = TweenService:Create(Bone, TweenInfo.new(.5, Enum.EasingStyle.Sine),{Orientation = Vector3.new(0, side, 0)})Bone2.Orientation.Z)})
		Tween:Play()
	end

	function Grass.new(part)
		local grass = {}
		grass.Part = part
		table.insert(grassList, grass)
		return setmetatable(grass, Grass)
	end
end

return Grass

Script in which I call the functions:

local CollectionService = game:GetService("CollectionService")
local RunService = game:GetService("RunService")

local char = script.Parent
local Grass = require(game.ReplicatedStorage.ModuleScript)

local Tagged = CollectionService:GetTagged("TallGrass")
local grass = Grass.new(Tagged)

for _,grass in pairs(Tagged) do
	RunService.Stepped:Connect(function()
		local distance = (char.Head.Position - grass.Position)
		local DotGrass = distance.Unit
		local DistGrass= distance.magnitude
		local grassLook = grass.CFrame.LookVector
		local dotProduct = DotGrass:Dot(grassLook)
		if DistGrass< 5 then
			if dotProduct > 0  then
				Grass:var(grass,-10,30,-10)
			elseif dotProduct < 0 then
				Grass:var(grass,10,-50,50)
			end
		end
		if DistGrass> 5 then
			Grass:var(grass,0, -7.689, 19.706)
		end
	end)
end

I’ll be incredibly grateful if you help me :pleading_face:

4 Likes

You should switch the tag of this post to #help-and-feedback:code-review.

3 Likes

Like @Katrist said, this belong in the #help-and-feedback:code-review category.

Alright, first you will want to benchmark your system as it is right now. Here’s a handy community tutorial I found. However, it’s not that useful for actually optimizing your code.

Because I don’t actually have the time right now to write out an explanation and relevant code samples, I’m just going to post a list of links you can check out. Hopefully you’ll find some, if not all, useful. The first link will most likely be the most helpful.

On this one, ignore the part about testing the speed of your code. You should use os.clock instead of tick for unit test and benchmarking.

This tutorial is by @Hexcede. He knows a lot about Roblox’s engine (or at least a lot more than me) so I would really try to understand it. Also, you’ve probably noticed that I’ve posted a few tutorial links for networking and reducing latency. This is because you might run into it later when developing your system.

6 Likes