Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: changeable keybindings #203

Merged
merged 6 commits into from
Apr 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,9 @@ export function App() {
<Train />
<Ramp args={[30, 6, 8]} position={[2, -1, 168.55]} rotation={[0, 0.49, Math.PI / 15]} />
<Heightmap elementSize={0.5085} position={[327 - 66.5, -3.3, -473 + 213]} rotation={[-Math.PI / 2, 0, -Math.PI]} />
<Goal args={[0.001, 10, 18]} onCollideBegin={onStart} rotation={[0, 0.55, 0]} position={[-27, 1, 180]} />
<Goal args={[0.001, 10, 18]} onCollideBegin={onFinish} rotation={[0, -1.2, 0]} position={[-104, 1, -189]} />
<Goal args={[0.001, 10, 18]} onCollideBegin={onCheckpoint} rotation={[0, -0.5, 0]} position={[-50, 1, -5]} />
<Goal args={[0.001, 10, 18]} onCollideBegin={onStart as () => void} rotation={[0, 0.55, 0]} position={[-27, 1, 180]} />
<Goal args={[0.001, 10, 18]} onCollideBegin={onFinish as () => void} rotation={[0, -1.2, 0]} position={[-104, 1, -189]} />
<Goal args={[0.001, 10, 18]} onCollideBegin={onCheckpoint as () => void} rotation={[0, -0.5, 0]} position={[-50, 1, -5]} />
<BoundingBox {...{ depth: 512, height: 100, position: [0, 40, 0], width: 512 }} />
</ToggledDebug>
</Physics>
Expand Down
55 changes: 13 additions & 42 deletions src/controls/Keyboard.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,25 @@
import { useEffect } from 'react'
import { cameras, useStore } from '../store'

interface KeyConfig extends KeyMap {
keys?: string[]
}

interface KeyMap {
fn: (pressed: boolean) => void
up?: boolean
pressed?: boolean
}
import { useStore } from '../store'
import type { KeyConfig, KeyMap } from '../store'

function useKeys(keyConfig: KeyConfig[]) {
useEffect(() => {
const keyMap = keyConfig.reduce<{ [key: string]: KeyMap }>((out, { keys, fn, up = true }) => {
keys && keys.forEach((key) => (out[key] = { fn, pressed: false, up }))
keys && keys.forEach((key) => key.values.forEach((value) => (out[value] = { fn, pressed: false, up })))
return out
}, {})

const downHandler = ({ key, target }: KeyboardEvent) => {
if (!keyMap[key] || (target as HTMLElement).nodeName === 'INPUT') return
const { fn, pressed, up } = keyMap[key]
keyMap[key].pressed = true
const downHandler = ({ code, target }: KeyboardEvent) => {
if (!keyMap[code] || (target as HTMLElement).nodeName === 'INPUT') return
const { fn, pressed, up } = keyMap[code]
keyMap[code].pressed = true
if (up || !pressed) fn(true)
}

const upHandler = ({ key, target }: KeyboardEvent) => {
if (!keyMap[key] || (target as HTMLElement).nodeName === 'INPUT') return
const { fn, up } = keyMap[key]
keyMap[key].pressed = false
const upHandler = ({ code, target }: KeyboardEvent) => {
if (!keyMap[code] || (target as HTMLElement).nodeName === 'INPUT') return
const { fn, up } = keyMap[code]
keyMap[code].pressed = false
if (up) fn(false)
}

Expand All @@ -43,27 +34,7 @@ function useKeys(keyConfig: KeyConfig[]) {
}

export function Keyboard() {
const { reset, set } = useStore(({ actions: { reset }, set }) => ({ reset, set }))
useKeys([
{ keys: ['ArrowUp', 'w', 'W', 'z', 'Z'], fn: (forward) => set((state) => ({ controls: { ...state.controls, forward } })) },
{ keys: ['ArrowDown', 's', 'S'], fn: (backward) => set((state) => ({ controls: { ...state.controls, backward } })) },
{ keys: ['ArrowLeft', 'a', 'A', 'q', 'Q'], fn: (left) => set((state) => ({ controls: { ...state.controls, left } })) },
{ keys: ['ArrowRight', 'd', 'D'], fn: (right) => set((state) => ({ controls: { ...state.controls, right } })) },
{ keys: [' '], fn: (brake) => set((state) => ({ controls: { ...state.controls, brake } })) },
{ keys: ['h', 'H'], fn: (honk) => set((state) => ({ controls: { ...state.controls, honk } })) },
{ keys: ['Shift'], fn: (boost) => set((state) => ({ controls: { ...state.controls, boost } })) },
{ keys: ['r', 'R'], fn: reset, up: false },
{ keys: ['.'], fn: () => set((state) => ({ editor: !state.editor })), up: false },
{ keys: ['i', 'I'], fn: () => set((state) => ({ help: !state.help, leaderboard: false, pickcolor: false })), up: false },
{ keys: ['l', 'L'], fn: () => set((state) => ({ help: false, leaderboard: !state.leaderboard, pickcolor: false })), up: false },
{ keys: ['m', 'M'], fn: () => set((state) => ({ map: !state.map })), up: false },
{ keys: ['p', 'P'], fn: () => set((state) => ({ help: false, pickcolor: !state.pickcolor, leaderboard: false })), up: false },
{ keys: ['u', 'U'], fn: () => set((state) => ({ sound: !state.sound })), up: false },
{
keys: ['c', 'C'],
fn: () => set((state) => ({ camera: cameras[(cameras.indexOf(state.camera) + 1) % cameras.length] })),
up: false,
},
])
const keyboardBindings = useStore((state) => state.keyboardBindings)
useKeys(keyboardBindings)
return null
}
2 changes: 1 addition & 1 deletion src/models/BoundingBox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ type Props = {
}

export const BoundingBox = ({ depth, height, position: [x, y, z], width }: Props) => {
const { reset: onCollide } = useStore(({ actions: { reset } }) => ({ reset }))
const { reset: onCollide } = useStore(({ actions: { reset } }) => ({ reset: reset as () => void }))

const sharedProps = {
isTrigger: true,
Expand Down
148 changes: 146 additions & 2 deletions src/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ export const wheelInfo: WheelInfo = {
useCustomSlidingRotationalSpeed: true,
}

const actionNames = ['onCheckpoint', 'onFinish', 'onStart', 'reset'] as const
const actionNames = ['onCheckpoint', 'onFinish', 'onStart', 'reset', 'addKeyBinding', 'removeKeyBinding'] as const
export type ActionNames = typeof actionNames[number]

export type Camera = typeof cameras[number]
Expand All @@ -87,15 +87,33 @@ type BaseState = {
[K in Booleans]: boolean
}

export interface Key {
name: string
values: string[]
}

export interface KeyMap {
fn: (pressed: boolean) => void
up?: boolean
pressed?: boolean
}

export interface KeyConfig extends KeyMap {
keys: Key[]
action: string
}

export interface IState extends BaseState {
actions: Record<ActionNames, () => void>
actions: Record<ActionNames, (() => void) | ((action: string, newKey: Key) => void) | ((action: string, name: string) => void)>
api: PublicApi | null
bestCheckpoint: number
camera: Camera
chassisBody: RefObject<Object3D>
checkpoint: number
color: string
controls: Controls
keyboardBindings: KeyConfig[]
keyBindingsWithError: number[]
dpr: number
finished: number
get: Getter
Expand All @@ -106,6 +124,20 @@ export interface IState extends BaseState {
vehicleConfig: VehicleConfig
wheelInfo: WheelInfo
wheels: [RefObject<Object3D>, RefObject<Object3D>, RefObject<Object3D>, RefObject<Object3D>]
keyInput: string | null
}

function deduplicateKeys(newKey: Key, keysList: KeyConfig[]): KeyConfig[] {
return keysList.map((key) => ({ ...key, keys: key.keys.filter((keyCode) => keyCode.name !== newKey.name) }))
}

function checkKeybindings(keysList: KeyConfig[]): number[] {
return keysList.reduce<number[]>((akk, value, index) => {
if (value.keys.length < 1) {
akk.push(index)
}
return akk
}, [])
}

const useStoreImpl = create<IState>((set: SetState<IState>, get: GetState<IState>) => {
Expand Down Expand Up @@ -138,8 +170,117 @@ const useStoreImpl = create<IState>((set: SetState<IState>, get: GetState<IState
return { ...state, finished: 0, start: 0 }
})
},
addKeyBinding: (action: string, newKey: Key) => {
set((state) => {
const index = state.keyboardBindings.findIndex(({ action: stateAction }) => action === stateAction)

if (index === -1) {
return state
}

const keyboardBindingsCopy = deduplicateKeys(newKey, state.keyboardBindings)

keyboardBindingsCopy[index].keys.push(newKey)
njm222 marked this conversation as resolved.
Show resolved Hide resolved

const keyBindingsWithError = checkKeybindings(keyboardBindingsCopy)

return { ...state, keyboardBindings: keyboardBindingsCopy, keyBindingsWithError }
})
},
removeKeyBinding: (action: string, name: string) => {
set((state) => {
const index = state.keyboardBindings.findIndex(({ action: stateAction }) => action === stateAction)

if (index === -1) {
return state
}

const keyIndex = state.keyboardBindings[index].keys.findIndex(({ name: stateName }) => name === stateName)

const keyboardBindingsCopy = [...state.keyboardBindings]

keyboardBindingsCopy[index].keys.splice(keyIndex, 1)
njm222 marked this conversation as resolved.
Show resolved Hide resolved

const keyBindingsWithError = checkKeybindings(keyboardBindingsCopy)

return { ...state, keyboardBindings: keyboardBindingsCopy, keyBindingsWithError }
})
},
}

const defaultKeyboardBindings: KeyConfig[] = [
{
action: 'Forward',
keys: [
{ name: '↑', values: ['ArrowUp'] },
{ name: 'W', values: ['KeyW'] },
{ name: 'Z', values: ['KeyZ'] },
],

fn: (forward) => set((state) => ({ controls: { ...state.controls, forward } })),
},
{
action: 'Backward',
keys: [
{ name: '↓', values: ['ArrowDown'] },
{ name: 'S', values: ['KeyS'] },
],
fn: (backward) => set((state) => ({ controls: { ...state.controls, backward } })),
},
{
action: 'Left',
keys: [
{ name: '←', values: ['ArrowLeft'] },
{ name: 'A', values: ['KeyA'] },
{ name: 'Q', values: ['KeyQ'] },
],
fn: (left) => set((state) => ({ controls: { ...state.controls, left } })),
},
{
action: 'Right',
keys: [
{ name: '→', values: ['ArrowRight'] },
{ name: 'D', values: ['KeyD'] },
],
fn: (right) => set((state) => ({ controls: { ...state.controls, right } })),
},
{ action: 'Drift', keys: [{ name: 'Space ␣', values: ['Space'] }], fn: (brake) => set((state) => ({ controls: { ...state.controls, brake } })) },
{ action: 'Honk', keys: [{ name: 'H', values: ['KeyH'] }], fn: (honk) => set((state) => ({ controls: { ...state.controls, honk } })) },
{
action: 'Turbo Boost',
keys: [{ name: 'Shift ⇧', values: ['ShiftLeft', 'ShiftRight'] }],
fn: (boost) => set((state) => ({ controls: { ...state.controls, boost } })),
},
{ action: 'Reset', keys: [{ name: 'R', values: ['KeyR'] }], fn: actions.reset, up: false },
{ action: 'Editor', keys: [{ name: '.', values: ['Period'] }], fn: () => set((state) => ({ editor: !state.editor })), up: false },
{
action: 'Help',
keys: [{ name: 'I', values: ['KeyI'] }],
fn: () => set((state) => ({ help: !state.help, leaderboard: false, pickcolor: false })),
up: false,
},
{
action: 'Leaderboards',
keys: [{ name: 'L', values: ['KeyL'] }],
fn: () => set((state) => ({ help: false, leaderboard: !state.leaderboard, pickcolor: false })),
up: false,
},
{ action: 'Map', keys: [{ name: 'M', values: ['KeyM'] }], fn: () => set((state) => ({ map: !state.map })), up: false },
{
action: 'Pick Car Color',
keys: [{ name: 'P', values: ['KeyP'] }],
fn: () => set((state) => ({ help: false, pickcolor: !state.pickcolor, leaderboard: false })),
up: false,
},
{ action: 'Toggle Mute', keys: [{ name: 'U', values: ['KeyU'] }], fn: () => set((state) => ({ sound: !state.sound })), up: false },
{
action: 'Toggle Camera',
keys: [{ name: 'C', values: ['KeyC'] }],
fn: () => set((state) => ({ camera: cameras[(cameras.indexOf(state.camera) + 1) % cameras.length] })),
up: false,
},
]

return {
actions,
api: null,
Expand All @@ -149,11 +290,14 @@ const useStoreImpl = create<IState>((set: SetState<IState>, get: GetState<IState
checkpoint: 0,
color: '#FFFF00',
controls,
keyboardBindings: defaultKeyboardBindings,
keyBindingsWithError: [],
debug,
dpr,
editor: false,
finished: 0,
get,
keyInput: null,
help: false,
leaderboard: false,
level: createRef<Group>(),
Expand Down
Loading