ReactJS / JavaScript条件语句

3
我正在使用箭头键移动圆形对象。现在我想将其限制在SVG区域的高度和宽度内。我的条件语句部分起作用,一旦球到达任何“墙壁”,它就会卡住并且无法移动。我明白为什么会这样,但无法想出防止它发生的方法。
编辑: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 = {
     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>
    )
  }
}

谢谢你

编辑:

根据下面的建议,我尝试了以下操作,但在四个角落之一时失败:

 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
1
我认为你需要做的是,不要检查它是否已经超出边缘,而是检查在更改后它是否将会超出边缘。 - Brigand
1个回答

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接