2016-04-03 34 views
3

Daire nesnesini taşımak için ok tuşlarını kullanıyorum. Şimdi onu svg alanının yüksekliğine ve derinliğine sınırlamak istiyorum. Şartlı ifadelerim, topun 'duvarlara' ulaştığı anda sıkışıp kalır ve herhangi bir yere taşınmaz. Bunu neden yaptığını anlıyorum ama bunu yapmasını engellemek için bir yol düşünemiyorum.ReactJS/Javascript koşullu bildirimleri

Düzenleme: CodePen: Ben tr, bir öneri aşağıda ardından

: http://codepen.io/wasteland/pen/GZvWeo?editors=0110

Teşekkür

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

Düzenleme ederiz Aşağıdaki dört köşeden birinde olduğunuzda başarısız olan aşağıdakileri reddedebilirsiniz:

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

Bir öneri nesne duvara vurmak sonra, uzak o sıkışmış durumdan almak için nesneyi ters yönde bir dürtükledim etmektir. – starcorn

+1

Yapmanız gereken şey bence, kenarın ** üzerinde ** olup olmadığını kontrol etmek yerine, değişiklikten sonra kenarın ** üzerinde olup olmayacağını kontrol edin. – FakeRainBrigand

cevap