Randomly Positioning Squares in JavaScript? - javascript

Code isn't working, I need to randomly position a square component. I tried running some code, but nothing happens. Here's my code:
function component(width, height, color, x, y, type) {
this.type = type;
if (type == "image"){
this.image = new Image();
this.image.src = color;
}
this.score = 0;
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.gravity = 0;
this.gravitySpeed = 0;
this.update = function() {
ctx = myGameArea.context;
if (this.type == "image"){
ctx.drawImage(this.image,this.x, this.y, this.width,this.height);
} else {
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
}
function startGame() {
random = Math.floor((Math.random()*100) + 1);
document.write(random);
random2 = Math.floor((Math.random()*100) + 1);
document.write(random2);
square = new component(random, random2, "green", random, random2);
myGameArea.start();
return square
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 450;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 1);
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function updateGameArea() {
myGameArea.clear();
square.update();
}
For some reason, the function startGame doesn't work correctly. Nothing happens when I run the code. I opened the console log as well, and no syntax errors registered.

You can get the code to work by applying it like this, for example:
function component(width, height, color, x, y, type) {
this.type = type;
if (type == "image"){
this.image = new Image();
this.image.src = color;
}
this.score = 0;
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.gravity = 0;
this.gravitySpeed = 0;
this.color=color;
this.update = function() {
random = Math.floor((Math.random()*100) + 1);
random2 = Math.floor((Math.random()*100) + 1);
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
randcolor=getRandomColor();
ctx = myGameArea.context;
if (this.type == "image"){
ctx.drawImage(this.image, random, random2, random,random2);
} else {
ctx.fillStyle = randcolor;
ctx.fillRect(random, random2, random, random2);
}
this.x=random;
this.y=random2;
this.width=random;
this.height=random2;
this.color=randcolor;
}
}
function startGame() {
random = Math.floor((Math.random()*100) + 1);
random2 = Math.floor((Math.random()*100) + 1);
square = new component(random, random2, "green", random, random2);
myGameArea.start();
return square
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 450;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 1);
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function updateGameArea() {
myGameArea.clear();
square.update();
}
document.getElementById("start").addEventListener('click', startGame)
<div id="start">press to start</div>
In here I did three things:
I added a text that you can click
I added an event listener on this text that invokes the startGame() function
I got rid of the document.write() statements. I built this is Jsfiddle, which doesn't allow it, and it's considered bad practice anyway.

Related

Javascript Game: How to generate enemies (images) from an array

I was successful in generating enemies (out of one image) with an array, however, I'm stuck in trying to generate enemies out of more than one image (e. g. 5 different images, thus 5 different enemies)
Here is my code that works:
Enemies (enemyImg - one image) are generated
/** #type {HTMLCanvasElement} */
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const backgroundImg = document.getElementById("background");
const playerImg = document.getElementById("player");
const enemyImg = document.getElementById("enemy");
canvas.width = 800;
canvas.height = 500;
const enemies = [];
class Enemy {
constructor(x, y, w, h, speed) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.speed = speed;
}
draw() {
ctx.drawImage(enemyImg, this.x, this.y, this.w, this.h);
}
update() {
this.x = this.x - this.speed;
}
}
function spawnEnemies() {
setInterval(() => {
let w = 100;
let h = 40;
let x = canvas.width;
let y = Math.random() * Math.abs(canvas.height - h);
let speed = 5;
enemies.push(new Enemy(x, y, w, h, speed));
}, 1000);
}
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
enemies.forEach((enemy) => {
enemy.draw();
enemy.update();
});
}
animate();
spawnEnemies();
Here is the code, that does not work. I do not get any error message at all:
I have 6 images in one folder, named enemy_1.png to enemy_6.png) and I want them to be generated;
/** #type {HTMLCanvasElement} */
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const backgroundImg = document.getElementById("background");
const playerImg = document.getElementById("player");
const enemyImg = document.getElementById("enemy");
canvas.width = 800;
canvas.height = 500;
let enemies = [];
class Enemy {
constructor(img, x, y, w, h, speed) {
this.img = img;
(this.x = x),
(this.y = y),
(this.w = w),
(this.h = h),
(this.speed = speed);
}
draw() {
ctx.drawImage(img, this.x, this.y, this.w, this.h);
}
move() {
this.x = this.x - this.speed;
}
}
function createEnemies() {
setInterval(() => {
let w = 40;
let h = 72;
let x = 300;
let y = Math.random() * Math.abs(canvas.height - h);
let speed = 5;
enemies.length = 6;
for (let i = 1; i < enemies.length; i++) {
enemies[i] = new Image();
enemies[i].src = "./images/enemy_" + i + ".png";
enemies.push(new Enemy(enemies[i], x, y, w, h, speed));
}
}, 2000);
}
function createGame() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
enemies.forEach((enemy) => {
enemy.draw();
enemy.move();
});
requestAnimationFrame(createGame);
}
createGame();
createEnemies();
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const backgroundImg = document.createElement('img');
const playerImg = document.createElement('img');
canvas.width = 500;
canvas.height = 200;
// load your images:
const imagesCount = 0; // I have not this images, so its zero for me
const enemyImages = [];
for (let i = 1; i < imagesCount; i++) {
const img = new Image();
img.src = "./images/enemy_" + i + ".png";
enemyImages.push(img);
}
// I have not your images so i take some random pictures:
const enemyImage1 = new Image();
enemyImage1.src = 'https://pngimg.com/uploads/birds/birds_PNG106.png';
const enemyImage2 = new Image();
enemyImage2.src = 'https://purepng.com/public/uploads/large/purepng.com-magpie-birdbirdsflyanimals-631522936729bqeju.png';
const enemyImage3 = new Image();
enemyImage3.src = 'https://www.nsbpictures.com/wp-content/uploads/2018/10/birds-png.png';
enemyImages.push(
enemyImage1,
enemyImage2,
enemyImage3,
);
const enemies = [];
class Enemy {
constructor(x, y, w, h, speed, img) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.speed = speed;
// Self image:
this.img = img;
}
draw() {
// Draw self image:
ctx.drawImage(this.img, this.x, this.y, this.w, this.h);
}
update() {
this.x = this.x - this.speed;
}
}
function spawnEnemies() {
setInterval(() => {
let w = 60;
let h = 50;
let x = canvas.width;
let y = Math.random() * Math.abs(canvas.height - h);
let speed = 5;
enemies.push(new Enemy(x, y, w, h, speed,
// Pick random image from array:
enemyImages[Math.floor(Math.random()*enemyImages.length)]
));
}, 1000);
}
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
enemies.forEach((enemy) => {
enemy.draw();
enemy.update();
});
}
animate();
spawnEnemies();
<canvas id=canvas></canvas>

