Coin placement system

Hello developers!

I am trying to make a coin placement system.

Here is my current code:

function SpawnCoin(Region)
	local X = Region.Position.X
	local Z = Region.Position.Z
	local XS = Region.Size.X/2
	local ZS = Region.Size.Z/2

	local NewCoin = game.ReplicatedStorage.Coin:Clone()

	NewCoin.Parent = game.Workspace

	local Pos1 = math.random(X-XS,X+XS)
	local Pos2 = math.random(Z-ZS,Z+ZS)

	NewCoin.Position = Vector3.new(Pos1, Region.Position.Y, Pos2)
end

Now, this works fine and all, but what I’d love is so that the coin finds the nearest gound and goes to it.

Here is a top quality drawing of this:

Does anyone have any ideas? Thanks!

You would probably want to raycast straight down from the spawn point and use its hit pos.


r = Ray.new(
				Vector3.new(Pos1, Region.Position.Y, Pos2),
				Vector3.new(0,-1,0)*500
			)

local hit,pos = workspace:FindPartOnRayWithIgnoreList(r,{ignore parts})

NewCoin.Position =  pos
2 Likes

Hit an error on Ray.new()…

I added a comment w/ the error. (attempt to call a nil value)

function SpawnCoin(Region)
	local X = Region.Position.X
	local Z = Region.Position.Z
	local XS = Region.Size.X/2
	local ZS = Region.Size.Z/2

	local NewCoin = game.ReplicatedStorage.Coin:Clone()

	NewCoin.Parent = game.Workspace

	local Pos1 = math.random(X-XS,X+XS)
	local Pos2 = math.random(Z-ZS,Z+ZS)
	
	local Raycast = Ray.New( -------- attempt to call a nil value
		Vector3.new(Pos1, Region.Position.Y, Pos2),
		Vector3.new(0,-1,0)*500
	)

	local Hit, Position = workspace:FindPartOnRayWithIgnoreList(Raycast) -- second argument is parts that are being ignored

	NewCoin.Position =  Position

end

Ray.new() should be lowercase.

2 Likes