-
Notifications
You must be signed in to change notification settings - Fork 0
/
joystick.js
91 lines (87 loc) · 3.02 KB
/
joystick.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import React, { Component } from 'react';
import {
Text,
View,
PanResponder,
TouchableHighlight
} from 'react-native';
import { styles, joystickSize } from './styles';
export default class Joystick extends Component {
constructor(props) {
super(props);
this.state = { x: 0, y: 0 };
this.onLayout = this.onLayout.bind(this);
}
componentWillMount() {
this._panResponder = PanResponder.create({
// Ask to be the responder:
onStartShouldSetPanResponder: () => true,
onStartShouldSetPanResponderCapture: () => true,
onMoveShouldSetPanResponder: () => true,
onMoveShouldSetPanResponderCapture: () => true,
onPanResponderGrant: (evt, gestureState) => {
this.setState({ x: gestureState.x0 - this.joystickX, y: gestureState.y0 - this.joystickY });
},
onPanResponderMove: (evt, gestureState) => {
this.setState({ x: gestureState.moveX - this.joystickX, y: gestureState.moveY - this.joystickY });
},
onPanResponderTerminationRequest: () => true,
onPanResponderRelease: () => {
this.setState({ x: 0, y: 0 });
},
onPanResponderTerminate: () => {
// Another component has become the responder, so this gesture
// should be cancelled
},
onShouldBlockNativeResponder: () => true,
// Returns whether this component should block native components from becoming the JS
// responder. Returns true by default. Is currently only supported on android.
});
}
onLayout() {
this.jview.measureInWindow((x, y, width, height) => {
this.joystickX = x + width * 0.5;
this.joystickY = y + height * 0.5;
});
}
render() {
const { x, y } = this.state;
const inputRad = Math.min(Math.sqrt(x * x + y * y), joystickSize * 0.5 - 15);
let innerJoystickX = x * inputRad / Math.sqrt(x * x + y * y);
let innerJoystickY = y * inputRad / Math.sqrt(x * x + y * y);
// zero the axes when not taking any input
if (isNaN(innerJoystickX)) {
innerJoystickX = 0;
innerJoystickY = 0;
}
innerJoystickX += joystickSize * 0.5 - 20;
innerJoystickY += joystickSize * 0.5 - 20;
return (
<View ref={(v) => { this.jview = v; }} style={styles.joystick} {...this._panResponder.panHandlers} onLayout={this.onLayout}>
<TouchableHighlight
activeOpacity={1}
onPress={() => undefined}
onHideUnderlay={() => undefined}
onShowUnderlay={() => undefined}
>
<TouchableHighlight
style={{
marginLeft: innerJoystickX,
marginTop: innerJoystickY,
width: 30,
height: 30,
borderRadius: 15,
borderWidth: 2,
backgroundColor: '#a05050'
}}
activeOpacity={1}
onPress={() => undefined}
onHideUnderlay={() => undefined}
onShowUnderlay={() => undefined}
>
<Text />
</TouchableHighlight>
</TouchableHighlight>
</View>);
}
}