我正在使用箭头键移动圆形对象。现在我想限制它到svg区域的高度和深度。我的条件陈述部分地起作用,因为一旦球进入任何一堵“墙”,它就会卡住,并且不会移动到任何地方。我明白为什么这样做,但不能想办法阻止它做到这一点。ReactJS/Javascript条件语句
编辑:CodePen:http://codepen.io/wasteland/pen/GZvWeo?editors=0110
感谢
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 = {
\t 37: [-1, 0],
\t 38: [0, -1],
\t 39: [1, 0],
\t 40: [0, 1]
};
// Display the current position
this._currentPosition()
// Detect key presses and change the position accordingly
\t 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]
})
}
\t \t }
}
componentDidMount() {
document.addEventListener("keydown", this._handleKey, false);
}
render() {
return (
<div>
<Circle { ...this.state } />
</div>
)
}
}
谢谢
编辑:
下面的建议之后,我TR当您处于四个角落中的某一个时失败:
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]
})
}
}
一个建议是,一旦对象已经打在了墙上,给该对象的微调,以相反的方向得到它从停滞状态了。 – starcorn
我认为你需要做的是,而不是检查**是否是**边缘以上,检查它是否会在更改后的边缘**。 – FakeRainBrigand