Asteroids Canvas Game: Splitting the asteroid - html

I'm still making Asteroids game in canvas in html5. Everything were going good, but now I'm in deadlock. Collision works, but I have no idea how to split an asteroid after shooting in it.
Here is code:
window.addEventListener('keydown',doKeyDown,true);
window.addEventListener('keyup',doKeyUp,true);
var canvas = document.querySelector('#pageCanvas');
var context = canvas.getContext('2d');
var angle = 0;
var H = /*500;*/window.innerHeight; //*0.75,
var W = /*500;*/window.innerWidth; //*0.75;
canvas.width = W;
canvas.height = H;
var xc = W/2; //zeby bylo w centrum :v
var yc = H/2; //jw.
var x = xc;
var y = yc;
var dv = 0.2;
var dt = 1;
var vx = 0;
var vy = 0;
var fps = 30;
var maxVel = 5;
var maxVelLeft = -5;
var frict = 0.99;
var brakes = 0.90;
var keys = new Array();
var fire = false;
var points = 0;
var lives = 3;
var randomize = true;
//zamiennik do setintervala
var requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
var fps = 30;
var now;
var then = Date.now();
var interval = 1000/fps;
var delat;
//laser
var laserF = false;
var lasery = [];
var shootVel = 12; //velocity of laser
//asteroids
var asteroidy = [];
var newasteroid1 ={
ax : ((Math.round(Math.random()*1000))%500),
ay : ((Math.round(Math.random()*1000))%500),
avx : 1*(Math.random() > 0.5 ? -1 : 1),
avy : 1*(Math.random() > 0.5 ? -1 : 1),
ar : 30,
aangle : 3,
colour : "gray"
};
asteroidy.push(newasteroid1);
var newasteroid2 ={
ax : ((Math.round(Math.random()*1000))%500),
ay : ((Math.round(Math.random()*1000))%500),
avx : 1*(Math.random() > 0.5 ? -1 : 1),
avy : 1*(Math.random() > 0.5 ? -1 : 1),
ar : 30,
aangle : 2,
colour : "gray"
};
asteroidy.push(newasteroid2);
var newasteroid3 ={
ax : ((Math.round(Math.random()*1000))%500),
ay : ((Math.round(Math.random()*1000))%500),
avx : 1*(Math.random() > 0.5 ? -1 : 1),
avy : 1*(Math.random() > 0.5 ? -1 : 1),
ar : 30,
aangle : 2,
colour : "gray"
};
asteroidy.push(newasteroid3);
var newasteroid4 ={
ax : ((Math.round(Math.random()*1000))%500),
ay : ((Math.round(Math.random()*1000))%500),
avx : 1*(Math.random() > 0.5 ? -1 : 1),
avy : 1*(Math.random() > 0.5 ? -1 : 1),
ar : 30,
aangle : 0,
colour : "fuchsia"
};
asteroidy.push(newasteroid4);
function doKeyUp(evt){
keys[evt.keyCode] = false;
fire = false;
if (laserF) {
var newlaser ={
lx: x,
ly: y,
//lw : 4,
//lh : 4,
lr : 2,
lvx : Math.cos(convertToRadians(angle)),
lvy : Math.sin(convertToRadians(angle))
}
lasery.push(newlaser);
laserF = false;
}
}
function doKeyDown(evt){
keys[evt.keyCode] = true;
if(40 in keys && keys[40]){
if(randomize){
x = (Math.round(Math.random()*1000))%W;
y = (Math.round(Math.random()*1000))%H;
vx = 0;
vy = 0;
randomize = false;
setTimeout(function(){randomize = true;}, 2000);
}
}
}
function drawPoints(){
context.save();
context.setTransform(1,0,0,1,0,0);
context.beginPath();
context.fillText("Score: " + points, 50, 50);
context.fillStyle = "#FFFFFF";
context.fill();
context.closePath();
context.restore();
}
function drawLives(){
context.save();
context.setTransform(1,0,0,1,0,0);
context.beginPath();
context.fillText(lives + " lives left", 150, 50);
context.fillStyle = "#FFFFFF";
context.fill();
context.closePath();
context.restore();
}
function drawAsteroids(idx){
var asteroid = asteroidy[idx];
context.save();
context.setTransform(1,0,0,1,0,0);
context.rotate(0);
context.translate(asteroid.ax, asteroid.ay);
context.rotate(asteroid.aangle);
context.translate(-25,-25);
context.beginPath();
context.fillText(asteroid.ax + " " + asteroid.ay, 0,50);
context.arc(0, 0, asteroid.ar, 0, 2 * Math.PI, false);
context.fillStyle = asteroid.colour;
context.fill();
context.closePath();
/*beginPath();
moveTo(0,0);
lineTo()*/
context.restore();
}
function moveAsteroids(idx){
var asteroid = asteroidy[idx]
asteroid.ax += asteroid.avx;
asteroid.ay += asteroid.avy;
asteroid.aangle += 0.009;
if(asteroid.ax > W){
asteroid.ax = 0 -25;
}
else{
if(asteroid.ax < -25){
asteroid.ax = W;
}
}
if(asteroid.ay > H){
asteroid.ay = 0 -25;
}
else{
if(asteroid.ay < -25){
asteroid.ay = H;
}
}
}
function drawLaser(idx) {
var laser = lasery[idx];
context.save();
context.translate(laser.lx,laser.ly);
context.fillStyle = "red";
//context.fillText(laser.lx + " " + laser.ly,10,10);
//context.fillRect(0,0,laser.lw,laser.lh);
context.beginPath();
context.arc(0, 0, laser.lr, 0, 2 * Math.PI, false);
context.fillStyle = "red";
context.fill();
context.closePath();
context.restore();
}
function moveLaser(idx) {
var laser = lasery[idx];
laser.lx += laser.lvx * shootVel;
laser.ly += laser.lvy * shootVel;
if (laser.lx > W || laser.lx < 0 || laser.ly > H || laser.ly < 0) {
lasery.splice(idx, 1);
}
}
//OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
function ogienZdupy(){
context.fillStyle = "red";
context.beginPath();
context.moveTo(-2,2);
context.lineTo(2,10);
context.lineTo(-2,18);
context.lineTo(-25,10);
context.lineTo(-2,2);
context.strokeStyle = "red";
context.stroke();
}
function convertToRadians(degree) {
return degree*(Math.PI/180);
}
function incrementAngle() {
angle += 5;
if(angle > 360){
angle = 0;
}
}
function decrementAngle(){
angle -= 5;
if(angle > 360){
angle = 0;
}
}
function xyVelocity(){
vx += dv * Math.cos(convertToRadians(angle)); //* friction;
vy += dv * Math.sin(convertToRadians(angle)); //* friction;
if(vx > maxVel){
vx = maxVel;
}
if(vy < maxVelLeft){
vy = maxVelLeft;
}
if(vx < maxVelLeft){
vx = maxVelLeft;
}
if(vy > maxVel){
vy = maxVel;
}
}
function shipMovement(){
if(66 in keys && keys[66]){ //it's B
vx = 0;
vy = 0;
}
if(38 in keys && keys[38]){
xyVelocity();
fire = true;
}
if(37 in keys && keys[37]){
decrementAngle();
};
if (39 in keys && keys[39]){
incrementAngle();
};
if (32 in keys && keys[32]){
laserF = true;
};
}
function xyAndFriction(){
x += vx * dt;
y += vy * dt;
vx *= frict;
vy *= frict;
}
function outOfBorders(){
if(x > W){
x = x - W;
}
if(x< 0){
x = W;
}
if(y > H){
y = y - H;
}
if(y < 0){
y = H;
}
}
function blazeatron420(){ //the ship
context.beginPath();
context.moveTo(0,0);
context.lineTo(20,10);
context.lineTo(0,20);
context.lineTo(7,10);
context.lineTo(0,0);
context.strokeStyle = "green";
context.stroke();
}
function space(){
context.fillStyle = "black";
context.fillRect(0,0,W,H);
}
/*
function superLaserCollider(){
for(var i in asteroidy){
var ax = asteroidy[i].ax,
ay = asteroidy[i].ay,
ar = asteroidy[i].ar
for(var j in lasery){
var xl = lasery[j].lx,
yl = lasery[j].ly,
rl = lasery[j].lr
}
}
/*var dx = Math.abs(ax - (xl+wl/2));
var dy = Math.abs(ay - (yl+yl/2));
if(dx > ar + wl){
return (false);
}
if(dy > ar + hl){
return (false);
}
if(dx <= wl){
return (true);
}
if(dy <= hl){
return (true);
}
var dx = dx - wl;
var dy = dy - hl;
return(dx * dx + dy * dy <= ar * ar);
var dx = ax - xl;
var dy = ay - yl;
var distance = Math.sqrt(dx * dx + dy * dy);
if(xl > ax && yl > ax){
console.log("kolizja");
}
}
*/
function bigAsteroidExplosion(idx){
var asteroid = asteroidy[idx];
context.clearRect(asteroid.ax, asteroid.ay, 100, 100);
}
function superLaserCollider(){
for(var i in asteroidy){
var ax = asteroidy[i].ax,
ay = asteroidy[i].ay,
ar = asteroidy[i].ar;
for(var j in lasery){
var xl = lasery[j].lx,
yl = lasery[j].ly,
rl = lasery[j].lr;
var dx = ax - xl;
var dy = ay - yl;
var distance = Math.sqrt(dx * dx + dy * dy);
if(distance < ar + rl){
console.log("kabom");
points = points + 100;
//alert("BOOM");
console.log(points);
}
}
}
}
/*
context.beginPath();
context.fillText(points, 100, 100);
context.fillStyle = "#FFFFFF";
context.fill();
context.closePath();
*/
function drawEverything() {
shipMovement();
xyAndFriction();
outOfBorders();
//context.save();
//;
space();
context.save();
context.translate(x,y);
//context.translate(25,25);
context.rotate(convertToRadians(angle));
context.translate(-7,-10);
if(fire){
ogienZdupy();
}
context.fillStyle = "green";
//context.fillText(vx + " km/h",50,50);
/*context.fillText("dupa",-30,0);
context.beginPath();
context.moveTo(-20,5);
context.lineTo(-5,10);
context.strokeStyle = "green"; //KOLOR LINII ;_;
context.stroke();*/
if(asteroidy.length > 0 ){
for (var tmp in asteroidy){
drawAsteroids(tmp);
moveAsteroids(tmp);
}
}
//putAsteroids();
blazeatron420();
//shootAsteroid(idx);
context.translate(-x+7,-y+10);
drawPoints();
drawLives();
context.restore();
console.log(asteroidy.length);
//superCollider();
//for(var i = 0; i < asteroidy.length; i++)
if(lasery.length > 0){
for (var tmp in lasery) {
drawLaser(tmp);
moveLaser(tmp);
}
}
superLaserCollider();
}
//setInterval(drawEverything, 20);
function draw(){
requestAnimationFrame(draw);
now = Date.now();
delta = now - then;
if (delta > interval){
then = now - (delta % interval);
}
drawEverything();
}
draw();
body{
margin:0;
padding:0;
overflow:hidden;
}
<body>
<canvas id="pageCanvas" style="display:block">
You do not have a canvas enabled browser. Please, stop using IE :P
</canvas>
</body>

