I am using arrow keys to move the circle object. Now I want to limit it to the height and witdth of the svg area. My conditional statements partially work as once the ball gets to any of the 'walls' it gets stuck and does not move anywhere. I understand why it does it but can't think of a way to prevent it from doing it.
Edit: CodePen: http://codepen.io/wasteland/pen/GZvWeo?editors=0110
Thanks
class App extends React.Component {
constructor(props) {
super(props)
// Why you need to bind _handleKey:
// https://facebook.github.io/react/docs/reusable-components.html#no-autobinding
this._handleKey = this._handleKey.bind(this)
this.state = {
h: 200,
w: 800,
x: 50,
y: 50,
r: 20,
stroke: "none",
fill: "#6F90A2"
}
}
_currentPosition() {
// Display the current position
console.log(this.state.x, this.state.y);
}
_handleKey(e){
// Define key codes and movement vectors
const vector = {
37: [-1, 0],
38: [0, -1],
39: [1, 0],
40: [0, 1]
};
// Display the current position
this._currentPosition()
// Detect key presses and change the position accordingly
if (e.keyCode in vector) {
if (this.state.x < this.state.w - this.state.r &&
this.state.x > this.state.r &&
this.state.y > this.state.r &&
this.state.y < this.state.h - this.state.r) {
this.setState({
x: this.state.x + vector[e.keyCode][0],
y: this.state.y + vector[e.keyCode][1]
})
}
}
}
componentDidMount() {
document.addEventListener("keydown", this._handleKey, false);
}
render() {
return (
<div>
<Circle { ...this.state } />
</div>
)
}
}
Thank you
Edit:
Following a suggestion below, I tried the following, which fails when you're in one of the four corners:
if (e.keyCode in vector) {
if (this.state.x < this.state.w - this.state.r &&
this.state.x > this.state.r &&
this.state.y > this.state.r &&
this.state.y < this.state.h - this.state.r) {
this.setState({
x: this.state.x + vector[e.keyCode][0],
y: this.state.y + vector[e.keyCode][1]
})
} else {
this.setState({
x: this.state.x - vector[e.keyCode][0],
y: this.state.y - vector[e.keyCode][1]
})
}
}