How do i detect collision betwen two animated balls? - javascript

I'm trying to make a simple shooter, but I have some problems with detecting collisions between the shots and the enemy (blue balls). I have tried several things, but I can't figure it out
Can someone pliz please help me?
var canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
var tileldig = Math.floor((Math.random() * 300) + 1);
var tekst = document.getElementById("tekst")
var kuler = [
{r: 10, x: canvas.width/2, y: canvas.height-100, f: "red", dy:0},
//{r: 50, x: tileldig, y: 50, vx:0 , vy: 3, f: "green"},
]
var fiender = [
{r: 20, x: tileldig, y: -20, vx:0 , vy: 1, },
]
/*var skudder = [
{r: 10, x:0+kuler.x, y: 0+kuler.y, f: "black"},
]*/
function spill() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < kuler.length; i++) {
kuler[i].x += 0;
kuler[i].y += kuler[i].dy;
ctx.fillStyle = kuler[i].f;
ctx.beginPath();
ctx.arc(kuler[i].x, kuler[i].y, kuler[i].r, 2*Math.PI, 0);
ctx.closePath();
ctx.fill();
if (kuler[0].x >= canvas.width-kuler[0].r) {
kuler[0].x = canvas.width-kuler[0].r
};
if (kuler[0].x <= 0+kuler[0].r) {
kuler[0].x = 0+kuler[0].r
};
if (kuler[0].y >= canvas.height-kuler[0].r) {
kuler[0].y = canvas.height-kuler[0].r
};
if (kuler[0].y <= 0+kuler[0].r) {
kuler[0].y = 0+kuler[0].r
};
for (var j = 0; j < fiender.length; j++) {
ctx.fillStyle = "blue";
ctx.beginPath();
ctx.arc(fiender[j].x, fiender[j].y, fiender[j].r, 2*Math.PI, 0);
ctx.closePath();
ctx.fill();
fiender[j].y += fiender[j].vy;
if (fiender[j].y >= canvas.height) {
fiender.splice(j,1);
console.log("ute");
};
if (fiender[j].y + fiender[j].r >= kuler[i].y && fiender[j].x + fiender[j].r == kuler[i].x) { // remove kuler[i] and fiender[j] }
fiender.splice(j, 1);
kuler.splice(i,1);
};
if(j > 1){
fiender.splice(j,1)
}
}
}
document.onkeydown = function tast (e) {
switch (e.keyCode) {
case 37:
kuler[0].x -= 10;
break;
case 39:
kuler[0].x += 10;
break;
case 38:
kuler[0].y -= 10;
break;
case 40:
kuler[0].y += 10;
break;
case 32:
newskudd()
console.log("hit space")
break;
}
};
requestAnimationFrame(spill);
}
function newskudd () {
var nyttskudd =
{x:kuler[0].x, y:kuler[0].y, r:5, dy:-5, f:"black"};
kuler.push(nyttskudd);
};
setInterval(
function(){
fiender.push({r: 20, x: Math.floor((Math.random() * 300) + 1), y: -20, vx:0 , vy: 1, f: "green"});
}, 1000);
spill();
/*for (var i = 0; i < kuler.length; i++) {
for (var j = 0; j < fiender.length; j++) {
if (kuler[i].y >= fiender[j].y) { // remove kuler[i] and fiender[j] }
};
}*/
/*if (circles.x >= canvas.height- circles.r){
circles.splice(i,1);
}*/
If you want to see a demo, click the link: DEMO

