2016-04-03 18 views
3

私は矢印キーを使って円オブジェクトを移動しています。今、私はそれをsvg領域の高さとwitdthに制限したいと思います。私の条件文は、ボールがどこにも詰まっていてどこにも移動しない「壁」に到達すると部分的に機能します。なぜそれがそれを行うが、それを防ぐ方法を考えることはできません。ReactJS/Javascript条件文

編集:CodePen:私はTR、以下の提案に続い

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> 
 
    ) 
 
    } 
 
}

あなた

編集ありがとうございました

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] 
     }) 

     } 
     } 
+0

1つの提案オブジェクトが壁にヒットした後、そのスタック状態からそれを逃れるために、反対方向にオブジェクトにナッジを与えることです。 – starcorn

+1

あなたがする必要があると思うのは、それが**エッジの上に**あるかどうかをチェックするのではなく、**変化の後に**エッジの上に**あるかどうかをチェックすることです。 – FakeRainBrigand

答えて