Forgive my complete indispensability here, as very new to JS. I created a really simple canvas with one rectangle that is controlled by keydownevents, and one just moves around the canvas in rAF.
I want now that if a moving ball hits the users rectangle in order to collide and bounce back, but to bounce at a right angle, which it hits not only the other way around, as I tried and could not.
I know that I need to figure out where it hits users, but I have no idea where to start or how Can someone point me in the right direction or give me a small snippet of what to do?
I will not leave Keycode functions for space, as they are not needed.
function init() {
canvas = document.getElementById("canvasdemo");
ctx = canvas.getContext("2d");
canvasWidth = canvas.width;
canvasHeight = canvas.height;
drawSquare();
}
function drawSquare() {
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
ctx.fillStyle = "blue";
ctx.fillRect(rect.x, rect.y, rect.w, rect.h);
requestAnimationFrame(drawSquare);
if (rect.x + rect.vx > canvasWidth - 20 || rect.x + rect.vx < 0)
rect.vx = -rect.vx;
if (rect.y + rect.vy > canvasHeight - 20 || rect.y + rect.vy < 0)
rect.vy = -rect.vy;
rect.x += rect.vx;
rect.y += rect.vy;
requestAnimationFrame(squareTwo);
if (dir1 == "right") {
if (xpos < canvasWidth - 35) {
xpos += 2;
}else{
dir1 = "left";
}
}
if (dir1 == "left") {
if (xpos>0) {
xpos -= 2;
}else{
dir1 = "right";
}
}
}
function squareTwo() {
ctx.fillStyle = "black";
ctx.fillRect(xpos, ypos, 35, 35);
ctx.fill();
}