Binding xbox controls to pc controls and scrolling through?

Here’s what I have so far -

local userInputService = game:GetService('UserInputService')
local contextActionService = game:GetService('ContextActionService')

local equipping = require(script:WaitForChild('Equipping'))

local selectedWeapon = 'Primary'

userInputService.InputBegan:Connect(function(inputObject)
if inputObject.KeyCode == Enum.KeyCode.One then
		selectedWeapon = 'Primary'
	elseif inputObject.KeyCode == Enum.KeyCode.Two then
		selectedWeapon = 'Secondary'
	elseif inputObject.KeyCode == Enum.KeyCode.Three then
		selectedWeapon = 'Melee'
	end
end)

Basically when player presses 1, they gonna equip the primary weapon, 2, etc. equipping hasn’t been coded in yet, just getting the basics done. However, I’ve never done binding with xbox controls before. I’ve read through the devhub about contextactionservice, and I’m completely lost with all that. Basically the aim would be when they press ButtonL1, it’d scroll ‘left’ and ButtonR1 would scroll right, depending what weapon that currently have selected, so kinda like this

if inputObject.KeyCode == Enum.KeyCode.ButtonL1 then
	if selectedWeapon == 'Secondary' then
		selectedWeapon = 'Primary'
	elseif selectedWeapon == 'Melee' then
		selectedWeapon = 'Secondary'
	end
elseif inputObject.KeyCode == Enum.KeyCode.ButtonR1 then
	if selectedWeapon == 'Primary' then
		selectedWeapon = 'Secondary'
	elseif selectedWeapon == 'Secondary' then
		selectedWeapon = 'Melee'
	end
end

But that seems really cluttered and inefficient. Any advice would be great

I feel like using numbers instead of strings would be much easier. Is there any reason something like this wouldn’t work for you?

local selectedWeapon = 1

if inputObject.KeyCode == Enum.KeyCode.ButtonL1 then
	selectedWeapon = math.clamp(selectedWeapon - 1, 1, 3)
elseif inputObject.KeyCode == Enum.KeyCode.ButtonR1 then
	selectedWeapon = math.clamp(selectedWeapon + 1, 1, 3)
end
1 Like

Looking closer at the code, what you have hear is a deterministic finite automaton. These things be be easily represented as a transition table, and are even easier to implement in Lua – which is all about tables!

Here is how I would do it:

local nextWeapon = {
  Melee = 'Secondary';
  Secondary = 'Primary';
  Primary = 'Primary';
}

local prevWeapon = {
  Primary = 'Secondary';
  Secondary = 'Melee';
  Melee = 'Melee';
}

... 

if inputObject.KeyCode == Enum.KeyCode.ButtonL1 then
	selectedWeapon = nextWeapon[selectedWeapon]
elseif inputObject.KeyCode == Enum.KeyCode.ButtonR1 then
	selectedWeapon = prevWeapon[selectedWeapon]
end

These tables encode the following DFA: (I happen to always have a whiteboard nearby)

1 Like