How to make the objects fall in javascript? - javascript

I am trying to make this game, you should not collide the falling object. I have the objects falling and I have my black square, but it flashes when I run it and Im not sure how to make the code stop when the two objects collide together.
here is the code that I have so far!
<html>
<body>
<canvas id="canvasRegn" width="600" height="450"style="margin:100px;"></canvas>
<script>
var ctx;
var imgBg;
var imgDrops;
var noOfDrops = 50;
var fallingDrops = [];
function drawBackground(){
ctx.drawImage(imgBg, 0, 0); //Background
}
function draw() {
drawBackground();
for (var i=0; i< noOfDrops; i++)
{
ctx.drawImage (fallingDrops[i].image, fallingDrops[i].x, fallingDrops[i].y); //The rain drop
fallingDrops[i].y += fallingDrops[i].speed; //Set the falling speed
if (fallingDrops[i].y > 480) { //Repeat the raindrop when it falls out of view
fallingDrops[i].y = -25 //Account for the image size
fallingDrops[i].x = Math.random() * 800; //Make it appear randomly along the width
}
}
}
function setup() {
var canvas = document.getElementById('canvasRegn');
if (canvas.getContext) {
ctx = canvas.getContext('2d');
imgBg = new Image();
imgBg.src = "http://www.hamdancommunications.com/HComm/img/wite%20square.png";
setInterval(draw, 36);
for (var i = 0; i < noOfDrops; i++) {
var fallingDr = new Object();
fallingDr["image"] = new Image();
fallingDr.image.src = 'http://s18.postimg.org/o6jpmdf9x/Line1.jpg';
fallingDr["x"] = Math.random() * 800;
fallingDr["y"] = Math.random() * 5;
fallingDr["speed"] = 3 + Math.random() * 5;
fallingDrops.push(fallingDr);
anotherGame();
}
}
}
setup();
function anotherGame(){
var canvas = document.getElementById("canvasRegn");
var ctx = canvas.getContext('2d');
canvas.addEventListener("mousedown", clicked);
canvas.addEventListener("mousemove", moved);
canvas.addEventListener("mouseup", released);
var isclicked = 0;
var square = new Object();
square.color = "black";
square.x = 100;
square.y = 100;
square.w = 50;
square.h = 50;
var offX = 0;
var offY = 0;
function draw(){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillStyle = square.color;
ctx.fillRect(square.x,square.y,square.w,square.h);
}
function game(){
}
function clicked(e){
var x = e.offsetX;
var y = e.offsetY;
if(x >= square.x && x <= square.x + square.w &&
y >= square.y && y <= square.y + square.h){
isclicked = 1;
offX = x - square.x;
offY = y - square.y;
}
}
function moved(e){
if(isclicked == 1){
var x = e.offsetX;
var y = e.offsetY;
square.x = x - offX;
square.y = y - offY;
}
}
function released(e){
var x = e.offsetX;
var y = e.offsetY;
isclicked = 0;
}
var drawtimer = setInterval(draw, 1000/30);
var gametimer = setInterval(game, 1000/10);
}
</script>
</body>
</html>

Related

How can I reverse the direction of this square after it reaches a certain value?