Related

HTML how to replace single colour object with picture? [duplicate]

This question already has answers here:
Change a shape on JavaScript canvas to become an image
(1 answer)
moving an image across a html canvas
(5 answers)
Closed 3 months ago.
I'm currently working on a simple HTML game and want to replace the yellow square with a picture. The yellow square's colour is defined by line 20, with "yellow". How can I make this a picture instead of a singular colour?
The line in question:
myGamePiece = new component(30, 30, "yellow", 10, 120);
This is what the game looks like currently:
This is ideally what the game will look like, hopefully it's a pretty simple fix but I can't figure out how to solve it.
var myGamePiece;
var myObstacles = [];
var myScore;
function startGame() {
myGamePiece = new component(30, 30, "yellow", 10, 120);
myGamePiece.gravity = 0.05;
myScore = new component("30px", "Consolas", "black", 280, 40, "text");
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateGameArea, 20);
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function component(width, height, color, x, y, type) {
this.type = type;
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 == "text") {
ctx.font = this.width + " " + this.height;
ctx.fillStyle = color;
ctx.fillText(this.text, this.x, this.y);
} else {
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
this.newPos = function() {
this.gravitySpeed += this.gravity;
this.x += this.speedX;
this.y += this.speedY + this.gravitySpeed;
this.hitBottom();
}
this.hitBottom = function() {
var rockbottom = myGameArea.canvas.height - this.height;
if (this.y > rockbottom) {
this.y = rockbottom;
this.gravitySpeed = 0;
}
}
this.crashWith = function(otherobj) {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var otherleft = otherobj.x;
var otherright = otherobj.x + (otherobj.width);
var othertop = otherobj.y;
var otherbottom = otherobj.y + (otherobj.height);
var crash = true;
if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
crash = false;
}
return crash;
}
}
function updateGameArea() {
var x, height, gap, minHeight, maxHeight, minGap, maxGap;
for (i = 0; i < myObstacles.length; i += 1) {
if (myGamePiece.crashWith(myObstacles[i])) {
return;
}
}
myGameArea.clear();
myGameArea.frameNo += 1;
if (myGameArea.frameNo == 1 || everyinterval(150)) {
x = myGameArea.canvas.width;
minHeight = 20;
maxHeight = 200;
height = Math.floor(Math.random()*(maxHeight-minHeight+1)+minHeight);
minGap = 50;
maxGap = 200;
gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap);
myObstacles.push(new component(10, height, "green", x, 0));
myObstacles.push(new component(10, x - height - gap, "green", x, height + gap));
}
for (i = 0; i < myObstacles.length; i += 1) {
myObstacles[i].x += -1;
myObstacles[i].update();
}
myScore.text="SCORE: " + myGameArea.frameNo;
myScore.update();
myGamePiece.newPos();
myGamePiece.update();
}
function everyinterval(n) {
if ((myGameArea.frameNo / n) % 1 == 0) {return true;}
return false;
}
function accelerate(n) {
myGamePiece.gravity = n;
}
window.addEventListener("DOMContentLoaded",startGame);
canvas {
border:1px solid #d3d3d3;
background-color: #3A93DC;
}
<br>
<button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.05)">ACCELERATE</button>
<p>Use the ACCELERATE button to stay in the air</p>
<p>How long can you stay alive?</p>

