2017-11-08 36 views
-1

私は新しいSVG rectを作成しキャンバスに置く(ポンゲーム)、最初のプレイヤーにはArrowUpとArrowDownを割り当て、2番目のプレイヤーにはキー "W"と "A"を割り当てるクラスJugadorを持っています「スティック」を動かす。あなたはkeydownイベントを有効にするにはどうすればよいですか?

this.jugador.addEventListener("onkeydown", movimiento); 

を行うことができ

class Jugador { 
    constructor(num, coorx, coory, color) { 
     this.parent = document.getElementById("svg"); 
     this.rectan = document.createElementNS("http://www.w3.org/2000/svg", "rect"); 
     this.parent.appendChild(this.rectan); 
     this.jugador = document.getElementsByTagName("rect")[num]; 
     this.jugador.setAttribute("x", coorx); 
     this.jugador.setAttribute("y", coory); 
     this.jugador.setAttribute("rx", "14"); 
     this.jugador.setAttribute("ry", "14"); 
     this.jugador.setAttribute("width", "35"); 
     this.jugador.setAttribute("height", "250"); 
     this.jugador.setAttribute("onkeydown", "movimiento(event)"); 
     this.jugador.style.fill = color; 
     this.jugador.style.stroke = "black"; 
     this.jugador.style.strokeWidth = "2"; 
    } 

    movimiento(event) { 
     let code = event.keyCode || event.which; 

     if (document.getElementsByTagName("rect")[0]) { 
      if (code == 38) { // flecha arriba 
       pala1.setAttribute("y", (pala1.getAttribute("y") + 5)); 
      } else if (code == 40) { //flecha abajo 
       pala1.setAttribute("y", (pala1.getAttribute("y") - 5)); 
      } 
     } 
     if (document.getElementsByTagName("rect")[1]) { 
      if (code == 113) { // letra Q 
       pala2.setAttribute("y", (pala2.getAttribute("y") + 5)); 
      } else if (code == 97) { //letra A 
       pala2.setAttribute("y", (pala2.getAttribute("y") - 5)); 
      } 
     } 
    } 
} 

var pala1 = new Jugador(0, 50, 300, "orange"); 
var pala2 = new Jugador(1, 1715, 300, "blue"); 

答えて

1

代わりの

this.jugador.setAttribute("onkeydown", "movimiento(event)"); 

それでも、イベントでは、その要素にフォーカスを持っている場合にのみ起動されます。

代わりに、あなたは文書全体のイベントをバインドすることができます。

document.body.addEventListener("onkeydown", movimiento); 
関連する問題