Your conditional should look like:
var distanceFromCenters = Math.sqrt(Math.pow(Math.abs(fiender[j].x - kuler[i].x),2) + Math.pow(Math.abs(fiender[j].y - kuler[i].y),2 );
if (distanceFromCenters <= (fiender[j].r + kuler[i].r)) {
// you have a collision

Related

How to make a smooth car moving animation?

I created a RaceTrack game, where you simply drive a car, collect yellow bonuses and avoid black obstacles.
The problem is that the animation of my car is not smooth ( When u try to go left or right etc. )
Can someone help me understand how can I do a smooth animation when steering a car ?
How could I add a spontanious curves instead of straight road?
Ps. I know my ColissionChecker() functions aren't perfect, but that is a problem for another day.
I don't know why in snippet's Full Page the canvas is very small and you can't see anything.
var canvas = document.querySelector('canvas');
var c = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var LineWidth = 10;
var LineHeight = 80;
var boundaryTopOffset = 5;
var boundaryLeftOffset = 2;
var boundaryPadding = 50;
var boundaryMiddleOffset = 2;
var speed = 50;
let executedTimer = false;
let dateDiff;
let currentScore = 0;
var leftBoundary = [];
var rightBoundary = [];
var middleBoundary = [];
var bonuses = [];
var obstacles = [];
var car = {
x: 1200,
y: 800
}
document.addEventListener('keydown', function(event) {
let key = event.which
if(key === 37) {
car.x -= speed;
} else if(key === 39) {
car.x += speed;
} else if(key === 38) {
car.y -= speed;
} else if(key === 40) {
car.y += speed;
}
})
for (x = 0; x < 8; x++) {
leftBoundary[x] =
{
offset: boundaryLeftOffset + 400,
topOffset: 0,
width: LineWidth,
height: LineHeight,
color: "red"
};
}
for (x = 0; x < 8; x++) {
middleBoundary[x] =
{
offset: boundaryMiddleOffset + 890,
topOffset: 0,
width: LineWidth,
height: LineHeight,
color: "white"
};
}
for (x = 0; x < 8; x++) {
rightBoundary[x] =
{
offset: boundaryLeftOffset + 1400,
topOffset: 0,
width: LineWidth,
height: LineHeight,
color: "red"
};
}
var cycle = 0,
totalCycle = LineHeight + boundaryPadding;
window.requestAnimationFrame(draw);
function draw() {
if(executedTimer == false) {
obstacles.push({x: Math.floor((Math.random() * 1000) + 450), y: 10});
timerStart();
}
drawCanvas(boundaryLeftOffset-2, 0, canvas.width, canvas.height, 'grey');
cycle = (cycle + 4) % totalCycle;
for (boundary of [leftBoundary, rightBoundary, middleBoundary]) {
for (i = 0; i < boundary.length; i++) {
boundary[i].topOffset = cycle + (i-1) * totalCycle;
drawBoundary(boundary[i], boundary[i].color);
}
}
if(dateDiff >= 1000) {
obstacles.push({x: Math.floor((Math.random() * 900) + 490), y: 10});
bonuses.push({x: Math.floor((Math.random() * 900) + 490), y: 10})
}
drawScore();
drawObstacle();
drawBonus();
drawCar();
obstacleColissionChecker();
bonusColissionChecker();
timerCheck();
window.requestAnimationFrame(draw);
}
function drawBoundary(x, elementColor) {
c.fillStyle = elementColor;
c.fillRect(x.offset+100, x.topOffset, x.width, x.height);
}
function drawCanvas(posX, posY, width, height, elementColor) {
c.fillStyle = elementColor;
c.fillRect(posX, posY, width, height);
}
function drawCar() {
c.fillStyle = "blue";
c.fillRect(car.x, car.y, 100, 150);
c.fillStyle = "black";
for(var i = 0; i < 101; i+=100){
c.beginPath();
c.ellipse(car.x + i, car.y + 10, 10, 15, Math.PI, 0, 2 * Math.PI);
c.ellipse(car.x + i, car.y + 140, 10, 15, Math.PI, 0, 2 * Math.PI);
c.fill();
c.closePath();
}
}
function timerStart() {
date1 = new Date();
executedTimer = true;
}
function timerCheck() {
var date2 = new Date();
dateDiff = Math.abs(date1 - date2);
if(dateDiff >= 1000)date1 = date2;
}
function drawScore() {
c.font='25px Verdana';
c.fillStyle = 'hsl('+ 0 +', 100%, 50%)';
c.fillText('Score : ' + currentScore, 100, 80);
}
function drawObstacle() {
c.fillStyle = "#080D23";
for(obstacle of [obstacles]) {
for (i = 0; i < obstacles.length; i++) {
c.fillRect(obstacle[i].x, obstacle[i].y+= 5, 80, 50);
}
}
}
function drawBonus() {
c.fillStyle = "#F2C14A";
for(bonus of [bonuses]) {
for (i = 0; i < bonuses.length; i++) {
c.beginPath();
c.arc(bonuses[i].x, bonuses[i].y+= 5, 20, 0, Math.PI * 2, false);
c.fill();
c.closePath();
}
}
}
function obstacleColissionChecker() {
for (i = 0; i < obstacles.length; i++) {
if(car.y + 20 - obstacles[i]?.y + 20 > 0 && car.y - 20 - obstacles[i]?.y + 20 < 100
&& car.x + 100 - obstacles[i]?.x + 20 > 0 && car.x - 100 - obstacles[i]?.x - 20 < 200) {
currentScore--;
}
}
}
function bonusColissionChecker() {
for (i = 0; i < bonuses.length; i++) {
if(car.y + 20 - bonuses[i]?.y + 20 > 0 && car.y - 20 - bonuses[i]?.y + 20 < 100
&& car.x + 100 - bonuses[i]?.x + 20 > 0 && car.x - 100 - bonuses[i]?.x - 20 < 200) {
currentScore++;
}
}
}
canvas {
border: 1px solid black;
margin: 0 !important;
padding: 0 !important;
}
body {
margin: 0;
}
<canvas></canvas>
In your code the speed is constant.
The car is either moving at that speed or is not moving.
This is the problem : you need to introduce acceleration.
You should car.x += speed on every frame and alter the speed in the key press handler. It would be a good start for you.

Integrate GSAP with canvas to make a curvy timeline

I'm currently working on a canvas timeline-like animation.
This is what I made so far...
$(function() {
'use strict';
var canvas = document.querySelector('#canvas');
var ctx = canvas.getContext('2d');
var s = 20;
var arr = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100];
var colorP = ['#ff5454', '#ffa144', '#ffe256', '#aaff75', '#8cd8ff', '#b5b6ff', '#b882ff'];
var dots = [];
var rDots = [];
function init() {
var reverse = true;
for (var i = 0; i < 100; i++) {
var dot = new Object();
var height = null;
if (arr.indexOf(i) != -1) {
dot.x = s;
dot.y = 50;
dot.r = 3;
dot.c = 'red';
dot.f = 'rgba(0,0,0,0)';
dot.t = '1';
dot.s = 0;
rDots.push(dot);
} else {
dot.x = s;
dot.y = 50;
dot.r = 1;
dot.c = 'red';
dot.f = '';
dot.t = '';
dot.s = 0;
}
s += 10;
dots.push(dot);
};
function tween() {
height = Math.floor(Math.random() * (75 - 25) + 25);
TweenMax.staggerTo(dots, 5, {
y: height,
yoyo: true,
repeat: 'repeat',
repeatDelay: 1,
ease: Sine.easeInOut
}, 0.5);
};
tween();
setInterval(function() {
tween()
}, 4800);
}
init();
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < dots.length - 1; i++) {
ctx.beginPath();
ctx.moveTo(dots[i].x, dots[i].y);
ctx.lineTo(dots[i + 1].x, dots[i + 1].y);
ctx.lineWidth = 3;
ctx.strokeStyle = 'red';
ctx.stroke();
};
for (var i = 0; i < dots.length; i++) {
ctx.beginPath();
ctx.arc(dots[i].x, dots[i].y, dots[i].r, 0, 2 * Math.PI);
ctx.strokeStyle = dots[i].c;
ctx.lineWidth = 1;
ctx.fillStyle = dots[i].f;
ctx.fill();
ctx.stroke();
ctx.font = dots[i].s + 'px Arial';
ctx.textAlign = 'center';
ctx.fillStyle = '#FFF';
ctx.fillText(dots[i].t, dots[i].x, dots[i].y + 4);
};
setTimeout(function() {
draw();
}, 5);
}
draw();
function hover(e, bool) {
var dot = canvas.getBoundingClientRect();
var x = e.clientX - dot.left;
var y = e.clientY - dot.top;
for (var i = 0; i < rDots.length; i++) {
if (x == rDots[i].x) {
TweenMax.to(rDots[i], 0.1, {
r: 10,
f: 'red',
s: 8
});
$('body').css('cursor', 'pointer');
} else {
TweenMax.to(rDots[i], 0.1, {
r: 3,
f: 'rgba(0,0,0,0)',
s: 0
});
}
};
};
$(canvas).on('mousemove', function(e) {
hover(e, true);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" height="100" width="1050" style="background: #EEE"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.19.1/TweenMax.min.js"></script>
The idea is,
I want it to swing randomly (checked)
and when the cursor close in the knot, it will enlarge and show the text in it...
I tried to use x and y axis to do the trick,
but it doesn't work well...
Then I tried to make another function to draw a bigger circle to cover the original knot,
but since my draw() keeping clear the canvas, so I failed again...
Wondering is there any better ways to make it work?
any suggestions or hints are welcome!
You may find jCanvas helpful.
It's a JavaScript library that wraps the HTML5 canvas API, letting you add certain object-like functionality using a jQuery-style syntax. You could refactor your code a bit and use a mouseOver effect rather than binding a mousemove event to the canvas, which will let you create a smother animation.
Also, if you increase the area of the rDots.x that's triggering your animation and set your Tween time interval to something a bit longer than 0.1 that makes the animation slightly less jerky as well.
Not sure if this solves your issue, but I hope it helps!
Ok, I've work my way out.
$(function() {
'use strict';
var dots = [],
eDots = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100],
rDots = [],
stagger = 0;
var canvas = document.querySelector('#canvas'),
ctx = canvas.getContext('2d');
//initialize all the dots obj
function init() {
for (var i = 0; i < 100; i++) {
if (eDots.indexOf(i) != -1) {
var dot = {
xAxis: stagger,
yAxis: 50,
radius: 3,
color: 'rgba(0,0,0,0)',
num: 1,
};
rDots.push(dot);
} else {
var dot = {
xAxis: stagger,
yAxis: 50,
radius: .5,
color: 'rgba(0,0,0,0)',
num: ''
};
}
dots.push(dot);
stagger += 10;
}
};
init();
//Save position property for click event
function getSize() {
for (var i = 0; i < rDots.length; i++) {
rDots[i].top = rDots[i].yAxis - rDots[i].radius;
rDots[i].right = rDots[i].xAxis + rDots[i].radius;
rDots[i].bottom = rDots[i].yAxis + rDots[i].radius;
rDots[i].left = rDots[i].xAxis - rDots[i].radius;
}
}
getSize();
//Hover event dots to change style
function hover() {
$(canvas).bind('mousemove', function(e) {
var dot = canvas.getBoundingClientRect(),
x = e.clientX - dot.left,
y = e.clientY - dot.top;
for (var i = 0; i < rDots.length; i++) {
ctx.beginPath();
ctx.arc(rDots[i].xAxis, rDots[i].yAxis, rDots[i].radius, 0, 2 * Math.PI);
//rDots[i].radius = ctx.isPointInPath(x, y) ? 10 : 3;
//rDots[i].color = ctx.isPointInPath(x, y) ? 'red' : 'rgba(0, 0, 0, 0)';
if (ctx.isPointInPath(x, y)) {
TweenMax.to(rDots[i], 0.1, {
radius: 10,
color: 'red',
});
$(canvas).css({
cursor: 'pointer'
});
return;
} else {
TweenMax.to(rDots[i], 0.1, {
radius: 3,
color: 'rgba(0,0,0,0)'
});
}
ctx.stroke();
ctx.fill();
$(canvas).css({
cursor: 'default'
});
}
});
};
hover();
//Setup click event for functioning purpose
function click(e) {
var dot = canvas.getBoundingClientRect(),
x = e.clientX - dot.left,
y = e.clientY - dot.top;
for (var i = 0; i < rDots.length; i++) {
if (x < rDots[i].right && x > rDots[i].left && y > rDots[i].top && y < rDots[i].bottom) {
console.log('This is dot ' + i);
}
}
};
$(canvas).on('click', function(e) {
click(e);
})
//Let the line start to twist
function tween() {
var height = Math.floor(Math.random() * (75 - 25) + 25);
TweenMax.staggerTo(dots, 4, {
yAxis: height,
yoyo: true,
repeat: 'repeat',
repeatDelay: 1,
ease: Sine.easeInOut
}, 0.5);
setTimeout(function() {
tween();
}, 3800);
}
tween();
//Let's get some paint
function draw() {
//clear canvas for animate
ctx.clearRect(0, 0, canvas.width, canvas.height);
//draw the lines
for (var i = 0; i < dots.length - 1; i++) {
ctx.moveTo(dots[i].xAxis, dots[i].yAxis);
ctx.lineTo(dots[i + 1].xAxis, dots[i + 1].yAxis);
ctx.lineWidth = 3;
ctx.stroke();
}
//draw the dots
for (var i = 0; i < dots.length; i++) {
ctx.beginPath();
ctx.arc(dots[i].xAxis, dots[i].yAxis, dots[i].radius, 0, 2 * Math.PI);
ctx.strokeStyle = 'red';
ctx.strokeWidth = '1px';
ctx.fillStyle = dots[i].color;
ctx.stroke();
ctx.fill()
};
setTimeout(function() {
draw();
}, 10);
}
draw();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.19.1/TweenMax.min.js"></script>
<canvas id="canvas" height="100" width="1000" style="background:#EEE"></canvas>
Turn's out all I need is to do is use isPointOnPath to get the path's axis,
then manipulate the certain dot's property with if statement, in my case is it's radius and color.
simple enough...
Can't believe I couldn't figured it out.
I guess I need some sleep now XD

How do I get one singel array inside a for-loop?

i have a simpel game but when the red ball hits the blue ball while in motion the SPLICING desen't work i get the error form the movement script. I think the best solution to this problem is to registrer a collition when only the red ball hits the blu ball. can somone help me whith that?
To se a demo clik the linkDEMO press R to restart
Code:
var canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
var tileldig = Math.floor((Math.random() * 300) + 1);
var tekst = document.getElementById("tekst")
var log = document.getElementById("log")
var highlog = document.getElementById("highlog")
var kuler = [{
r: 10,
x: canvas.width / 2,
y: canvas.height - 100,
f: "red",
dy: 0
}, ];
var fiender = [{
r: 20,
x: tileldig,
y: -20,
vx: 0,
vy: 1,
}, ];
//var snd = new Audio("Skudd.m4a");
var poeng = 0;
var highscore = 0;
var høyre = 0;
var venstre = 0;
var opp = 0;
var ned = 0;
var restart = 0;
var død = 0;
document.onkeydown = function tast(e) {
if (e.keyCode == 39) { // høyre
høyre = 1;
}
if (e.keyCode == 37) { // venstre
venstre = 1;
}
if (e.keyCode == 38) { // opp
opp = 1;
}
if (e.keyCode == 40) { // ned
ned = 1;
}
if (e.keyCode == 32) {
newskudd();
// snd.play();
console.log("hit space")
}
if (e.keyCode == 82) {
init();
log.innerHTML += ("Poeng: " + poeng)
poeng = 0;
}
}
document.onkeyup = function tast2(e) {
if (e.keyCode == 39) { // høyre
høyre = 0;
}
if (e.keyCode == 37) { // venstre
venstre = 0;
}
if (e.keyCode == 38) { // opp
opp = 0;
}
if (e.keyCode == 40) { // ned
ned = 0;
}
}
function spill() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < kuler.length; i++) {
kuler[i].x += 0;
kuler[i].y += kuler[i].dy;
ctx.fillStyle = kuler[i].f;
ctx.beginPath();
ctx.arc(kuler[i].x, kuler[i].y, kuler[i].r, 2 * Math.PI, 0);
ctx.closePath();
ctx.fill();
if (kuler[0].x >= canvas.width - kuler[0].r) {
kuler[0].x = canvas.width - kuler[0].r
};
if (kuler[0].x <= 0 + kuler[0].r) {
kuler[0].x = 0 + kuler[0].r
};
if (kuler[0].y >= canvas.height - kuler[0].r) {
kuler[0].y = canvas.height - kuler[0].r
};
if (kuler[0].y <= 0 + kuler[0].r) {
kuler[0].y = 0 + kuler[0].r
};
for (var j = 0; j < fiender.length; j++) {
ctx.fillStyle = "blue";
ctx.beginPath();
ctx.arc(fiender[j].x, fiender[j].y, fiender[j].r, 2 * Math.PI, 0);
ctx.closePath();
ctx.fill();
if (fiender[j].x >= canvas.width - fiender[j].r) {
fiender[j].x = canvas.width - fiender[j].r;
};
if (fiender[j].x <= 0 + fiender[j].r) {
fiender[j].x = 0 + fiender[j].r;
};
if (fiender[j].vy >= 2) {
fiender[j].vy = 2;
};
var distanceFromCenters = Math.sqrt(Math.pow(Math.abs(fiender[j].x - kuler[i].x), 2) + Math.pow(Math.abs(fiender[j].y - kuler[i].y), 2)); // you have a collision
if (distanceFromCenters <= (fiender[j].r + kuler[i].r)) {
fiender.splice(j, 1);
kuler.splice(i, 1);
poeng += 1;
restart = 1;
} else if (fiender[j].y > canvas.height) {
fiender.splice(j, 1)
}
if (j > 1) {
fiender.splice(j, 1)
}
log.innerHTML = ("<br>" + "Score denne runden: " + poeng + "</br>" + "<br>" + "Highscore: " + highscore + "</br>")
if (poeng >= highscore) {
log.innerHTML += ("<br>" + "Ny Highscore: " + highscore + "</br>")
highscore = poeng;
}
}
}
for (var j = 0; j < fiender.length; j++) {
fiender[j].y += fiender[j].vy;
}
if (venstre == 1) {
kuler[0].x -= 4;
}
if (høyre == 1) {
kuler[0].x += 4;;
}
if (opp == 1) {
kuler[0].y -= 4;
}
if (ned == 1) {
kuler[0].y += 4;
}
requestAnimationFrame(spill);
return;
}
document.onload = spill();
function newskudd() {
var nyttskudd = {
x: kuler[0].x,
y: kuler[0].y,
r: 5,
dy: -5,
f: "white"
};
kuler.push(nyttskudd);
};
setInterval(function() {
fiender.push({
r: 20,
x: Math.floor((Math.random() * 300) + 1),
y: -20,
vx: 0,
vy: 1,
f: "green"
});
}, 1000);
function init() {
kuler = [{
r: 10,
x: canvas.width / 2,
y: canvas.height - 100,
f: "red",
dy: 0
}, ];
fiender = [{
r: 20,
x: tileldig,
y: -20,
vx: 0,
vy: 1,
}, ];
}

How do i get two canvas-animations to collide?

im trying to make a simpel game where i can shoot balls at other bals and then they dissapear. i have managed to make the animations work and i can shoot the balls but i dont know how to make them collide.
i have tried to do somethong at line 72-74 but i get the error "Cannot read property 'y' of undefined ".
to see demo the game click the link DEMO
var canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
var tileldig = Math.floor((Math.random() * 300) + 1);
var kuler = [
{r: 10, x: canvas.width/2, y: canvas.height-100, f: "red", dy:0},
//{r: 50, x: tileldig, y: 50, vx:0 , vy: 3, f: "green"},
]
var fiender = [
{r: 10, x: tileldig, y: 50, vx:0 , vy: 1, },
]
var skudder = [
{r: 10, x:0+kuler.x, y: 0+kuler.y, f: "black"},
]
function spill() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < kuler.length; i++) {
kuler[i].x += 0;
kuler[i].y += kuler[i].dy;
ctx.fillStyle = kuler[i].f;
ctx.beginPath();
ctx.arc(kuler[i].x, kuler[i].y, kuler[i].r, 2*Math.PI, 0);
ctx.closePath();
ctx.fill();
if (kuler[0].x >= canvas.width-kuler[0].r) {
kuler[0].x = canvas.width-kuler[0].r
};
if (kuler[0].x <= 0+kuler[0].r) {
kuler[0].x = 0+kuler[0].r
};
if (kuler[0].y >= canvas.height-kuler[0].r) {
kuler[0].y = canvas.height-kuler[0].r
};
if (kuler[0].y <= 0+kuler[0].r) {
kuler[0].y = 0+kuler[0].r
};
};
document.onkeydown = function tast (e) {
switch (e.keyCode) {
case 37:
kuler[0].x -= 10;
break;
case 39:
kuler[0].x += 10;
break;
case 38:
kuler[0].y -= 10;
break;
case 40:
kuler[0].y += 10;
break;
case 32:
newskudd()
console.log("hit space")
if(fiender[i].y >= skudder[1].y){
alert();
};
break;
}
};
for (var i = 0; i < fiender.length; i++) {
ctx.fillStyle = "blue";
ctx.beginPath();
ctx.arc(fiender[i].x, fiender[i].y, fiender[i].r, 2*Math.PI, 0);
ctx.closePath();
ctx.fill();
fiender[i].y += fiender[i].vy;
if (fiender[i].y >= canvas.height) {
fiender.splice(i,1);
console.log("ute");
};
}
requestAnimationFrame(spill);
}
function newskudd () {
var nyttskudd =
{x:kuler[0].x, y:kuler[0].y, r:5, dy:-5, f:"black"};
kuler.push(nyttskudd);
};
setInterval(function(){
fiender.push({r: 10, x: Math.floor((Math.random() * 300) + 1), y: 0, vx:0 , vy: 1, f: "green"});
}, 1000);
spill();
/*if (circles.x >= canvas.height- circles.r){
circles.splice(i,1);
}*/
This is the problem line:
if(fiender[i].y >= skudder[1].y){
You are outside of the loop here, so fiender[i] makes no sense. The quickest fix would be to loop through all the fiender items here using a for loop, just like you're doing 5-6 lines afterwards. Like this:
for (var i = 0; i < fiender.length; i++) {
if(fiender[i].y >= skudder[1].y){
alert();
};
}
Also, skudder[1] doesn't seem to exist, maybe it should be skudder[0].
You need to provide more info to get more accurate answers.
UPDATE: CODE sample as I promised
Sorry, I had to rewrite a lot of your code to make things more clean for me. I tried to keep your origin names.
Line 72-74 is not the place, where you can calculate collision ;)
I will try to give you few hints.
Delete this part, you dont need it.
console.log("hit space")
if(fiender[i].y >= skudder[1].y){
alert();
};
Each time you shoot, you add new bullet in "Array of kulers", which is already done in your function newskudd().
I guess you dont want to kill your enemy when space being hit, but when one ball meets another.
So in spill() go thrue all "bullets" and try to find out, if any of enemies is being hit. ==> every redraw your program will test, if anything is being hit
JS I made in update:
// constants
var TILELDIG = Math.floor((Math.random() * 300) + 1);
var NEW_ENEMY_INTERVAL = 1000;
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// basic graphic constructs (prototypes)
var EntityBall = function (position, color, delta, speed, size) {
this.size = size || 10;
this.position = position || [0, 0];
this.delta = delta || [0, 0];
this.speed = speed || [0, 0];
this.color = color || "black";
};
var Kuler = function (position) {
EntityBall.call(this, position, "black", [0, -10], [0, 0], 5);
};
var Fiender = function (position) {
EntityBall.call(this, position, "blue", [0, 1]);
};
var Skudder = function (position) {
EntityBall.call(this, position, "red", [0, 0], [5, 5]);
}
// Program constructor
var Program = function (ctx, canvas) {
this.ctx = ctx;
this.canvas = canvas;
this.init();
};
// Program inicialization
Program.prototype.init = function () {
// these arrays store living things
this.kulers = [];
this.fienders = [];
this.skudders = [];
this.hordeUpdate = null;
var player1 = new Skudder([canvas.width*0.5, canvas.height*0.75 ]);
this.skudders.push(player1);
// here you bind keys for moving main ball (player1)
document.addEventListener("keydown", this.player1Actions.bind(this, player1));
};
// handle player moves
Program.prototype.player1Actions = function (player1, e) {
switch (e.keyCode) {
case 37:
player1.position[0] -= player1.speed[0];
break;
case 39:
player1.position[0] += player1.speed[0];
break;
case 38:
player1.position[1] -= player1.speed[1];
break;
case 40:
player1.position[1] += player1.speed[1];
break;
case 32:
this.attack(player1);
console.log("hit space");
break;
}
if(player1.position[0] < 0) {
player1.position[0] = 0;
}
if(player1.position[0] > canvas.width) {
player1.position[0] = canvas.width;
}
if(player1.position[1] < 0) {
player1.position[1] = 0;
}
if(player1.position[1] > canvas.height) {
player1.position[1] = canvas.height;
}
};
// only spawns bullet, but doesnt calculate collision
Program.prototype.attack = function (player) {
var kulerPosition = [player.position[0], player.position[1]];
var kuler = new Kuler(kulerPosition);
this.kulers.push(kuler);
};
// main Program thread (refreshed 60 times per second)
Program.prototype.refresh = function () {
var canvas = this.canvas;
this.ctx.clearRect(0, 0, canvas.width, canvas.height);
// update all positions (delta move of each entity)
var list = [this.kulers, this.fienders, this.skudders];
for (var i = 0; i < list.length; i++) {
for (var j = 0; j < list[i].length; j++) {
// find new position
list[i][j].position[0] += list[i][j].delta[0];
list[i][j].position[1] += list[i][j].delta[1];
// delete entity if it is out of canvas (else all browser memory will be eaten by blue balls)
if (list[i][j].position[1] > canvas.height || list[i][j].position[1] < 0 || list[i][j].position[0] > canvas.width || list[i][j].position[0] < 0) {
list[i].splice(j, 1); // this delete it
};
}
}
// calculate bullets collision
for (var i = 0; i < this.kulers.length; i++) { // go thrue all bullets
for (var j = 0; j < this.fienders.length; j++) { // for each bullet go thrue all enemies
// find if this enemy is being hit
// (5 + 2.5), 5 is r of blue ball, 2.5 is r of black ball, you dont want to find perfect hit, scratches counts too
if ((this.kulers[i].position[0] >= this.fienders[j].position[0] - (5 + 2.5) && this.kulers[i].position[0] <= this.fienders[j].position[0] + (5 + 2.5)) && this.kulers[i].position[1] <= this.fienders[j].position[1]) {
this.kulers.splice(i, 1); // delete bullet that hits
this.fienders.splice(j, 1); // delete dead enemy
break;
}
}
}
// after all removes, draw all living entities
for (var i = 0; i < list.length; i++) {
for (var j = 0; j < list[i].length; j++) {
this.ctx.fillStyle = list[i][j].color;
ctx.beginPath();
ctx.arc(list[i][j].position[0], list[i][j].position[1], list[i][j].size, 2 * Math.PI, 0);
ctx.closePath();
ctx.fill();
}
}
// repeat
requestAnimationFrame(this.refresh.bind(this));
};
// this will start blue enemies coming
Program.prototype.hordeComing = function () {
this.hordeUpdate = setInterval(this.addEnemy.bind(this), NEW_ENEMY_INTERVAL);
};
// this spawn enemy
Program.prototype.addEnemy = function () {
var position = [Math.floor(Math.random() * canvas.width / 2) * 2, 0];
var fiender = new Fiender(position);
this.fienders.push(fiender);
};
// run program with params
var program1 = new Program(ctx, canvas);
program1.refresh();
program1.hordeComing();