simulate onmouseup event to canvas

i have a simple HTML5 with a canvas object, i just need to add replicate the same events on the button below the code-
As you can see pushing the button, the canvas calls accelerate() and onmouseUp event calls the function again with different argument, and the canvas stops going up and starts with the gravity
I would like to use in a touch screen, the only problem is the event OnmuseUp that i do not know how to manage
this is the code:
var myGamePiece;
var myObstacles = [];
var myScore;
function startGame() {
myGamePiece = new component(30, 30, "red", 10, 120);
myGamePiece.gravity = 0.05;
myScore = new component("30px", "Consolas", "black", 280, 40, "text");
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.canvas.addEventListener('click', function() {accelerate(-0.2);}, false);
updateGameArea();
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function component(width, height, color, x, y, type) {
this.type = type;
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 == "text") {
ctx.font = this.width + " " + this.height;
ctx.fillStyle = color;
ctx.fillText(this.text, this.x, this.y);
} else {
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
this.newPos = function() {
this.gravitySpeed += this.gravity;
this.x += this.speedX;
this.y += this.speedY + this.gravitySpeed;
this.hitBottom();
}
this.hitBottom = function() {
var rockbottom = myGameArea.canvas.height - this.height;
if (this.y > rockbottom) {
this.y = rockbottom;
this.gravitySpeed = 0;
}
}
this.crashWith = function(otherobj) {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var otherleft = otherobj.x;
var otherright = otherobj.x + (otherobj.width);
var othertop = otherobj.y;
var otherbottom = otherobj.y + (otherobj.height);
var crash = true;
if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
crash = false;
}
return crash;
}
}
function updateGameArea() {
var x, height, gap, minHeight, maxHeight, minGap, maxGap;
for (i = 0; i < myObstacles.length; i += 1) {
if (myGamePiece.crashWith(myObstacles[i])) {
return;
}
}
myGameArea.clear();
myGameArea.frameNo += 1;
if (myGameArea.frameNo == 1 || everyinterval(150)) {
x = myGameArea.canvas.width;
minHeight = 20;
maxHeight = 200;
height = Math.floor(Math.random()*(maxHeight-minHeight+1)+minHeight);
minGap = 50;
maxGap = 200;
gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap);
myObstacles.push(new component(10, height, "green", x, 0));
myObstacles.push(new component(10, x - height - gap, "green", x, height + gap));
}
for (i = 0; i < myObstacles.length; i += 1) {
myObstacles[i].x += -1;
myObstacles[i].update();
}
myScore.text="SCORE: " + myGameArea.frameNo;
myScore.update();
myGamePiece.newPos();
myGamePiece.update();
}
function everyinterval(n) {
if ((myGameArea.frameNo / n) % 1 == 0) {return true;}
return false;
}
function accelerate(n) {
if (!myGameArea.interval) {myGameArea.interval = setInterval(updateGameArea, 20);}
myGamePiece.gravity = n;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<br>
<button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.05)">ACCELERATE</button>
<p>Click the ACCELERATE button to start the game</p>
<p>How long can you stay alive? Use the ACCELERATE button to stay in the air..</p>
</body>
</html>
Rather than use the event listener to drive the game, use the event listener just to track the input state.
Eg
canvas.addEventListener("mousedown",inputEvent);
canvas.addEventListener("touchstart",inputEvent);
const input = {
active : false;
}
function inputEvent(){
input.active = true;
}
Then rather than use setInterval (which you should never use for animation) create a main loop function
function mainLoop(){
// see answer below
requestAnimationFrame(mainLoop); // get the next frame
}
requestAnimationFrame(mainLoop); // starts the first frame
This will start being called every 1/60th second. In this you monitor the input and do what is needed depending on the game state.
const thrust = -0.4;
const gravity = 0.1;
var inplay = false; // when true game is playing.
function mainLoop(){
if(input.active && !inplay){
inplay = true;
input.active = false; // clear the input
}
if(inplay){
if(input.active){ // input
myGamePiece.speedY += thrust;
input.active = false; // clear input
}
updateGameArea(); // call the render game function.
}
requestAnimationFrame(mainLoop); // get the next frame
}
requestAnimationFrame(mainLoop); // starts the first frame
You will need to change the move function
You had
this.newPos = function() {
this.gravitySpeed += this.gravity;
this.x += this.speedX;
this.y += this.speedY + this.gravitySpeed;
this.hitBottom();
}
Change to
this.newPos = function() {
this.speedY += gravity;
this.x += this.speedX;
this.y += this.speedY;
this.hitBottom();
}
Or you can change the input to have a thrust over some frames
const input = {
active : 0;
}
const thrustFrameCount = 4;
function inputEvent(){
input.active = thrustFrameCount;
}
and change the main loop to
const thrust = -0.1;
const gravity = 0.1;
var inplay = false; // when true game is playing.
function mainLoop(){
if(input.active > 0 && !inplay){
inplay = true;
input.active = 0; // clear the input
}
if(inplay){
if(input.active > 0){ // input
myGamePiece.speedY += thrust * input.active;
input.active -= 1; // count down input on.
}
updateGameArea(); // call the render game function.
}
requestAnimationFrame(mainLoop); // get the next frame
}
requestAnimationFrame(mainLoop); // starts the first frame
Well everything is sort of like that, your game code is a little bit overly complex so I have hacked a quick mod to give you an example of what I meant in the above answer.
var myGamePiece;
var myObstacles = [];
var myScore;
function startGame() {
myGamePiece = new component(30, 30, "red", 10, 120);
myScore = new component("30px", "Consolas", "black", 280, 40, "text");
myGameArea.start();
}
var myGameArea = {
canvas : canvas,
start : function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
this.frameNo = 0;
updateGameArea();
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function component(width, height, color, x, y, type) {
this.type = type;
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 == "text") {
ctx.font = this.width + " " + this.height;
ctx.fillStyle = color;
ctx.fillText(this.text, this.x, this.y);
} else {
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
this.newPos = function() {
this.speedY += gravity;
this.x += this.speedX;
this.y += this.speedY;
this.hitBottom();
}
this.hitBottom = function() {
var rockbottom = myGameArea.canvas.height - this.height;
if (this.y > rockbottom) {
this.y = rockbottom;
if(this.speedY > 0){
this.speedY = 0;
}
}
}
this.crashWith = function(otherobj) {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var otherleft = otherobj.x;
var otherright = otherobj.x + (otherobj.width);
var othertop = otherobj.y;
var otherbottom = otherobj.y + (otherobj.height);
var crash = true;
if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
crash = false;
}
return crash;
}
}
function updateGameArea() {
var x, height, gap, minHeight, maxHeight, minGap, maxGap;
for (i = 0; i < myObstacles.length; i += 1) {
if (myGamePiece.crashWith(myObstacles[i])) {
return;
}
}
myGameArea.clear();
if (myGameArea.frameNo % wallFrameCount === 0 ) {
x = myGameArea.canvas.width;
minHeight = 20;
maxHeight = 200;
height = Math.floor(Math.random()*(maxHeight-minHeight+1)+minHeight);
minGap = 50;
maxGap = 200;
gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap);
myObstacles.push(new component(10, height, "green", x, 0));
myObstacles.push(new component(10, x - height - gap, "green", x, height + gap));
}
for (i = 0; i < myObstacles.length; i += 1) {
myObstacles[i].x += -1;
myObstacles[i].update();
}
myScore.text="SCORE: " + myGameArea.frameNo;
myScore.update();
myGamePiece.newPos();
myGamePiece.update();
myGameArea.frameNo += 1;
}
canvas.addEventListener("mousedown",inputEvent);
canvas.addEventListener("touchstart",inputEvent);
const input = {active : 0 };
const thrustFrameCount = 4;
function inputEvent(){
input.active = thrustFrameCount;
}
const wallFrameCount = 200;
const thrust = -0.4;
const gravity = 0.2;
var inplay = false; // when true game is playing.
function mainLoop(){
if(input.active > 0 && !inplay){
startGame();
inplay = true;
input.active = 0; // clear the input
}
if(inplay){
if(input.active > 0){ // input
myGamePiece.speedY += thrust * input.active;
input.active -= 1; // count down input on.
}
updateGameArea(); // call the render game function.
}
requestAnimationFrame(mainLoop); // get the next frame
}
requestAnimationFrame(mainLoop); // starts the first frame
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}
<canvas id="canvas" width="480" height="270"></canvas><br>
Click touch canvas to start.

