I am in the process of developing a simple game for a class project. Currently, I am working on ensuring that my rectangle stays within the boundaries of the canvas as I move it using a bounce function. However, I am facing difficulties as the rectangle does not seem to be bouncing off the edges as expected. I have already implemented the bounce function and called it at the beginning of my code. Despite this, the rectangle continues to move past the canvas limits instead of rebounding off the border.
var canvas;
var ctx;
var w = 1000;
var h = 700;
var o1 = {
x: 100,
y: h/2,
w: 100,
h: 100,
c: 0,
a: 100,
angle: 0, //changes angle that shape sits at
distance: 10
}
document.onkeydown = function(e){keypress(e, o1)}
setUpCanvas();
// circle (o1);
animationLoop();
function animationLoop(){
//clear
clear();
//draw
rect(o1);
//update
bounce(o1)
requestAnimationFrame(animationLoop)
}
function bounce(o){
if(o.x+o.w/2 > w || o.x-o.w/2 < 0){ //makes shape bounce from edge instead of middle. collision detection
o.changeX *= -1; //same as o.changeX = o.changeX = -1;
}
if(o.y+o.h/2 > h || o.y-o.h/2 <0){
o.changeY *= -1;
}
}
function updateData(o){
o.x += o.changeX;
o.y += o.changeY;
}
function keypress(e,o){
if (e.key == "ArrowUp"){
o.angle = 270;
o.distance= 80;
forward(o);
}
if (e.key == "ArrowDown"){
o.angle = 90;
o.distance= 20;
forward(o);
}
}
function forward(o){ //makes shape able to move
var cx;
var cy;
cx = o.distance*Math.cos(o.angle);
cy = o.distance*Math.sin(o.angle)
o.y += cy;
}
function rect(o){
var bufferx = o.x;
var buffery = o.y
o.x = o.x - o.w/2;
o.y = o.y- o.h/2;
ctx.beginPath(); //this is very important when we are changing certain ctx properties
ctx.moveTo(o.x,o.y);
ctx.lineTo(o.x+o.w,o.y);
ctx.lineTo(o.x+o.w,o.y+o.h);
ctx.lineTo(o.x, o.y+o.h);
ctx.lineTo(o.x,o.y);
ctx.fillStyle = "hsla("+String (o.c)+",100%,50%,"+o.a+")";
ctx.fill();
o.x = bufferx; //o.x = o.x + o.w/2;
o.y = buffery;//o.y = o.y+ o.h/2;
}
function clear(){
ctx.clearRect(0, 0, w, h);
}
function randn(range){
var r = Math.random()*range-(range/2);
return r
}
function rand(range){
var r = Math.random()*range
return r
}
function setUpCanvas(){
canvas = document.querySelector("#myCanvas");
canvas.width = w;
canvas.height = h;
// canvas.style.width = "1000px";
// canvas.style.height = "700px";
canvas.style.border = "10px solid black";
ctx = canvas.getContext("2d");
}
console.log("Final Assignment")