Vehicle Horn bugg

Hey there,

I made a stand-alone vehicle horn script wich should make it able to click the button and only play the sound then.
The current script makes it possible to click the button and play the sound while not in vehicle.
How can I make the horn work only while in vehicle?



AddCSLuaFile("autorun/dmod_horn.lua")

resource.AddSingleFile("sound/vehicles/car_horn.mp3")
util.PrecacheSound("vehicles/car_horn.mp3")

hook.Add( "KeyPress", "keypress_use_hi", function( ply, key )
		if ( key == IN_ATTACK ) then
			Entity( 1 ):EmitSound( "vehicles/car_horn.mp3", 75, 100, 1.0)
		end
end )


Kind regards,

Koen

Use

Player:InVehicle as one of your checks.

if Player:InVehicle() returns true you should use Player:GetVehicle() to EmitSound from.

How should the code then look? I’m a beginner at lua coding :S

Almost the exact same as your “IN_ATTACK” if statement?

Spoilers:
[sp]hook.Add( “KeyPress”, “keypress_use_hi”, function( ply, key )
if ( key == IN_ATTACK ) and ply:InVehicle() then
ply:GetVehicle():EmitSound( “vehicles/car_horn.mp3”, 75, 100, 1.0)
end
end )[/sp]

This would turn your keyboard into a piano when driving.

Fixed, but pianos are pretty good cars

I fixed the code myself with the emitsound code from MPan1



AddCSLuaFile("autorun/dmod_horn.lua")

resource.AddSingleFile("sound/vehicles/car_horn.mp3")
util.PrecacheSound("vehicles/car_horn.mp3")

hook.Add( "KeyPress", "keypress_use_hi", function( ply, key )

	local ply = LocalPlayer()
	
	if ply:InVehicle() then 
		if ( Entity( 1 ):KeyPressed( IN_ATTACK ) ) then
			ply:GetVehicle():EmitSound( "vehicles/car_horn.mp3", 75, 100, 1.0)
		end	
	end
	
	if not ply:InVehicle() then
		return false
	end
end)

Thanks everybody!

Using Entity(1) is not a fix at all, that’d only work if the first entity was the one pressing the key, also, you don’t need to return false, and you don’t need to set ply as LocalPlayer() because ply is already defined (and also that wouldn’t work serverside as it’s a shared file by the looks of it), and you don’t need to use ply:KeyPressed because key is already defined and you were even using it before…

I don’t see why you wanted to change the example I posted so it doesn’t work?