Stopping/removing everything then changing scene

I am making a shooting game and when i die it will not remove the child's it just freezes them on the screen. I would like to be able to stop all of the action then remove and change screens afterwards.
var gunLength:uint = 90;
var bullets:Array = new Array();
var bulletSpeed:uint = 20;
var baddies:Array = new Array();
var timer:Timer = new Timer(1000);
timer.addEventListener(TimerEvent.TIMER, addBaddie);
timer.start();
var lives:Number = 0;
stop();
stage.addEventListener(MouseEvent.MOUSE_MOVE, aimGun);
stage.addEventListener(MouseEvent.MOUSE_DOWN, fireGun);
stage.addEventListener(Event.ENTER_FRAME, moveObjects);
function addBaddie(evt:TimerEvent):void {
var baddie:Baddie = new Baddie();
var side:Number = Math.ceil(Math.random() * 4);
if (side == 1) {
baddie.x = Math.random() * stage.stageWidth;
baddie.y = - baddie.height;
} else if (side == 2) {
baddie.x = stage.stageWidth + baddie.width;
baddie.y = Math.random() * stage.stageHeight;
} else if (side == 3) {
baddie.x = Math.random() * stage.stageWidth;
baddie.y = stage.stageHeight + baddie.height;
} else if (side == 4) {
baddie.x = - baddie.width
baddie.y = Math.random() * stage.stageHeight;
}
baddie.angle = getAngle(baddie.x, baddie.y, gun.x, gun.y);
baddie.speed = Math.ceil(Math.random() * 15);
addChild(baddie);
baddies.push(baddie);
}
function fireGun(evt:MouseEvent) {
var bullet:Bullet = new Bullet();
bullet.rotation = gun.rotation;
bullet.x = gun.x + Math.cos(deg2rad(gun.rotation)) * gunLength;
bullet.y = gun.y + Math.sin(deg2rad(gun.rotation)) * gunLength;
addChild(bullet);
bullets.push(bullet);
}
function moveObjects(evt:Event):void {
moveBullets();
moveBaddies();
}
function moveBullets():void {
for (var i:int = 0; i < bullets.length; i++) {
var dx = Math.cos(deg2rad(bullets[i].rotation)) * bulletSpeed;
var dy = Math.sin(deg2rad(bullets[i].rotation)) * bulletSpeed;
bullets[i].x += dx;
bullets[i].y += dy;
}
}
function moveBaddies():void {
for (var i:int = 0; i < baddies.length; i++) {
var dx = Math.cos(deg2rad(baddies[i].angle)) * baddies[i].speed;
var dy = Math.sin(deg2rad(baddies[i].angle)) * baddies[i].speed;
baddies[i].x += dx;
baddies[i].y += dy;
if (baddies[i].hitTestPoint(gun.x, gun.y, true)) {
removeChild(baddies[i]);
baddies.splice(i, 1);
loseLife();
lives -= 1;
if(lives < 1){
gotoAndStop(1,"Dead");
for each(var gun:Gun in gun){
removeChild(gun)
}
lives--;
trace("Lives = " + lives);
}
} else {
checkForHit(baddies[i]);
}
}
}
function checkForHit(baddie:Baddie):void {
for (var i:int = 0; i < bullets.length; i++) {
if (baddie.hitTestPoint(bullets[i].x, bullets[i].y, true)) {
removeChild(baddie);
baddies.splice(baddies.indexOf(baddie), 1);
}
}
}
function loseLife():void {
}
function aimGun(evt:Event):void {
gun.rotation = getAngle(gun.x, gun.y, mouseX, mouseY);
var distance:Number = getDistance(gun.x, gun.y, mouseX, mouseY);
var adjDistance:Number = distance / 12 - 7;
}
function getAngle(x1:Number, y1:Number, x2:Number, y2:Number):Number {
var radians:Number = Math.atan2(y2 - y1, x2 - x1);
return rad2deg(radians);
}
function getDistance(x1:Number, y1:Number, x2:Number, y2:Number):Number {
var dx:Number = x2 - x1;
var dy:Number = y2 - y1;
return Math.sqrt(dx * dx + dy * dy);
}
function rad2deg(rad:Number):Number {
return rad * (180 / Math.PI);
}
function deg2rad(deg:Number):Number {
return deg * (Math.PI/180);
}
var target:MovieClip;
initialiseCursor();
function initialiseCursor():void {
Mouse.hide();
target = new Target();
target.x = mouseX;
target.y = mouseY;
target.mouseEnabled = false;
addChild(target);
stage.addEventListener(MouseEvent.MOUSE_MOVE, targetMove);
stage.addEventListener(MouseEvent.MOUSE_DOWN, targetDown);
stage.addEventListener(MouseEvent.MOUSE_UP, targetUp);
}
function targetMove(evt:MouseEvent):void {
target.x = this.mouseX;
target.y = this.mouseY;
}
function targetDown(evt:MouseEvent):void {
target.gotoAndStop(2);
}
function targetUp(evt:MouseEvent):void {
target.gotoAndStop(1);
}