I'm trying to create an idle animation where the red rectangle moves back and forth slightly in a loop. For some reason once it reaches the specified threshhold instead of proceeding to move in the opposite direction, it just stops.
What did I do wrong?
<canvas id="myCanvas" width="1500" height="500" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// Spaceship structure
var shipWidth = 250;
var shipHeight = 100;
// Canvas parameters
var cWidth = canvas.width;
var cHeight = canvas.height;
// Positioning variables
var centerWidthPosition = (cWidth / 2) - (shipWidth / 2);
var centerHeightPosition = (cHeight / 2) - (shipHeight / 2);
var requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
function drawShip(){
ctx.clearRect(0, 0, cWidth, cHeight);
ctx.fillStyle = "#FF0000";
ctx.fillRect(centerWidthPosition,centerHeightPosition,shipWidth,shipHeight);
centerWidthPosition--;
if (centerWidthPosition < 400){
++centerWidthPosition;
}
requestAnimationFrame(drawShip);
}
drawShip();
</script>
#TheAmberlamps explained why it's doing that. Here I offer you a solution to achieve what I believe you are trying to do.
Use a velocity variable that changes magnitude. X position always increases by velocity value. Velocity changes directions at screen edges.
// use a velocity variable
var xspeed = 1;
// always increase by velocity
centerWidthPosition += xspeed;
// screen edges are 0 and 400 in this example
if (centerWidthPosition > 400 || centerWidthPosition < 0){
xspeed *= -1; // change velocity direction
}
I added another condition in your if that causes the object to bounce back and forth. Remove the selection after || if you don't want it doing that.
Your function is caught in a loop; once centerWidthPosition reaches 399 your conditional makes it increment back up to 400, and then it decrements back to 399.
here is another one as a brain teaser - how would go by making this animation bounce in the loop - basically turn text into particles and then reverse back to text and reverse back to particles and back to text and so on and on and on infinitely:
var random = Math.random;
window.onresize = function () {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
};
window.onresize();
var ctx = canvas.getContext('2d');
ctx.font = 'bold 50px "somefont"';
ctx.textBaseline = 'center';
ctx.fillStyle = 'rgba(255,255,255,1)';
var _particles = [];
var particlesLength = 0;
var currentText = "SOMETEXT";
var createParticle = function createParticle(x, y) {_particles.push(new Particle(x, y));};
var checkAlpha = function checkAlpha(pixels, i) {return pixels[i * 4 + 3] > 0;};
var createParticles = function createParticles() {
var textSize = ctx.measureText(currentText);
ctx.fillText(currentText,Math.round((canvas.width / 2) - (textSize.width / 2)),Math.round(canvas.height / 2));
var imageData = ctx.getImageData(1, 1, canvas.width, canvas.height);
var pixels = imageData.data;
var dataLength = imageData.width * imageData.height;
for (var i = 0; i < dataLength; i++) {
var currentRow = Math.floor(i / imageData.width);
var currentColumn = i - Math.floor(i / imageData.height);
if (currentRow % 2 || currentColumn % 2) continue;
if (checkAlpha(pixels, i)) {
var cy = ~~(i / imageData.width);
var cx = ~~(i - (cy * imageData.width));
createParticle(cx, cy);
}}
particlesLength = _particles.length;
};
var Point = function Point(x, y) {
this.set(x, y);
};
Point.prototype = {
set: function (x, y) {
x = x || 0;
y = y || x || 0;
this._sX = x;
this._sY = y;
this.reset();
},
add: function (point) {
this.x += point.x;
this.y += point.y;
},
multiply: function (point) {
this.x *= point.x;
this.y *= point.y;
},
reset: function () {
this.x = this._sX;
this.y = this._sY;
return this;
},
};
var FRICT = new Point(0.98);//set to 0 if no flying needed
var Particle = function Particle(x, y) {
this.startPos = new Point(x, y);
this.v = new Point();
this.a = new Point();
this.reset();
};
Particle.prototype = {
reset: function () {
this.x = this.startPos.x;
this.y = this.startPos.y;
this.life = Math.round(random() * 300);
this.isActive = true;
this.v.reset();
this.a.reset();
},
tick: function () {
if (!this.isActive) return;
this.physics();
this.checkLife();
this.draw();
return this.isActive;
},
checkLife: function () {
this.life -= 1;
this.isActive = !(this.life < 1);
},
draw: function () {
ctx.fillRect(this.x, this.y, 1, 1);
},
physics: function () {
if (performance.now()<nextTime) return;
this.a.x = (random() - 0.5) * 0.8;
this.a.y = (random() - 0.5) * 0.8;
this.v.add(this.a);
this.v.multiply(FRICT);
this.x += this.v.x;
this.y += this.v.y;
this.x = Math.round(this.x * 10) / 10;
this.y = Math.round(this.y * 10) / 10;
}
};
var nextTime = performance.now()+3000;
createParticles();
function clearCanvas() {
ctx.fillStyle = 'rgba(0,0,0,1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
(function clearLoop() {
clearCanvas();
requestAnimationFrame(clearLoop);
})();
(function animLoop(time) {
ctx.fillStyle = 'rgba(255,255,255,1)';
var isAlive = true;
for (var i = 0; i < particlesLength; i++) {
if (_particles[i].tick()) isAlive = true;
}
requestAnimationFrame(animLoop);
})();
function resetParticles() {
for (var i = 0; i < particlesLength; i++) {
_particles[i].reset();
}}

Adding objects into array

Could someone tell me what's wrong with this code ? I am trying to fill canvas with squares as objects but as the loop is done and i am trying to draw that square on canvas nothing happens...
var canvas = document.getElementById('c');
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(35, 180, 218)";
var rectHeight = 5;
var rectWidth = 5;
var cells = [];
for (var i = 0; i <= canvas.width/rectWidth; i++) {
for (var x = 0; x <= canvas.height/rectHeight; x++) {
cells[i] = {
posX : i*rectWidth,
posY : x*rectHeight,
draw : function() {
ctx.fillRect(posX, posY, rectWidth, rectHeight);
},
clear : function() {
ctx.clearRect(posX, posY, rectWidth, rectHeight);
}
};
}
}
cells[2].draw;
var canvas = document.getElementById('c');
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
var rectHeight = 15;
var rectWidth = 15;
var cells = [];
for (var i = 0; i <= canvas.width/rectWidth; i++) {
for (var x = 0; x <= canvas.height/rectHeight; x++) {
cells[i] = {
posX : i*rectWidth,
posY : x*rectHeight,
draw : function() {
ctx.fillRect(this.posX, this.posY, rectWidth, rectHeight);
},
clear : function() {
ctx.clearRect(positionX, positionY, rectWidth, rectHeight);
}
};
}
}
cells[2].draw();
<canvas id="c" width="500" height="400"></canvas>
Thanks for the help #Xufox #SimranjitSingh and #Andreas..
Code now works like this:
var canvas = document.getElementById('c');
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(35, 180, 218)";
var rectHeight = 5;
var rectWidth = 5;
var cells = [];
for (var i = 0; i <= canvas.width/rectWidth; i++) {
for (var x = 0; x <= canvas.height/rectHeight; x++) {
cells[i*x] = {
posX : i*rectWidth,
posY : x*rectHeight,
draw : function() {
ctx.fillRect(this.posX, this.posY, rectWidth, rectHeight);
},
clear : function() {
ctx.clearRect(this.posX, this.posY, rectWidth, rectHeight);
}
};
}
}
cells[2].draw();

Weird issue with Javascript game

OK, so I'm new to JS, so am trying to make the basic 'breakout' game. What I'm trying to do is arrange the bricks into a triangle shape (or more accurately, forming a triangle out of the absence of bricks). But when I choose which items in the 2D array I want to equal 0 (no brick), it only allows me choose one. after that, the game simply won't load.
Weirdest thing is, it will only accept the first line in this part. No matter what I change, the second line onwards will cause the game to not load:
bricks[0][10]=0;
bricks[7][16]=0;
bricks[7][15]=0;
bricks[7][14]=0;
bricks[7][13]=0;
bricks[7][12]=0;
bricks[7][11]=0;
bricks[7][10]=0;
bricks[7][9]=0;
bricks[7][8]=0;
bricks[7][7]=0;
bricks[7][6]=0;
bricks[7][5]=0;
bricks[7][4]=0;
bricks[7][3]=0;
bricks[7][17]=0;
bricks[6][4]=0;
bricks[6][16]=0;
bricks[5][15]=0;
bricks[5][5]=0;
bricks[4][14]=0;
bricks[4][6]=0;
bricks[3][13]=0;
bricks[3][7]=0;
bricks[2][8]=0;
bricks[2][12]=0;
bricks[1][11]=0;
bricks[1][9]=0;
Also, i know the code is incomplete and flawed as it is. It's not finished and still need a lot of polishing up.
Here's my entire code
canvasApp();
function canvasApp(){
var canvas=document.getElementById("canvas")
if (!canvas || !canvas.getContext){
return;
}
var ctx = canvas.getContext("2d");
if (!ctx) {
return
}
//Application States
const GAME_STATE_TITLE = 0;
const GAME_STATE_NEW_LEVEL = 1;
const GAME_STATE_GAME_OVER = 2;
var currentGameState = 0;
var currentGameStateFunction = null;
var brickcount;
var bouncecount = 0;
//Initialise Start Screen State
var titleStarted = false;
var gameStarted = false;
var gameOver = false;
var keyPressList = [];
var keys = false //mouse or keys. false = mouse control, vice versa
var difficulty = 0;
// Declarations for the game
var dx = 6;
var dy = 6;
var x = 150;
var y = 100;
var r = 10;
var WIDTH = 500;
var HEIGHT = 400;
var ballx = 200;
var bally = 200;
var paddlex = WIDTH/1.2;
var paddleh = 10;
var paddlew = 75;
var paddledx = 30
var mouseX;
var bricks;
var NROWS;
var NCOLS;
var BRICKWIDTH;
var BRICKHEIGHT;
var PADDING;
var rowcolours = ["#FF1C0A", "#FFFD0A", "#00A308", "#0008DB", "#EB0093"];
var paddlecolour = "#FF00FF";
var ballcolour = "#00FFFF";
var backcolour = "#0000FF";
function initbricks() {
NROWS = 9
NCOLS = 21
brickcount = NROWS*NCOLS;
BRICKWIDTH = (WIDTH/NCOLS) - 1;
BRICKHEIGHT = 10;
PADDING = 1;
bricks = new Array(NROWS);
for (i=0; i < NROWS; i++) {
bricks[i] = new Array(NCOLS);
for (j=0; j < NCOLS; j++) {
bricks[i][j] = 1;
}
bricks[0][10]=0;
bricks[7][16]=0;
bricks[7][15]=0;
bricks[7][14]=0;
bricks[7][13]=0;
bricks[7][12]=0;
bricks[7][11]=0;
bricks[7][10]=0;
bricks[7][9]=0;
bricks[7][8]=0;
bricks[7][7]=0;
bricks[7][6]=0;
bricks[7][5]=0;
bricks[7][4]=0;
bricks[7][3]=0;
bricks[7][17]=0;
bricks[6][4]=0;
bricks[6][16]=0;
bricks[5][15]=0;
bricks[5][5]=0;
bricks[4][14]=0;
bricks[4][6]=0;
bricks[3][13]=0;
bricks[3][7]=0;
bricks[2][8]=0;
bricks[2][12]=0;
bricks[1][11]=0;
bricks[1][9]=0;
}
}
initbricks();
function switchGameState(newState) {
currentGameState = newState;
switch (currentGameState) {
case GAME_STATE_TITLE:
currentGameStateFunction = gameStateTitle;
break;
case GAME_STATE_NEW_LEVEL:
currentGameStateFunction = gameStatePlayLevel;
break;
case GAME_STATE_GAME_OVER:
currentGameStateFunction = gameStateGameOver;
break;
}
}
function gameStateTitle(){
if (titleStarted != true){
ctx.fillStyle = '#000000';
ctx.fillRect(0,0,500,400);
ctx.fillStyle = '#ffffff';
ctx.font = '20px _sans';
ctx.textBaseline = 'top';
ctx.fillText ("Breakout!", 200,150);
ctx.fillText ("Press Space to Play", 170,200);
if (keys == 0 ) {
ctx.fillText ("Mouse selected", 180,250);
ctx.fillText ("Press k to switch to keys", 140,300);
} else {
ctx.fillText ("Keys selected", 190,250);
ctx.fillText ("Press m to switch to mouse", 140,300);
}
titleStarted = true;
}else{
if (keyPressList[75] == true){
keys = 1;
titleStarted = false;
gameStateTitle(); // Redraw the title page
}
if (keyPressList[77] == true){
keys = 0;
titleStarted = false;
gameStateTitle();
}
if (keyPressList[32] == true){
switchGameState(GAME_STATE_NEW_LEVEL);
titleStarted = false;
}
}
}
function gameStatePlayLevel(){
ctx.fillStyle = '#000000';
ctx.fillRect(0,0,500,400);
ctx.fillStyle = '#ffffff';
// Update the game state and check for game over
function update() {
x+=dx
y+=dy
if (keys == 0) {
paddlex = mouseX;
}else{
if (keyPressList[37]==true){
paddlex-=paddledx;
}
if (keyPressList[39]==true){
paddlex+=paddledx;
}
}
//have we hit a brick?
rowheight = BRICKHEIGHT + PADDING;
colwidth = BRICKWIDTH + PADDING;
row = Math.floor(y/rowheight);
col = Math.floor(x/colwidth);
//if so, reverse the ball and mark the brick as broken
if (y < NROWS * rowheight && row >= 0 && col >= 0 && bricks[row][col] == 1) {
dy = -dy;
bricks[row][col] = 0;
brickcount--;
if (brickcount == 0) {
switchGameState(GAME_STATE_NEW_LEVEL);
difficulty+=1;
initbricks();
x=250;
y=200 + (difficulty*20);
brickcount=NROWS*NCOLS;
bouncecount=0;
}
}
if( x<0 || x>WIDTH) dx=-dx;
if( y<0 || y>HEIGHT) dy=-dy;
else if (y + dy > HEIGHT) {
if (x > paddlex && x < paddlex + paddlew) {
dx = 8 * ((x-(paddlex+paddlew/2))/paddlew);
dy = -dy;
bouncecount++;
}
else {
//game over, so stop the animation
switchGameState(GAME_STATE_GAME_OVER);
initbricks();
}
}
}
function render() {
ctx.save();
function circle(x,y,r) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, true);
ctx.fill();
}
function rect(x,y,w,h) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
//draw bricks
for (i=0; i < NROWS; i++) {
ctx.fillStyle = rowcolours [i];
for (j=0; j < NCOLS; j++) {
if (bricks[i][j] == 1) {
rect((j * (BRICKWIDTH + PADDING)) + PADDING,
(i * (BRICKHEIGHT + PADDING)) + PADDING, BRICKWIDTH, BRICKHEIGHT);
}
}
}
circle(x, y, 10);
// init_paddle();
ctx.fillStyle = paddlecolour;
rect (paddlex, HEIGHT-paddleh, paddlew, paddleh);
ctx.restore();
show_result()
}
update();
render();
}
function gameStateGameOver(){
if (gameOver != true){
bouncecount=0;
ctx.fillStyle = '#000000';
ctx.fillRect(0,0,500,400);
ctx.fillStyle = '#ffffff';
ctx.font = '20px _sans';
ctx.textBaseline = 'top';
ctx.fillText ("Game over", 200,150);
ctx.fillText ("Press Space to Restart", 160,200);
ctx.fillText ("You completed " + difficulty + " levels", 160,240);
difficulty=0;
gameOver = true;
}else{
if (keyPressList[32] == true){
switchGameState(GAME_STATE_TITLE);
gameOver = false;
}
}
}
function runGame(){
currentGameStateFunction();
}
// Key handler
document.onkeydown = function(e){
e= e?e:window.event;
keyPressList[e.keyCode] = true;
}
document.onkeyup = function(e){
e= e?e:window.event;
keyPressList[e.keyCode] = false;
}
function onMouseMove(evt) {
// Event data passes to this function
mouseX = evt.clientX-canvas.offsetLeft - paddlew/2;
// Assign the relative position of the mouse in the canvas to mouseX
mouseY = evt.clientY-canvas.offsetTop;
//Do the same for mouseY
document.title="("+mouseX+","+mouseY+")";
//Put the mouse X and Y in the title for info
paddlex = mouseX;
// Position the paddle
}
canvas.addEventListener("mousemove",onMouseMove, false);
//Application start
switchGameState(GAME_STATE_TITLE);
const FRAME_RATE = 40;
var intervalTime = 1000/FRAME_RATE;
setInterval(runGame, intervalTime);
function show_result(){
ctx.fillText ("There are " + brickcount + " bricks", 160,200);
ctx.fillText ("Paddle bounces are " + bouncecount , 160,220);
}
}
With proper indenting, your code looks like this:
bricks = new Array(NROWS);
for (i=0; i < NROWS; i++) {
bricks[i] = new Array(NCOLS);
for (j=0; j < NCOLS; j++) {
bricks[i][j] = 1;
}
bricks[0][10]=0;
bricks[7][16]=0;
In other words, you're attempting to access bricks[7] in the very first iteration when only bricks[0] has been created. Properly close the first for loop with a } before running your list of overrides.

Moving content of canvas with a specific framerate

So I have this sprite animation which goes fine when it's not in movement (I need it to go on 20 fps max because if not the animation would be too fast), but when I try to move it across the screen, the movement looks really choppy. Any ideas on how to make the movement smoothly? Increase the framerate works, but I'd like to see if there is another option aside of that.
var canvasA = document.createElement("canvas");
var canvasB = document.createElement("canvas");
var contextA = canvasA.getContext("2d");
var contextB = canvasB.getContext("2d");
canvasA.style.position = "absolute";
canvasB.style.position = "absolute";
var xpos = 0;
var ypos = 0;
var index = 0;
var frameSizeX = 140;
var frameSizeY = 395;
var numFrames = 20;
var drawing_character = false;
var xPosition = 0;
var now, then, elapsed, startTime, fps, fpsInterval;
var fpscounter = setInterval(updatefps, 1000);
var forw = true;
var cfps = 0;
// Pictures
var background = new Image();
background.src = "http://i.imgur.com/3FDB45h.png";
var character = new Image();
character.src = "http://i.imgur.com/tziJajG.png";
function redraw() {
contextB.clearRect(0, 0, canvasB.width, canvasB.height);
contextB.drawImage(background, 0, 0);
}
function drawchar() { // Input= fps max
requestAnimationFrame(drawchar);
now = Date.now();
elapsed = now - then;
if (elapsed > fpsInterval) {
then = now - (elapsed % fpsInterval);
contextA.clearRect(0, 0, 800, 600);
contextA.drawImage(character,
xpos,
ypos,
frameSizeX,
frameSizeY,
xPosition,
0,
frameSizeX,
frameSizeY);
xpos += frameSizeX;
index += 1;
if (index >= numFrames) {
xpos = 0;
ypos = 0;
index = 0;
} else if (xpos + frameSizeX > character.width) {
xpos = 0;
ypos += frameSizeY;
}
cfps++;
}
}
function updatefps() {
document.getElementById("fps").innerHTML = "FPS: " + cfps;
cfps = 0;
}
function aqui() {
prepareCanvas();
setInterval(redraw, 1000/60);
animarchar(20);
setInterval(move, 1);
}
function move() {
if (forw === true) {
xPosition += 1;
if (xPosition === 300){
forw = false;}
} else {
xPosition -= 1;
if (xPosition === 0){
forw = true;}
}
}
function prepareCanvas() {
canvasB.width = 800;
canvasB.height = 600;
canvasA.width = canvasB.width;
canvasA.height = canvasB.height;
//document.body.appendChild(canvasB);
document.body.appendChild(canvasA);
}
function animarchar(fps) {
fpsInterval = 1000 / fps;
then = Date.now();
startTime = then;
drawchar();
}
window.onload = function () {
aqui();
};
Here is a jsFiddle: https://jsfiddle.net/qb171ghf/

Canvas Asteroids game

I'm making Asteroids game in html5 with canvas. I've made moveable ship, which can rotate right and left and can move forward. I've added friction to slow it down when keys aren't pressed. Next thing to do is shooting bullets/lasers. I have yet only one shot and bullet goes forward, but it follow the movement of ship too :/ I don't know how to detach it from the ship and how to make more bullets.
Here's the code:
window.addEventListener('keydown',doKeyDown,true);
window.addEventListener('keyup',doKeyUp,true);
var canvas = document.getElementById('pageCanvas');
var context = canvas.getContext('2d');
var angle = 0;
var H = window.innerHeight; //*0.75,
var W = 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 = 10;
var frict = 0.99;
var brakes = 0.90;
var keys = new Array();
var fire = false;
var laser = false;
///////////////////lasery xD
var lx = 25,
ly = 9,
lw = 4,
lh = 4;
function doKeyUp(evt){
keys[evt.keyCode] = false;
fire = false;
}
function doKeyDown(evt){
keys[evt.keyCode] = true;
}
//OOOOOOOOOOOOOOOOOOLASEROOOOOOOOOOOOOOOOOOOOOOOOOOO
function drawLaser() {
context.fillStyle = "red";
context.fillRect(lx,ly,lw,lh);
}
function moveLaser() {
lx += 2;
}
//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 > maxVel){
vy = maxVel;
}
}
function shipMovement(){
if(38 in keys && keys[38]){
xyVelocity();
fire = true;
}
if(40 in keys && keys[40]){
vx = 0;
vy = 0;
}
if(37 in keys && keys[37]){
decrementAngle();
};
if (39 in keys && keys[39]){
incrementAngle();
};
if (32 in keys && keys[32]){
laser = 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(){
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 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();
}
if(laser){
drawLaser();
moveLaser();
}
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();*/
blazeatron420();
context.restore();
}
setInterval(drawEverything, 20);
And the fiddle http://jsfiddle.net/tomasthall/q40zvd6v/1/
I moved your laser drawing out of the rotated context.
Initiated lx and ly to x y in the moment of firing.
laser = true;
lx = x;
ly = y;
http://jsfiddle.net/q40zvd6v/2/
Now you need to just give the laser a proper vector.
That can be calculated from the angle of your ship and some trigonometry.
if (32 in keys && keys[32]){
laser = true;
lx = x;
ly = y;
var angle_in_radians = convertToRadians(angle);
lvx = Math.cos(angle_in_radians);
lvy = Math.sin(angle_in_radians);
};
And it shoots fine now:
http://jsfiddle.net/q40zvd6v/4/
Looks much nicer if you add the ship vector to projectile vector though.
if (32 in keys && keys[32]){
laser = true;
lx = x;
ly = y;
var angle_in_radians = convertToRadians(angle);
lvx = Math.cos(angle_in_radians);
lvy = Math.sin(angle_in_radians);
lvx += vx;
lvy += vy;
};
http://jsfiddle.net/q40zvd6v/5/
Good luck on your game :>
this be your problem right here:
context.rotate(convertToRadians(angle));
context.translate(-7,-10);
you rotate everything on the canvas..
when in fact you should only be rotating the blazeatron420
Please look at this question:
How do I rotate a single object on an html 5 canvas?
and see the solutions for rotating a single "object"..

Categories

Resources