How to add multiple colors to an array

I am trying to add multiple colors to an array in an HTML5 canvas animation. I am using an if statement to add 3 different colors based on the array index, but the only color showing up is the "else" color (orange). Below is the code.
window.onload = function() {
var canvas = document.getElementById('myCanvas'),
context = canvas.getContext('2d'),
w = window.innerWidth,
h = window.innerHeight,
total = 100,
gumballs = [];
canvas.width = w;
canvas.height = h;
for(var i = 0; i < total; i++) {
gumballs.push({
x: Math.random()* w,
y: Math.random()* h,
r: Math.random()* 4+3,
d: Math.random()*total
})
}
function draw() {
context.clearRect(0,0,w,h);
context.beginPath();
for(var i = 0; i < total; i++) {
var s = gumballs[i];
if(s % 3 === 0){
context.fillStyle = 'blue';
} else if (s % 4 === 0) {
context.fillStyle = 'red';
} else {
context.fillStyle = "orange";
}
context.moveTo(s.x, s.y);
context.arc(s.x, s.y, s.r, 0, Math.PI*2, true);
}
context.fill();
update();
}
function update() {
for(var i = 0; i < total; i++) {
var s = gumballs[i];
s.y += 8;
if(s.x > w + 10 || s.x < - 10 || s.y > h) {
gumballs[i] = {x: Math.random()*w, y: 0, r: s.r, d: s.d};
}
}
}
setInterval(draw, 30);
}
You need to do .fill for each gumball rather than one .fill at the end:
function draw() {
context.clearRect(0,0,w,h);
for(var i = 0; i < total; i++) {
var s = gumballs[i];
if((i%3) == 0){
context.fillStyle = 'blue';
} else if ((i%4) == 0) {
context.fillStyle = 'red';
} else {
context.fillStyle = "orange";
}
context.beginPath();
context.moveTo(s.x, s.y);
context.arc(s.x, s.y, s.r, 0, Math.PI*2, true);
context.fill();
}
update();
}
It looks like gumballs[i] will always be an object - {x, y, r, d} - and so s % 3 and s % 4 will be NaN, causing the code to fall to the else clause.
You state you want to set color based on array index so your if should be checking index, not the array element at that index
Try changing:
if(s % 3 === 0){
To:
if(i % 3 === 0){
Same for other if

Categories

Resources