Ball movement path in canvas, and other ideas you may have?

I've created this animation for my project that had to use any form of physics.
I am a total beginner, too :) Anyway, this is my project now :
Bouncing Balls
You can setup gravity and force, then click play, and just drag and drop to shoot the balls. You can change the values and hit update too see an effect.
My question is, how can I create an effect that when I press ratio button (for example) I can see the path that ball makes? Is it complicated? As I was saying I am a beginner, so no complex code for me :)
Also, doyou have any ideas to make the project better? Any additional "physics" effects? Or maybe you know a website that shows tutorials for simile (please) effects made in HTML5/js so I can add additional effects to my project.
One possibility (as you're clearing the canvas each frame) would be to draw ball paths onto a secondary canvas, which would not be cleared each frame. Then, when you come to clear the first frame, render the second frame after clearing, and before rendering the balls.
The second canvas would of course have to be the same dimensions as the first, so that all of the ball points line up correctly. The second canvas should also have a z-index lower than the first, so that it is only shown when you specifically render it to the first canvas (i.e. when the radio button is checked).
To decrease any lag while the radio is not checked, you could skip drawing the ball paths to the second canvas, although I don't think you would see any great increase in performance.
On each frame update, you would mark the position of each ball with a pixel, or line (from the previous position to the current) on the second canvas.
Looking at your code, you seem pretty competent, so I've skipped writing an example as I think this would be good experience for you :)
Modified 'script.js' source demonstrating solution
window.onload = function(){
$("#canvas").hide();
var howManyPaths = 0;
var showPath=false;
// SLIDERS
var gravitySlider = document.getElementById('gravitySlider');
var gravityVal = document.getElementById('gravityValue');
gravitySlider.onchange = function(){
gravityVal.value = gravitySlider.value;
}
gravityVal.onkeyup = function(){
gravitySlider.value = gravityVal.value;
}
var forceSlider = document.getElementById('forceSlider');
var forceValue = document.getElementById('forceValue');
forceSlider.onchange = function(){
forceValue.value = forceSlider.value;
}
forceValue.onkeyup = function(){
forceSlider.value = forceValue.value;
}
// GLOBAL VARIABLES
var test = false;
var gravityCount = $("#gravity").val();
var forceCount = $("#rectangles").val();
// CSS :
var playCSS = document.getElementById("play");
var restartCSS = document.getElementById("restart");
var clickableCSS = document.getElementById("setup");
var clickableBG = document.getElementById("img");
//restartCSS.style.visibility="hidden";
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var canvas2 = document.getElementById("canvas2");
var ctx2 = canvas2.getContext("2d");
//var ctx;
var gravity = 9.86;
var forceFactor = 0.5;
var mouseDown = false;
var balls = new Array();
var mousePos = new Array();
// EVENT HANDLER
function onMouseDown(evt){
mouseDown = true;
mousePos['downX'] = evt.pageX;
mousePos['downY'] = evt.pageY;
}
function onMouseUp(evt){
mouseDown = false;
setup.style.visibility="visible";
if(test == true && !( mousePos['downX'] < 200 && mousePos['downY'] < 150) ){
restartCSS.style.visibility="visible";
forceFactor = forceCount;
balls.push(new ball(mousePos["downX"],
mousePos["downY"],
(evt.pageX - mousePos["downX"]) * forceFactor,
(evt.pageY - mousePos["downY"]) * forceFactor,
10 + (Math.random() * 10),
0.8,
randomColor()
));
}
ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
}
function onMouseMove(evt){
mousePos['currentX'] = evt.pageX;
mousePos['currentY'] = evt.pageY;
}
function resizeWindow(evt){
//canvas.height = 960;
//canvas.width = 720;
canvas.height = $(window).height()-6;
canvas.width = $(window).width();
canvas2.height = $(window).height()-6;
canvas2.width = $(window).width();
}
$(document).mousedown(onMouseDown);
$(document).mouseup(onMouseUp);
$(document).mousemove(onMouseMove);
$(window).bind("resize", resizeWindow);
// GRAPHICS CODE
function circle(x, y, r, col){
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, true);
ctx.closePath;
// fill
ctx.fillStyle = col;
ctx.fill();
// stroke
ctx.lineWidth = r * 0.1;
ctx.strokeStyle = "#000000";
ctx.stroke();
}
function circlePath(x, y)
{
ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
ctx2.fillStyle = '#3f4043';
ctx2.fillRect(x, y, 5, 5);
ctx2.strokeStyle = "black";
ctx2.strokeRect(x, y, 5, 5);
}
function randomColor(){
var letter = "0123456789ABCDEF".split("");
var color = "#";
for(var i=0; i<6; i++){
color += letter[Math.round(Math.random()*15)];
}
return color;
}
function arrow(fromX, fromY, toX, toY, color){
// path
ctx.beginPath();
var headLen = 10;
var angle = Math.atan2(toY - fromY, toX - fromX);
ctx.moveTo(fromX, fromY);
ctx.lineTo(toX, toY);
ctx.lineTo(toX - headLen * Math.cos(angle - Math.PI/6), toY - headLen * Math.sin(angle - Math.PI/6));
ctx.moveTo(toX, toY);
ctx.lineTo(toX - headLen * Math.cos(angle + Math.PI/6), toY - headLen * Math.sin(angle + Math.PI/6));
// style
ctx.lineWith = 1;
ctx.strokeStyle = color;
ctx.lineCap = "butt";
ctx.stroke();
}
function drawBall(){
// Gravity
gravity = gravityCount;
this.speedY += gravity * 0.5; // v = a * t
this.x += this.speedX * 0.05; // s = v * t
this.y += this.speedY * 0.05;
// prawa ściana
if(this.x + this.r > canvas.width){
this.x = canvas.width - this.r;
this.speedX *= -1 * this.bounce;
}
// lewa ściana
if(this.x - this.r < 0){
this.x = this.r;
this.speedX *= -1 * this.bounce;
}
// dolna ściana
if(this.y + this.r > canvas.height){
this.y = canvas.height - this.r;
this.speedY *= -1 * this.bounce;
}
// górna ściana
if(this.y - this.r < 0){
this.y = this.r;
this.speedY *= -1 * this.bounce;
}
// zwalnianie na ziemi
if (this.speedX > 0.25){
this.speedX -= 0.25;
if (this.speedY > 0.25)
this.speedY -= 0.25;
}
if (this.speedX < -0.25){
this.speedX += 0.25;
//if (this.speedY < -0.25)
// this.speedY += 0.25;
}
circle(this.x, this.y, this.r, this.col);;
}
// OBJECTS
function ball(positionX, positionY, sX, sY, radius, b, color){
this.x = positionX;
this.y = positionY;
this.speedX = sX;
this.speedY = sY;
this.r = radius;
this.bounce = b;
this.col = color;
this.draw = drawBall;
}
//GAME LOOP
function gameLoop(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
//grab the context from your destination canvas
//if path drawing is enabled, first draw the path canvas to the display canvas
if (showPath) ctx.drawImage(canvas2,0,0);
if(mouseDown == true){
// ctx.clearRect(0, 0, canvas.width, canvas.height); /* !important !!!!!!!!!!!!!!! */
arrow(mousePos['downX'], mousePos['downY'], mousePos['currentX'], mousePos['currentY'], "red");
}
for(var i=0; i<balls.length; i++){
balls[i].draw();
if (i==balls.length-1) {
//draw path
ctx2.fillStyle = '#3f4043';
ctx2.fillRect(balls[i].x, balls[i].y, 5, 5);
ctx2.strokeStyle = "black";
ctx2.strokeRect(balls[i].x, balls[i].y, 5, 5);
}
}
ctx.fillStyle = "#000000";
ctx.font = "15px Arial";
ctx.fillText("Balls: " + balls.length + " " + gravityCount + " " + forceCount + " " + howManyPaths, 10, canvas.height -10);
}
// START THE GAME
function init(){
//$("#setup").hide();
$("#canvas").show();
$("#canvas2").hide();
ctx = $('canvas')[0].getContext("2d");
canvas.height = $(window).height()-6;
canvas.width = $(window).width();
//canvas.width = 960;
//canvas.height = 720;
canvas2.height = $(window).height()-6;
canvas2.width = $(window).width();
return setInterval(gameLoop, 10);
}
$("#play").click(function() {
test = true;
playCSS.style.visibility="hidden";
gravityCount = $("#gravitySlider").val();
forceCount = $("#forceSlider").val();
init();
});
$("#restart").click(function() {
window.location.href="index.html";
});
$("#refresh").click(function() {
gravityCount = $("#gravitySlider").val();
forceCount = $("#forceSlider").val();
});
$("#showPath").click(function() {
showPath=true;
});
$("#hidePath").click(function() {
showPath=false;
});
}