Building simple 2d javascript game, how to stop game piece leaving the canvass

So i'm new to this and have probably coded it wrong to start off with. I'm thinking after doing research that i should have stored my other game pieces in an array or as seperate variables. Please correct me if im wrong.
Here is my code
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:5px solid #d3d3d3;
background-color: green;
}
</style>
</head>
<body onload="startGame()">
<script>
var myGamePiece;
var myObstacle
function startGame() {
myGamePiece = new component(30, 30, "black", 350, 445);
blueGamePiece = new component(20, 20, "blue", 20, 20);
whiteGamePiece = new component(5, 40, "white",400, 20);
brownGamePiece = new component(25, 25, "brown", 650, 20);
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 700;
this.canvas.height = 480;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function (e) {
myGameArea.key = e.keyCode;
})
window.addEventListener('keyup', function (e) {
myGameArea.key = false;
})
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop : function() {
clearInterval(this.interval);
}
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function(){
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
}
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.key && myGameArea.key == 37) {myGamePiece.speedX = -5; }
if (myGameArea.key && myGameArea.key == 39) {myGamePiece.speedX = 5;}
myGamePiece.newPos();
myGamePiece.update();
myGamePiece.update();
blueGamePiece.y += 1;
blueGamePiece.update();
whiteGamePiece.y +=3;
whiteGamePiece.update();
brownGamePiece.y +=2;
brownGamePiece.update();
}
</script>
</body>
</html>
I simply want to stop myGamePiece leaving the canvass not bounce it back.
Any other advice would be more than welcome.
Thankyou very much in advance.
Solution: Replace "this.update" function with this code.
this.update = function(){
if(this.x < 0){this.x = 0}
if(this.y < 0){this.y = 0}
if(this.x + this.width > myGameArea.canvas.width){this.x = myGameArea.canvas.width - this.width}
if(this.y + this.height > myGameArea.canvas.height){this.y = myGameArea.canvas.height - this.height}
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}

Why wont my image draw but it loads?

