خرید بک لینک

Vote count: 0

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.

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() {
    retu (
      <div>
        <Circle { ...this.state } />
      </div>
    )
  }
}

Thank you

asked 2 mins ago

برچسب: نویسنده: استخدام کار تاريخ: يکشنبه 15 فروردين 1395 ساعت: 22:54

صفحه بندی