canvas.onmousedown function to add a shape won't work

I have some code, which can be seen below. At the bottom is a block of code to add a shape. For some reason it won't work unless the very first lines of code are different. Up until I added the 'addShape' code, it was all working fine, so I wandered if anyone on here could have a look and perhaps figure out a solution?
Cheers
Jon
EDIT Also available on jsFiddle http://jsfiddle.net/pukster/mfNq4/1/
$(document).ready(function() {
var canvas = $('#myCanvas');
var ctx = canvas.get(0).getContext("2d");
var context = new webkitAudioContext();
var canvasWidth = canvas.width();
var canvasHeight = canvas.height();
$(window).resize(resizeCanvas);
function resizeCanvas() {
canvas.attr("width", $(window).get(0).innerWidth - 2);
canvas.attr("height", $(window).get(0).innerHeight - 2);
canvasWidth = canvas.width();
canvasHeight = canvas.height();
};
resizeCanvas();
ctx.strokeStyle = "rgb(255, 0, 0)";
ctx.lineWidth = 2;
var playAnimation = true;
var Ring = function(x, y, radius, vx, vy) {
this.x = x;
this.y = y;
this.radius = radius;
this.vx = vx;
this.vy = vy;
};
var rings = [];
for (var i = 0; i < 10; i++) {
var x = Math.random()*ctx.canvas.width;
var y = Math.random()*ctx.canvas.height;
var vx = Math.random()*6-3;
var vy = Math.random()*6-3;
rings.push(new Ring(x, y, 40, vx, vy));
};
function animate() {
var ringsLength = rings.length;
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
for (var i = 0; i < ringsLength; i++) {
var tmpRing = rings[i];
for (var j = i+1; j < ringsLength; j++) {
var tmpRingB = rings[j];
var dx = tmpRingB.x - tmpRing.x;
var dy = tmpRingB.y - tmpRing.y;
var dist = Math.sqrt((dx * dx) + (dy * dy));
if(dist < tmpRing.radius + tmpRingB.radius) {
var sinewave = new SineWave(context);
var angle = Math.atan2(dy, dx);
var sine = Math.sin(angle);
var cosine = Math.cos(angle);
var x = 0;
var y = 0;
var xb = dx * cosine + dy * sine;
var yb = dy * cosine - dx * sine;
var vx = tmpRing.vx * cosine + tmpRing.vy * sine;
var vy = tmpRing.vy * cosine - tmpRing.vx * sine;
var vxb = tmpRingB.vx * cosine + tmpRingB.vy * sine;
var vyb = tmpRingB.vy * cosine - tmpRingB.vx * sine;
vx *= -1;
vxb *= -1;
xb = x + (tmpRing.radius + tmpRingB.radius);
tmpRing.x = tmpRing.x + (x * cosine - y * sine);
tmpRing.y = tmpRing.y + (y * cosine + x * sine);
tmpRingB.x = tmpRing.x + (xb * cosine - yb * sine);
tmpRingB.y = tmpRing.y + (yb * cosine + xb * sine);
tmpRing.vx = vx * cosine - vy * sine;
tmpRing.vy = vy * cosine + vx * sine;
tmpRingB.vx = vxb * cosine - vyb * sine;
tmpRingB.vy = vyb * cosine + vxb * sine;
tmpRing.loop = true;
};
};
tmpRing.x += tmpRing.vx;
tmpRing.y += tmpRing.vy;
if (tmpRing.x - tmpRing.radius < 0) {
var sinwave = new SinWave(context);
tmpRing.x = tmpRing.radius;
tmpRing.vx *= -1;
} else if (tmpRing.x + tmpRing.radius > ctx.canvas.width) {
var sinwave = new SinWave(context);
tmpRing.x = ctx.canvas.width - tmpRing.radius;
tmpRing.vx *= -1;
};
if (tmpRing.y - tmpRing.radius < 0) {
var sinwave = new SinWave(context);
tmpRing.y = tmpRing.radius;
tmpRing.vy *= -1;
} else if (tmpRing.y + tmpRing.radius > ctx.canvas.height) {
var sinwave = new SinWave(context);
tmpRing.y = ctx.canvas.height - tmpRing.radius;
tmpRing.vy *= -1;
};
ctx.beginPath();
ctx.arc(tmpRing.x, tmpRing.y, 40, 0, Math.PI*2, false);
ctx.closePath();
ctx.stroke();
//-------------------- The addRing Function Code --------------------//
var mx, my;
var offsetX, offsetY;
//canvas.onmousedown = sglClick;
function addRing(x, y, radius, vx, vy) {
var x = mx-5;
var y = my-5;
var vx = Math.random()*6-3;
var vy = Math.random()*6-3;
rings.push(new Ring(x, y, 40, vx, vy));
}
function sglClick(e) {
getMouse(e);
addRing();
}
function getMouse(e) {
var element = ctx, offsetX = 0, offsetY = 0;
if (element.offsetParent !== undefined) {
do {
offsetX += element.offsetLeft;
offsetY += element.offsetTop;
} while ((element = element.offsetParent));
}
mx = e.pageX - offsetX;
my = e.pageY - offsetY;
}
};
if(playAnimation) {
setTimeout(animate, 33);
};
};
animate();
});
I noticed a couple of problems.
First, you misspelled SineWave in a few places. Second, you are trying to bind an event to the canvas using canvas.onmousedown = sglClick;. You should try canvas.bind('mousedown', sglClick); instead and you shouldn't do the binding inside of your animate method. It will add a new event each iteration of the animation.