Transforms are added…endlessly

前端 未结 3 1746
灰色年华
灰色年华 2020-12-06 20:24

I\'m creating a simple asteroids-like game in CSS and JS using the DOM over canvas for...experimentation purposes.

My code is pretty small in this example to make i

3条回答
  •  执念已碎
    2020-12-06 21:17

    I have done a rapid answer - probably there are some aspect to smooth, but you'll get the idea: (ES6 code)

    'use strict'
    
    class Ship {
        constructor (elem) {
            this.posX = 0;
            this.posY = 0;
            this.deg = 0;
            this.rad = 0;
            this.speed = 0;
        }
    
        update (event) {
          switch( event.key ) {
            case "ArrowUp":
              this.speed += 5;
              break;
            case "ArrowDown":
              this.speed -= 5;
              if (this.speed < 0) this.speed = 0;
              break;
            case "ArrowRight":
              this.deg += 3;
              break;
            case "ArrowLeft":
              this.deg -= 3;
              break;
          }
              this.rad = (this.deg + 90) * Math.PI / 180;
        }
        move () {
          this.posX += this.speed * Math.cos(this.rad);
          this.posY += this.speed * Math.sin(this.rad);
          if (this.speed > 0) {
              this.speed -= 0.1;
          }
          if (this.elem == undefined) {
            this.elem = document.getElementById('ship');
          }
          var translation = 'translate(' + this.posX +'px, ' + this.posY + 'px) ';
          var rotation = 'rotate(' + this.deg + 'deg)';
          this.elem.style.transform = translation + rotation;
                         
        }
    }
    
    
    var ship = new Ship
    
    function update( e ) {
      ship.update(e);
      return false;
    }
    
    function start() {
      window.addEventListener( 'keydown', update );
      setInterval ( 
        function() {
          ship.move();
        },
        1000 / 24
      );  
    }
    
    start();
    #ship {
      position: absolute;
      left: 50%;
      top: 50%;
    }
    V

提交回复
热议问题