jeu
brique | création |
fonctions utilesPosition souris sur un objet function getRelativePos(e) {e = e || window.event;var pageX = e.pageX;var pageY = e.pageY;if (pageX === undefined) {pageX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;pageY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;}return {x:pageX-e.target.offsetLeft,y:pageY-e.target.offsetTop};} //getrelativePosdocument.getElementsByTagName('body')[0].addEventListener("mousemove", function(e){console.log(e.target.tagName+"["+getRelativePos(e).x+" " +getRelativePos(e).y+"]");},false);Voici le code en action ou encore. function getRelativePos(e) {
var rect = e.target.getBoundingClientRect(); return { x: e.clientX - rect.left, y: e.clientY - rect.top }; } //getrelativePos document.getElementsByTagName('body')[0].addEventListener("mousemove", function(e){
console.log(e.target.tagName+"["+getRelativePos(e).x+" " +getRelativePos(e).y+"]"); },false); AnimationLe code général est donné ici var requestId = 0;function render(time) {//code animation//dessinerequestId = window.requestAnimationFrame(render);//condition d’arrêtif (test) stop();}function start() {starttime=new Date();render(starttime);}function stop() {if (requestId) { window.cancelAnimationFrame(requestId);}//stopped = true;}Vous trouverez le code en action. Nous allons nous servir de ses blocs de base pour dessiner la raquette et la balle La raquetteCréation d’une raquette var Paddle = function Paddle(x,y,width,height,color){ this.x=x; this.y=y; this.width=width; this.heigth=height; this.color=color; }; Modification de son comportement Paddle.prototype= { drawn : function(){ ctx.save(); ctx.fillStyle = this.color; ctx.beginPath(); ctx.fillRect(this.x-this.width/2,this.y,this.width,this.heigth); ctx.closePath(); ctx.fill(); ctx.restore(); }, move : function(X,Y){ this.x=X; this.y=Y; // console.info("Shape moved."); } }; La ballevar Ball = function Ball(x,y,radius,color){ this.x=x; this.y=y; this.radius=radius; this.color=color;
this.vX = 1; this.vY = 2; };
Ball.prototype = { drawn : function(){ ctx.save(); ctx.fillStyle = this.color; ctx.beginPath(); ctx.arc(this.x,this.y,this.radius,0,Math.PI*2, true); ctx.closePath(); ctx.fill(); ctx.restore(); }, move : function(){ this.x+=this.vX; this.y+=this.vY; } }; var ball = new Ball(10,10,10,"green"); //ball.drawn(); AnimationExaminons les trois cas de rebonds sur les paroies. Cas à gauche
Cas à droite Cas en haut. | |
Code if (ball.x +ball.vX+ ball.radius > canvas.width || ball.x +ball.vX - ball.radius< 0) ball.vX = -ball.vX; if (ball.y - ball.radius < 0) ball.vY = -ball.vY; else if (ball.y+ ball.vY + ball.radius > canvas.height - raqM.heigth) {
if (ball.x > mouseX-raqM.width/2 && ball.x < mouseX +raqM.width/2 ) { ball.vY=-ball.vY; } }
Animation voici le code en action |
|