madcat999 Posted November 14, 2014 Share Posted November 14, 2014 I am trying to move to images which have been loaded to the screen so they meet together and stop. The code is below - one image disappears and they both move in the same direction. Any help would be appreciated as I am very very new to this and have googled for a whole day (bought a book) and am still not able to work it out. Thank you <canvas id="myCanvas" width="578" height="200"> <p>This browser does not support the <code>canvas</code> element.</p></canvas> <script> window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.oRequestAnimationFrame; // get canvas and create drawing contextvar canvas = document.getElementById('myCanvas');var context = canvas.getContext('2d'); // create imagevar img1 = document.createElement("img");var img2 = document.createElement("img"); img1.src = "http://domain.co.uk/xxx.png"img2.src = "http://domain.co.uk/yyy.png"var xSpeed = 0.05; //px per msvar ySpeed = 0.01; function animate(nowTime, lastTime, xPos, yPos) { if ((img1.style.width + xPos) > canvas.width) { xPos = 0; yPos = 0; } var timeDelta = nowTime - lastTime; var xDelta = xSpeed * timeDelta; var yDelta = ySpeed * timeDelta; // clear context.clearRect(0, 0, canvas.width, canvas.height); //draw img context.drawImage(img1, xPos, yPos); if (xPos < 133) {requestAnimationFrame(function(timestamp){animate(timestamp, nowTime, xPos + xDelta, yPos + yDelta)});}} function animate2(nowTime, lastTime, x2Pos, y2Pos) { if ((img2.style.width + x2Pos) > canvas.width) { x2Pos = 0; y2Pos = 90; } var timeDelta = nowTime - lastTime; var x2Delta = xSpeed * timeDelta; var y2Delta = ySpeed * timeDelta; // clear //context.clearRect(0, 0, canvas.width, canvas.height); //draw img context.drawImage(img2, x2Pos, y2Pos); if (x2Pos < 133) {requestAnimationFrame(function(timestamp){animate2(timestamp, nowTime, x2Pos + x2Delta, y2Pos + y2Delta)});}}animate(0, 0, 10, 1),animate2(0, 1, 70, 1); </script> Quote Link to comment Share on other sites More sharing options...
Mrst2L Posted January 1, 2015 Share Posted January 1, 2015 The Phaserjs framework provides sprite collision so you can try that. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.