Forgive my complete noobness here as very new to JS.
I've created a really simple canvas with one rectangle being controlled by keydownevents and one just moving around the canvas in rAF.
I want to now have if the moving ball hits the users rectangle to collide and bounce back but to bounce at the right angle that it hits not just in reverse like i have tried and failed at.
I know i need to calculate where it hits on the users rect, 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'll leave out the Keycode functions for space as they're 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);
// user controlled square
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;
// Moving Square 1 (left-right):
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";
}
}
}
// Second square
function squareTwo() {
ctx.fillStyle = "black";
ctx.fillRect(xpos, ypos, 35, 35);
ctx.fill();
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…