I'm starting to make a game and I'm putting together a little "game engine" to do stuff easily and not type so repetitively. I have a sprite function that loads the image and an update function which draws it. The problem is it won't draw, and no errors have been reported in the console.
jsfiddle
var canvas = document.createElement("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvas.style.position = "absolute";
canvas.style.right = "0px";
canvas.style.top = "0px";
document.body.appendChild(canvas);
var c = canvas.getContext("2d");
var Squares = [];
var Square = function(x,y,w,h,color="black") {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.color = color;
Squares.push(this);
return this
}
var Sprites = [];
var Sprite = function(x,y,w,h,src) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.src = src;
this.img = new Image();
this.img.onload = function() {
}
this.img.src = this.src;
this.img.width = this.w;
this.img.height = this.h;
return this
}
function Clear(x,y,w,h) {
c.clearRect(x,y,w,h);
}
function Update() {
Clear(0,0,canvas.width,canvas.height);
for(var square in Squares) {
c.fillStyle = Squares[square].color;
c.fillRect(Squares[square].x,Squares[square].y,Squares[square].w,Squares[square].h);
}
for(var sprite in Sprites) {
console.log(Sprites[sprite].img)
Sprites[sprite].img.onload = function() {
c.drawImage(Sprites[sprite].img);
}
}
}
var ground = new Square(0,0,canvas.width,canvas.height,color="forestgreen");
var player = new Square(10,10,6,6,color="red");
var Mtn = new Sprite(50,50,50,50,"mountain.png");
console.log(Mtn.img)
function Logic() {
}
function Main() {
Logic();
Update();
}
setInterval(Main,2);

class does not draw on Canvas

