How would I get a 2D object's "look vector"?

I am trying to achieve a 2D object that shoots bullets in the direction it is facing. I have a script that rotates the object to face the mouse, but I can’t seem to get it working. I tried using the .Unit of the mouse position, but that just changes the speed of the object depending on distance and scenario.

Here is the script I am using:

local rs = game:GetService("RunService")
local plrs = game:GetService("Players")
local player = plrs.LocalPlayer
local mouse = player:GetMouse()

local gui = script.Parent

local center = gui:WaitForChild("Center")
local img = center:WaitForChild("Img")

local balls = {}

local function ballCreate(pos,mousePos,speed)
	local cent_clone = center:Clone()
	cent_clone:ClearAllChildren()
	cent_clone.ZIndex = center.ZIndex+1
	cent_clone.Parent = gui
	local ball = Instance.new("ImageLabel")
	ball.Name = "Ball"
	ball.BackgroundTransparency = 1
	ball.Image = "http://www.roblox.com/asset/?id=596211266"
	ball.ScaleType = Enum.ScaleType.Fit
	ball.Size = UDim2.fromScale(5,5)
	ball.AnchorPoint = Vector2.new(.5,.5)
	ball.Position = pos
	ball.Parent = cent_clone

	table.insert(balls,ball)
end

rs:BindToRenderStep("RotateTo",Enum.RenderPriority.Camera.Value,function()
	local mousePos = Vector2.new(mouse.X,mouse.Y)
	local player2DPosition = center.AbsolutePosition
	local diff = mousePos - player2DPosition
	local angle = math.atan2(diff.Y, diff.X)

	center.Rotation = math.deg(angle)

	for _, ball in pairs(balls) do
		ball.Position = ball.Position + UDim2.fromOffset() -- no idea for how to get this direction
	end
end)

while task.wait(1) do
	ballCreate(
		center.Position,
		Vector2.new(mouse.X,mouse.Y),
		50
	)
end

Hierarchy:
Screenshot 2024-02-12 152341

If you want more information, feel free to ask.

1 Like
local function getLookVector(Frame: Frame)
	local LookVector = Vector2.new(math.sin(math.rad(Frame.Rotation)), math.sin(math.rad(Frame.Rotation + 270)))
	return UDim2.new(0, LookVector.X, 0, LookVector.Y) --> Returns lookVector in pixels in a range(-1, 1), if you want higher results, multiply it, and if you want in scale, convert it
end

It says “Frame” on the argument, but you can use it with any gui that has the Rotation property

1 Like

Thanks so much for the hasty reply! I appreciate your help.

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