este es mi codigo
ya puedo dibujar la linea pero cuando dejo de presionar la tecla deberia borrarse la linea dibujada
bueno pretendo hacer este juego
https://www.youtube.com/watch?v=WuuO7aOrTwo
ayuda please!!!
Código
// Variables globales function main() { window.addEventListener('keydown', dirigir, true); var canvas = document.getElementById("canvas2D"); var cWidth = document.getElementById("canvas2D").width; var cheight = document.getElementById("canvas2D").height; var context = canvas.getContext("2d"); var player={direction:39, posX:20, posY:20, ancho:10, alto:10}; var enemigo={posX:200, posY:200, ancho:50, alto:50}; var lineaDibujada={X1:20, Y1:20, X2:player.posX, Y2:player.posY}; //context.fillRect(20,20,50,50); function init(){ if(typeof game_loop!="undefined"){ clearInterval(game_loop); } game_loop=setInterval(main,200); } function dibujarLinea(X1,Y1,X2,Y2){ context.save(); context.moveTo(X1,Y1); context.lineTo(X2,Y2); context.strokeStyle = "#f00"; context.stroke(); context.restore(); } function dirigir(evt) { if(evt.keyCode!=null){ switch(evt.keyCode){ case 39: if(player.posX<cWidth-4){ player.posX+=2; } break; case 37: if(player.posX>-1){ //dibujarLinea(player.posX,player.posY,player.posX-2,player.posY); player.posX-=2; } break; case 38: if(player.posY>-1){ // dibujarLinea(player.posX,player.posY,player.posX,player.posY-2); player.posY -=2; } break; case 40: if(player.posY<cheight-4){ // dibujarLinea(player.posX,player.posY,player.posX,player.posY+2); player.posY+=2; } break; default: player.posX=player.posX; player.posY=player.posY; } }else{ context.restore(); //context.clearRect(0,0,cWidth,cheight); } } function main(){ moverEnemigo(); setBackground(); drawPlayer(); dibujarLinea(lineaDibujada.posX1,lineaDibujada.posY1,player.posX,player.posY); drawEnemigo(); } function moverEnemigo(){ var aleatorio =Math.random(); aleatorio =aleatorio*100; if(aleatorio<25){ if(enemigo.posX<cWidth-20){ enemigo.posX+=10; }else{ enemigo.posX-=10; } } if(aleatorio>=25&& aleatorio<45){ if (enemigo.posX>20){ enemigo.posX-=10; }else{ enemigo.posX+=10; } } if(aleatorio>=45 && aleatorio<70){ if(enemigo.posY>20){ enemigo.posY-=10; } else{ enemigo.posY+=10; } } if(aleatorio>=70 && aleatorio<=100){ if(enemigo.posY<cheight-20){ enemigo.posY+=10; }else{ enemigo.posY-=10; } } //para que se acerque al jugador e imponga miedo } function setBackground(){ context.save(); context.fillStyle="white"; context.fillRect(0,0,cWidth,cheight); context.strokeStyle="black"; context.strokeRect(0,0,cWidth,cheight); context.restore(); } setBackground(); function drawPlayer(){ context.save(); context.fillStyle="blue"; context.fillRect(player.posX,player.posY, player.ancho,player.alto); context.restore(); } function drawEnemigo(){ context.save(); context.fillStyle="Red"; context.fillRect(enemigo.posX,enemigo.posY, enemigo.ancho,enemigo.alto); context.restore(); } init(); }
Código
Mod: Tema modificado, colocadas etiquetas GeSHi para mejor visualización del código