I am building a tower defense game. So when building the tower would attach to the cursors location and perform collision checks.
The script below which changes color of its parent when it collides with another object. For context the tower would turn red if invalid and green if over a valid location. I tried 2 methods (ontouch event and raycasting). I found raycasting was better and more responsive so I went that route. The script would be attached to a part that is unanchored whereas the other part it interacted with would be anchored.
They both worked well but when attaching the tower directly to the mouse position this would break. Can someone explain why that is?
Here is the script:
local a = script.Parent
warn("Loaded ", a)
local isValid = a:WaitForChild("isValid")
local size = a.Size
local raycastResultLeft
local raycastResultBottom
a.Color = Color3.new(0.317647, 1, 0)
while true do
raycastResultLeft = workspace:Raycast(Vector3.new(a.Position.x-a.Size.X/2, a.Position.y, a.Position.z+a.Size.Z/2), Vector3.new(0,0,-1.8))
raycastResultBottom = workspace:Raycast(Vector3.new(a.Position.x-a.Size.X/2, a.Position.y, a.Position.z+a.Size.Z/2), Vector3.new(1.8,0,0))
print(raycastResultLeft)
print(raycastResultBottom)
if raycastResultLeft == nil and raycastResultBottom == nil then
a.Color = Color3.new(0.317647, 1, 0)
isValid.Value = true
else
a.Color = Color3.new(1, 0, 0.0156863)
isValid.Value = false
end
wait(0.1)
end
Ill post raycast script in next post as I reached character limit