I've been trying to draw on a canvas using the new Ecma6 class system, however after alot of research it just doesn't want to work. I'm passing the context as a paramater of the draw function, even when I log context it doesn't say it's empty or undefined.
Can any of you nice people help me?
This is my code:
class Canvas {
constructor() {
this.canvas = document.getElementById('canvas');
this.context = this.canvas.getContext('2d');
this.width = this.canvas.width;
this.height = this.canvas.height;
this.components = [];
}
draw() {
this.context.clearRect(0, 0, this.width, this.height);
this.context.globalCompositeOperation = 'hard-light';
this.components.map(e => e.draw(this.context));
window.requestAnimationFrame(this.draw.bind(this));
}
add(e) {
this.components.push(e);
this.components.sort(function (a, b) {
return a.layer - b.layer;
});
}
listeners() {
window.addEventListener('resize', () => {
this.width = this.canvas.width;
this.height = this.canvas.height;
}, false);
}
init() {
this.listeners();
this.draw();
}
}
class CanvasElement {
constructor(x, y, height, width, layer) {
this.position = {
x: x,
y: y
}
this.height = height;
this.width = width;
this.layer = layer;
this.color = "grey";
}
draw(context) {
context.fillStyle = this.color;
context.fillRect(this.x, this.y, this.width, this.height);
}
}
class CanvasImage extends CanvasElement {
constructor(x, y, image, context) {
super(x, y, image.width, image.height, 0);
let self = this;
this.image = new Image();
this.image.onload = function () {
self.imageReadyToUse = true;
self.width = this.width;
self.height = this.height;
}
this.image.src = image;
this.imageReadyToUse = false;
}
draw(context) {
if (this.imageReadyToUse) {
context.drawImage(this.image, this.x, this.y);
}
}
}
Your error lies on the position in the drawImage method.
Your this.x and this.y values are undefined.
Here is a working example:
var imageURL = "data:image/gif;base64,R0lGODlhPQBEAPeoAJosM//AwO/AwHVYZ/z595kzAP/s7P+goOXMv8+fhw/v739/f+8PD98fH/8mJl+fn/9ZWb8/PzWlwv///6wWGbImAPgTEMImIN9gUFCEm/gDALULDN8PAD6atYdCTX9gUNKlj8wZAKUsAOzZz+UMAOsJAP/Z2ccMDA8PD/95eX5NWvsJCOVNQPtfX/8zM8+QePLl38MGBr8JCP+zs9myn/8GBqwpAP/GxgwJCPny78lzYLgjAJ8vAP9fX/+MjMUcAN8zM/9wcM8ZGcATEL+QePdZWf/29uc/P9cmJu9MTDImIN+/r7+/vz8/P8VNQGNugV8AAF9fX8swMNgTAFlDOICAgPNSUnNWSMQ5MBAQEJE3QPIGAM9AQMqGcG9vb6MhJsEdGM8vLx8fH98AANIWAMuQeL8fABkTEPPQ0OM5OSYdGFl5jo+Pj/+pqcsTE78wMFNGQLYmID4dGPvd3UBAQJmTkP+8vH9QUK+vr8ZWSHpzcJMmILdwcLOGcHRQUHxwcK9PT9DQ0O/v70w5MLypoG8wKOuwsP/g4P/Q0IcwKEswKMl8aJ9fX2xjdOtGRs/Pz+Dg4GImIP8gIH0sKEAwKKmTiKZ8aB/f39Wsl+LFt8dgUE9PT5x5aHBwcP+AgP+WltdgYMyZfyywz78AAAAAAAD///8AAP9mZv///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAKgALAAAAAA9AEQAAAj/AFEJHEiwoMGDCBMqXMiwocAbBww4nEhxoYkUpzJGrMixogkfGUNqlNixJEIDB0SqHGmyJSojM1bKZOmyop0gM3Oe2liTISKMOoPy7GnwY9CjIYcSRYm0aVKSLmE6nfq05QycVLPuhDrxBlCtYJUqNAq2bNWEBj6ZXRuyxZyDRtqwnXvkhACDV+euTeJm1Ki7A73qNWtFiF+/gA95Gly2CJLDhwEHMOUAAuOpLYDEgBxZ4GRTlC1fDnpkM+fOqD6DDj1aZpITp0dtGCDhr+fVuCu3zlg49ijaokTZTo27uG7Gjn2P+hI8+PDPERoUB318bWbfAJ5sUNFcuGRTYUqV/3ogfXp1rWlMc6awJjiAAd2fm4ogXjz56aypOoIde4OE5u/F9x199dlXnnGiHZWEYbGpsAEA3QXYnHwEFliKAgswgJ8LPeiUXGwedCAKABACCN+EA1pYIIYaFlcDhytd51sGAJbo3onOpajiihlO92KHGaUXGwWjUBChjSPiWJuOO/LYIm4v1tXfE6J4gCSJEZ7YgRYUNrkji9P55sF/ogxw5ZkSqIDaZBV6aSGYq/lGZplndkckZ98xoICbTcIJGQAZcNmdmUc210hs35nCyJ58fgmIKX5RQGOZowxaZwYA+JaoKQwswGijBV4C6SiTUmpphMspJx9unX4KaimjDv9aaXOEBteBqmuuxgEHoLX6Kqx+yXqqBANsgCtit4FWQAEkrNbpq7HSOmtwag5w57GrmlJBASEU18ADjUYb3ADTinIttsgSB1oJFfA63bduimuqKB1keqwUhoCSK374wbujvOSu4QG6UvxBRydcpKsav++Ca6G8A6Pr1x2kVMyHwsVxUALDq/krnrhPSOzXG1lUTIoffqGR7Goi2MAxbv6O2kEG56I7CSlRsEFKFVyovDJoIRTg7sugNRDGqCJzJgcKE0ywc0ELm6KBCCJo8DIPFeCWNGcyqNFE06ToAfV0HBRgxsvLThHn1oddQMrXj5DyAQgjEHSAJMWZwS3HPxT/QMbabI/iBCliMLEJKX2EEkomBAUCxRi42VDADxyTYDVogV+wSChqmKxEKCDAYFDFj4OmwbY7bDGdBhtrnTQYOigeChUmc1K3QTnAUfEgGFgAWt88hKA6aCRIXhxnQ1yg3BCayK44EWdkUQcBByEQChFXfCB776aQsG0BIlQgQgE8qO26X1h8cEUep8ngRBnOy74E9QgRgEAC8SvOfQkh7FDBDmS43PmGoIiKUUEGkMEC/PJHgxw0xH74yx/3XnaYRJgMB8obxQW6kL9QYEJ0FIFgByfIL7/IQAlvQwEpnAC7DtLNJCKUoO/w45c44GwCXiAFB/OXAATQryUxdN4LfFiwgjCNYg+kYMIEFkCKDs6PKAIJouyGWMS1FSKJOMRB/BoIxYJIUXFUxNwoIkEKPAgCBZSQHQ1A2EWDfDEUVLyADj5AChSIQW6gu10bE/JG2VnCZGfo4R4d0sdQoBAHhPjhIB94v/wRoRKQWGRHgrhGSQJxCS+0pCZbEhAAOw==";
class Canvas {
constructor() {
this.canvas = document.getElementById('canvas');
this.context = this.canvas.getContext('2d');
this.width = this.canvas.width;
this.height = this.canvas.height;
this.components = [];
}
draw() {
this.context.clearRect(0, 0, this.width, this.height);
this.context.globalCompositeOperation = 'hard-light';
this.components.map(e => e.draw(this.context));
window.requestAnimationFrame(this.draw.bind(this));
}
add(e) {
this.components.push(e);
this.components.sort(function (a, b) {
return a.layer - b.layer;
});
}
listeners() {
window.addEventListener('resize', () => {
this.width = this.canvas.width;
this.height = this.canvas.height;
}, false);
}
init() {
this.listeners();
this.draw();
}
}
class CanvasElement {
constructor(x, y, height, width, layer) {
this.position = {
x: x,
y: y
}
this.height = height;
this.width = width;
this.layer = layer;
this.color = "grey";
}
draw(context) {
context.fillStyle = this.color;
context.fillRect(this.x, this.y, this.width, this.height);
}
}
class CanvasImage extends CanvasElement {
constructor(x, y, size, context) {
super(x, y, size.width, size.height, 0);
let self = this;
this.context = context;
this.image = new Image();
this.image.onload = function () {
self.imageReadyToUse = true;
self.width = this.width;
self.height = this.height;
self.draw();
}
this.image.src = imageURL;
this.imageReadyToUse = false;
}
draw() {
if (this.imageReadyToUse) {
console.log("YOU ARE UNDEFINED:", this.x, this.y);
this.context.drawImage(this.image, 0, 0, 61, 68);
}
}
}
var canvas = new Canvas();
var canvasImage = new CanvasImage(0, 0, {width:61, height:68}, canvas.context);
canvasImage.draw();
<canvas style="border:1px solid grey" id="canvas" width="400" height="400"></canvas>
sdsdc
So I found out what the problem was. Instead of using this.x and this.y, I had to use this.position.x and this.position.y.
Thank you for your help!

