PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience

Add a Seat for Vehicles

Add a Seat for Vehicles

Jun 23 2018, 2:01 AM PST

Problem

You want to enable players to ride in a vehicle.

Solution

Use the Steer property of VehicleSeat.

local seat = Workspace.VehicleSeat
 
seat.Touched:connect(function(c)
	local pl = game.Players:FindFirstChild(c.Parent.Name)
	if pl then
		print(pl.Name..' has sat on the seat.')
		seat.Changed:connect(function(p)
			if p == 'Steer' then
				if seat.Steer == -1 then
					pl.Character.Humanoid.Health = 0
				end
			end
		end)
	end
end)
 
seat.ChildRemoved:connect(function(c)
	print(c.Part1.Parent.Name..' is leaving the seat!')
end)

Discussion

In this example we have a VehicleSeat in the Workspace called “VehicleSeat” and the “seat” variable is set to it. We a user touches the seat we safely index their player and print “Player has sat in the seat”. Then when a property of the seat changes we check to see if the property that changed was the “Steer” property. If so and its equal to -1 (meaning the user was trying to turn left), we kill them.

We also attach the ChildRemoved event on the VehicleSeat. When a user sits in the seat a connection object called a Weld is placed into the seat. When they leave, the connection is removed. If we use the ChildRemoved event on the VehicleSeat we can determine who is leaving. We’ll discuss more about Welds and connection objects in later chapters.

Tags:
  • vehicle