Collision detection between circle and rectangle in Javascript game?

I'm creating a javascript game where I need a collision between the ball and rectangle to trigger a reset of the game. For now I just have an alert there for testing purposes. I'm having trouble getting the collision detection working.
This is what I've got so far but it isn't working
function startGame() {
keeper = new obstacle(40, 20, "#666", 130, 180);
theBall = new component("#000", 80, 10);
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 300;
this.canvas.height = 250;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function(e) {
myGameArea.key = e.keyCode;
})
window.addEventListener('keyup', function(e) {
myGameArea.key = false;
})
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function component(color, x, y, type) {
this.type = type;
this.speed = 1.5;
this.angle = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.beginPath();
ctx.arc(this.x, this.y, 10, 0, 2 * Math.PI);
ctx.fillStyle = color;
ctx.fill();
ctx.restore();
}
this.newPos = function() {
this.x -= this.speed * Math.sin(this.angle);
this.y += this.speed * Math.cos(this.angle);
}
}
function obstacle(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
}
this.collideWith = function(theBall){
var collide = true;
var myTop =this.y;
var theBallBottom = theBall.y + (theBall.radius)
if (myTop < theBallBottom)
{
collide = false;
}
return collide;
}
}
function updateGameArea() {
if (keeper.crashWith(theBall)) {
alert("Collision");
} else {
myGameArea.clear();
theBall.newPos();
theBall.update();
keeper.speedX = 0;
keeper.speedY = 0;
if (myGameArea.key && myGameArea.key == 37) {keeper.speedX = -1; }
if (myGameArea.key && myGameArea.key == 39) {keeper.speedX = 1; }
keeper.newPos();
keeper.update();
}
}
The game can be found here http://alexhollingsworth.co.uk/game.php
You named your method collideWith, but you are calling it crashWith in the update method. Plus this will only detect collision on y axis, but I assume this is intended.
I made an if statement that can detect collisions in JavaScript, here it is:
if circle x < rect x + circle width && circle x + rect width > rect x && circle y < rect y + circle height && rect height + circle y > rect y {
This works by putting the ball into an 'imaginary box', then senses if any of the edges of the 'imaginary box' come in contact with any of the edges of the rectangle. I hope this helped.

Categories

Resources