This is a game i am making. I am getting a very wiered error. When i click on first tile i am calling afunction level3. Which draws few vertical lines. After that even clearing the canvas my level2 is being executed.
Need Help !
You dont have to look entire code. Just the level2 and level 3 function.Check Demo link.When you click on first tile "Trader" level3 is called but remains for a short time and again level2 is executing without even calling.
SOLVED
Fixed Demo :http://stndlkr200.github.io/bugfixed.html
Bug Demo : http://stndlkr200.github.io/testbug.html
<html>
<head>
<style>
*{
background-color: black;
}
canvas{display: block;}
</style>
<body>
<canvas id="canvas"></canvas>
<script type="text/javascript">
window.onload=function() {
var canvas=document.getElementById('canvas');
var ctx=canvas.getContext('2d');
var w=window.innerWidth;
canvas.width=w;
var h=window.innerHeight;
canvas.height=h;
var ctr=0;
var words=["We Need Swaraj","Play for Change","Aam Aadmi Party","5 saal Kejriwal","AAP for
Change","Vote for Good","Arvind Kejriwal","Kejriwal Fir Se","We Need Swaraj","Play for
Change","Aam Aadmi Party","5 saal Kejriwal","AAP for Change","Vote for Good","Arvind
Kejriwal","Kejriwal Fir Se","We Need Swaraj","Play for Change","Aam Aadmi Party","5 saal
Kejriwal","AAP for Change","Vote for Good","Arvind Kejriwal","Kejriwal Fir Se","We Need
Swaraj","Play for Change","Aam Aadmi Party","5 saal Kejriwal","AAP for Change","Vote for
Good","Arvind Kejriwal","Kejriwal Fir Se"];
var j=0;
function box(x,y){
this.x=x;
this.y=y;
this.xVelo=10+Math.random()*20;
this.yVelo=1;
this.width=500;
this.height=500;
this.r=Math.round(Math.random()*255);
this.g=Math.round(Math.random()*255);
this.b=Math.round(Math.random()*255);
this.rgba = "rgba("+this.r+","+this.g+","+this.b+",1)";
this.message=words[i];
i++;
this.draw = function()
{
ctx.strokeStyle = this.rgba;
ctx.strokeRect(this.x,this.y,this.width,this.height);
ctx.font = 'bold 50px Calibri';
ctx.textAlign = 'center';
ctx.textBaseline='middle';
ctx.fillStyle =this.rgba;
ctx.fillText(this.message, this.x+this.width/2, this.y+this.height/2);
ctr++;
if(ctr>7000){
clearInterval(timer1);
ctx.font = 'bold 50px Calibri';
ctx.textAlign = 'center';
ctx.textBaseline='middle';
ctx.fillStyle ="white";
ctx.fillText("Vote For Honest Leaders", 400, 400);
ctx.fillText("Vote For Kejriwal", 600, 30);
ctx.fillText("Vote For Delhi", 1000, 400);
ctx.strokeStyle="rgba(200,56,78,0.4)";
ctx.strokeRect(550,200,100,60);
ctx.font = 'bold 20px Calibri';
ctx.textAlign = 'center';
ctx.textBaseline='middle';
ctx.fillStyle ="green";
ctx.fillText("Lets Play !", 600, 230);
}
this.update();
}
this.update = function()
{
if(this.x < 0) {
this.x = 0;
this.xVelo *= -1;
}
if(this.x > w - this.width)
{
this.x = w - this.width;
this.xVelo *= -5;
}
if(this.y < 0) {
this.y = 0;
this.yVelo *= -1;
}
if(this.y < h - this.height)
this.yVelo += .25;
if(this.y > h - this.height)
{
//this.xVelo *= .5
this.yVelo *= .5
this.y = h - this.height;
this.yVelo *= -2;
}
this.x += this.xVelo/5;
this.y += this.yVelo/3;
}
}
var boxes = [];
function draw()
{
ctx.globalCompositeOperation = "source-over";
ctx.fillStyle = "rgba(0,0,0,0.5)"
ctx.fillRect(0,0,w,h);
ctx.globalCompositeOperation = "lighter"
for(i=0; i < boxes.length; i++)
boxes[i].draw();
update();
}
function update()
{
for(i=0; i < boxes.length; i++)
boxes[i].update();
}
var timer1= setInterval(function(){
boxes.push( new box(0,0))
},1000);
var timer= setInterval(draw,30);
canvas.addEventListener("click",play_function);
function play_function(e){
button_x=e.pageX;
button_y=e.pageY;
if(button_x<650 && button_x>500 && button_y<260 && button_y >200)
start_levels();
}
function start_levels(){
clearInterval(timer);
canvas.removeEventListener('click',play_function);
level1();
}
var level1=function(){
ctx.clearRect(0,0,w,h);
ctx.font = '13px Arial';
ctx.textAlign = 'center';
ctx.textBaseline='middle';
ctx.fillStyle ="white";
ctx.fillText("MufflerMan wants you to sketch something.. Please do",500,10);
var dots=[];
var dotXval=["500","250","150","720","850"];
var dotYval=["100","250","300","250","300"];
function dot(xcod,ycod,radius,value){
this.xcod=xcod;
this.ycod=ycod;
this.radius=radius;
this.val=value;
}
function create_dots(x,y,radius,value){
ctx.beginPath();
ctx.arc(x,y,radius,0,2*Math.PI,true);
ctx.fillStyle="white";
ctx.fill();
ctx.font = '10px Arial';
ctx.textAlign = 'center';
ctx.textBaseline='middle';
ctx.fillStyle ="white";
ctx.fillText(value,x-10,y-10);
}
function startLevel(){
var dotRadius=10;
var dotsCount=5;
for (var i = 0; i <dotsCount; i++){
dots.push(new dot(dotXval[i],dotYval[i],dotRadius,i+1));
}
for (var j=0; j<dots.length; j++) {
create_dots(dots[j].xcod, dots[j].ycod,5,dots[j].val);
}
}
startLevel();
var mouse={x:0,y:0};
var drag4sketch=function(e){
mouse.x=e.pageX-this.offsetLeft;
mouse.y=e.pageY-this.offsetTop;
}
canvas.addEventListener('mousemove',drag4sketch);
ctx.lineWidth = 6;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = 'blue';
canvas.addEventListener('mousedown',function(e){
ctx.beginPath();
ctx.moveTo(mouse.x,mouse.y);
canvas.addEventListener('mousemove',sketch,false);
},false);
canvas.addEventListener('mouseup',function(){
canvas.removeEventListener('mousemove',sketch,false);
},false);
var sketch=function(){
ctx.lineTo(mouse.x,mouse.y);
ctx.stroke();
}
var time=0;
var clock=function(){
ctx.clearRect(1000,20,1200,200);
ctx.font = '20px Arial';
ctx.fillStyle ="white";
ctx.fillText(time++ + ' sec',1120,30);
if(time>2){
ctx.clearRect(0,0,w,h);
canvas.removeEventListener('mousemove',sketch);
canvas.removeEventListener('mouseup',level1);
canvas.removeEventListener('mousedown',level1);
canvas.removeEventListener('mousemove',level1);
canvas.removeEventListener('mouseup',sketch);
canvas.removeEventListener('mousedown',sketch);
canvas.removeEventListener('mousemove',sketch);
canvas.removeEventListener('mousemove',drag4sketch);
level2();
}
}
setInterval(clock,1000);
clearInterval(clock);
}
function level2(){
var m={x:0,y:0};
var rect_cordsX=["100","300","500","700","900","1100"];
var rect_cordsY=["50","160","370","480"];
var hints=
["Trader","Businessman","Student","Teacher","Writer","Scientist","Politicion","MufflerMan","Auto
Driver","Police","Doctor","Industrialist","Soldier","Musician","Cobbler","Social
Worker","MufflerMan","Engineer","Advocate","Reporter","Editor","MufflerMan","Poet","Actor"];
ctx.font = 'bold 13px Arial';
ctx.textAlign = 'center';
ctx.textBaseline='middle';
ctx.fillStyle ="white";
ctx.fillText("MufflerMan wants you to find his companions..Your Luck! ",620,10);
var hint_cards=[];
var hint_card=function(x,y,hint){
this.x=x;
this.y=y;
this.hint=hint;
}
for (var i = 0; i< rect_cordsX.length; i++) {
for (var j=0;j<rect_cordsY.length;j++){
hint_cards.push(new hint_card(rect_cordsX[i],rect_cordsY[j],hints[i*j]));
}
}
for (var k=0;k<hint_cards.length;k++){
ctx.strokeStyle="white";
ctx.strokeRect(hint_cards[k].x,hint_cards[k].y,100,80);
ctx.font = 'bold 15px Calibri';
ctx.textAlign="center";
ctx.textBaseline="middle";
ctx.fillStyle="white";
ctx.fillText(hints[k],parseInt(hint_cards[k].x)+50,parseInt(hint_cards[k].y)+40);
}
function click_hint_card(e){
m.x=e.pageX-this.offsetLeft;
m.y=e.pageY-this.offsetTop;
if(m.x>100 && m.y>50 && m.x<200 && m.y<130){
console.log("Trader");
level3();
}
}
canvas.addEventListener('click',click_hint_card);
}
function level3 (){
ctx.clearRect(0,0,w,h);
ctx.beginPath();
for(var x=100;x<1200;x+=100){
ctx.moveTo(x,100);
ctx.lineTo(x,200);
ctx.moveTo(x,300);
ctx.lineTo(x,500);
}
ctx.strokeStyle="white";
ctx.stroke();
}
}
</script>
</body>
</head>
</html>
Your setInterval(clock, 1000); calls a block of code:
var clock=function(){
ctx.clearRect(1000,20,1200,200);
ctx.font = '20px Arial';
ctx.fillStyle ="white";
ctx.fillText(time++ + ' sec',1120,30);
if(time>2){
ctx.clearRect(0,0,w,h);
canvas.removeEventListener('mousemove',sketch);
canvas.removeEventListener('mouseup',level1);
canvas.removeEventListener('mousedown',level1);
canvas.removeEventListener('mousemove',level1);
canvas.removeEventListener('mouseup',sketch);
canvas.removeEventListener('mousedown',sketch);
canvas.removeEventListener('mousemove',sketch);
canvas.removeEventListener('mousemove',drag4sketch);
level2();
}
}
I suspect it is the last line of that clock function that is causing your problem. Remove it and it should go away.
Related
this is my first time asking a question on StackOverflow. I was wondering on to make an object move based on its x and y coordinates with keyboard inputs. I am making a grid based movement for my game. I apologize for any bad code or formatting. I am making a web game for a school project. Do comment if u need my html code. Here's my code below:
$(function(){
var health = 800;
var fuel = 100;
var tankX = 25;
var tankY = 530;
var c = document.getElementById("gameCanvas");
var ctx = c.getContext('2d');
ctx.beginPath();
ctx.fillStyle = "grey";
ctx.fillRect(0,600,1110,100);
ctx.stroke();
for (i = 100; i < 600; i += 100)
{
ctx.moveTo(0, i);
ctx.lineTo(c.width, i);
ctx.stroke();
}
for (i = 100; i < 1110; i += 100)
{
ctx.moveTo(i, 0);
ctx.lineTo(i,600);
ctx.stroke();
}
ctx.fillStyle ="black";
ctx.font = "20px Lucida Sans Typewriter ";
ctx.fillText("Health:",500,630);
ctx.fillText("Fuel:", 100,630);
ctx.fillStyle = "green";
ctx.fillRect(500,640,(health/800)*250,40);
function fuelGauge(){
ctx.fillStyle="yellow";
ctx.fillRect(100,640,(fuel/100)*250,40);
console.log(fuel);
}
function drawTank(){
ctx.fillStyle = "#283618"
ctx.fillRect(tankX,tankY,50,50);
ctx.moveTo(tankX,tankY);
}
drawTank();
fuelGauge();
});
I don't do a lot of jquery, but since nobody answered, here's an example. It uses the keydown event to listen for the arrow keys. I'm sure there's lots of room for improvement, but it should get you started.
var c = document.getElementById("gameCanvas");
var ctx = c.getContext('2d');
var tankX = 25;
var tankY = 530;
var health = 800;
var fuel = 100;
$('html').keydown(function(e){
eraseTank();
if (e.key == "ArrowUp") {
if (tankY > 15) tankY -= 102;
}
else if (e.key == "ArrowDown") {
if (tankY < 530) tankY += 102;
}
else if (e.key == "ArrowLeft") {
if (tankX > 25) tankX -= 100;
}
else if (e.key == "ArrowRight") {
if (tankX < 525) tankX += 100;
}
drawTank();
});
function fuelGauge(){
ctx.fillStyle="yellow";
ctx.fillRect(100,640,(fuel/100)*250,40);
console.log(fuel);
}
function drawTank(){
ctx.fillStyle = "#283618"
ctx.fillRect(tankX,tankY,50,50);
ctx.moveTo(tankX,tankY);
}
function eraseTank(){
ctx.fillStyle = "white"
ctx.fillRect(tankX,tankY,50,50);
ctx.moveTo(tankX,tankY);
}
function drawGame()
{
ctx.beginPath();
ctx.fillStyle = "grey";
ctx.fillRect(0,600,1110,100);
ctx.stroke();
for (i = 100; i < 600; i += 100)
{
ctx.moveTo(0, i);
ctx.lineTo(c.width, i);
ctx.stroke();
}
for (i = 100; i < 1110; i += 100)
{
ctx.moveTo(i, 0);
ctx.lineTo(i,600);
ctx.stroke();
}
ctx.fillStyle ="black";
ctx.font = "20px Lucida Sans Typewriter ";
ctx.fillText("Health:",500,630);
ctx.fillText("Fuel:", 100,630);
ctx.fillStyle = "green";
ctx.fillRect(500,640,(health/800)*250,40);
}
$(function(){
drawGame();
fuelGauge();
drawTank();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id="gameCanvas" width="600" height="1100"></canvas>
When you run the snippet, make sure you click on the game board first.
I was working on the paddle part of my code and was fixing other errors and after it was fixed, it gave me this error "p5practice.js:97 Uncaught TypeError: Cannot read property 'y' of undefined" Also, if that error can be fixed, how do I properly get my paddle to work? I've looked at several other pong like examples and have had no luck with mine working.
//variables
var canvas;
var ctx;
var w;
var h;
var ball;
var paddle;
var score1;
//ball object
var BALL = function(x, y) {
this.x = x;
this.y = y;
this.color = "white";
this.radius = 12;
this.vx = 3;
this.vy = -3;
};
//paddle 1
var PADDLE = function(x, y) {
this.x = 10;
this.y = h/2 - 50;
this.color = "white";
this.width = 5;
this.height = 100;
};
window.addEventListener("keydown", movePaddle);
//keydown event
//down
function movePaddle(e) {
switch (event.keyCode){
case 38: //up
console.log(paddle.y)
if (paddle.y - 30 >= -10) {
paddle.y -= 30;
}
break;
case 40: // down
console.log(paddle.y)
if (paddle.y + 30 < 305) {
paddle.y += 30;
}
break;
}
}
//DOM load
window.onload = function() {
canvas = document.getElementById('canvas');
w = canvas.width;
h = canvas.height;
ctx = canvas.getContext('2d');
ball = new BALL (w/2, h/2);
paddle = new PADDLE(w-100, h/2);
drawScore();
startGame();
movePaddle();
};
function startGame() {
requestAnimationFrame(startGame);
ctx.clearRect(0, 0, w, h);
ball.x += ball.vx;
ball.y += ball.vy;
ctx.fillStyle = ball.color;
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.radius, 0, 2*Math.PI, true);
ctx.closePath();
ctx.save();
ctx.fill();
ctx.restore();
ctx.fillStyle = paddle.color;
ctx.beginPath();
ctx.save();
ctx.shadowBlur = 20;
ctx.shadowOffsetX = 4;
ctx.shadowOffsetY = 4;
ctx.shadowColor = "red";
ctx.fillRect(paddle.x, paddle.y, paddle.width, paddle.height);
ctx.closePath();
ctx.restore();
}
//collision with walls
//https://www.khanacademy.org/computer-programming/paddle-ball/830543654
//bottom
if(ball.y >= 390) {
ball.vy = -ball.vy;
console.log("bottom hit");
}
//top
if(ball.y <= 10) {
ball.vy = -ball.vy;
console.log("top hit");
}
//right
if (ball.x >= 590){
ball.vx = -ball.vx;
console.log("right hit");
}
//left
if(ball.x <= 10){
score++;
ball.x = w/2;
ball.y = h/2;
console.log("left hit");
}
//collision with paddle
if(ball.x<15){
if(ball.y>paddle.y && ball.y<paddle.y + paddle.height){
ball.vy = -ball.vy;
console.log("paddle");
}
}
//reset
//https://bl.ocks.org/ruffrey/1e242222aebbcd102a53
//not finished
function reset(){
ball.x;
ball.y;
}
//score
var score = 0;
function drawScore(){
ctx.font ="16px Arial";
ctx.fillStyle ="#0095DD";
ctx.fillText("Score: "+score,w/2, 20);
}
var leftScore = this.x > 10;
if (leftScore){
playerCount.score++;
}
this.reset();
canvas {
border: 3px solid yellow;
background-color: black;
}
<!doctype html>
<html>
<head>
<title>Pong</title>
<script src="p5practice.js"></script>
<link rel= 'stylesheet' href="p5practice.css">
</head>
<body>
<canvas id="canvas" width="600" height="400"></canvas>
</script>
</body>
</html>
You need to move your if statements at the bottom into the onload or startGame function. They are running before the variable ball is getting initialized. So you are getting the error that is saying ball is undefined
You will also need to move this or it will complain about x:
var leftScore = this.x > 10;
//variables
var canvas;
var ctx;
var w;
var h;
var ball;
var paddle;
var score1;
//ball object
var BALL = function(x, y) {
this.x = x;
this.y = y;
this.color = "white";
this.radius = 12;
this.vx = 3;
this.vy = -3;
};
//paddle 1
var PADDLE = function(x, y) {
this.x = 10;
this.y = h / 2 - 50;
this.color = "white";
this.width = 5;
this.height = 100;
};
window.addEventListener("keydown", movePaddle);
//keydown event
//down
function movePaddle(e) {
switch (event.keyCode) {
case 38: //up
console.log(paddle.y)
if (paddle.y - 30 >= -10) {
paddle.y -= 30;
}
break;
case 40: // down
console.log(paddle.y)
if (paddle.y + 30 < 305) {
paddle.y += 30;
}
break;
}
}
//DOM load
window.onload = function() {
canvas = document.getElementById('canvas');
w = canvas.width;
h = canvas.height;
ctx = canvas.getContext('2d');
ball = new BALL(w / 2, h / 2);
paddle = new PADDLE(w - 100, h / 2);
drawScore();
startGame();
movePaddle();
//bottom
if (ball.y >= 390) {
ball.vy = -ball.vy;
console.log("bottom hit");
}
//top
if (ball.y <= 10) {
ball.vy = -ball.vy;
console.log("top hit");
}
//right
if (ball.x >= 590) {
ball.vx = -ball.vx;
console.log("right hit");
}
//left
if (ball.x <= 10) {
score++;
ball.x = w / 2;
ball.y = h / 2;
console.log("left hit");
}
//collision with paddle
if (ball.x < 15) {
if (ball.y > paddle.y && ball.y < paddle.y + paddle.height) {
ball.vy = -ball.vy;
console.log("paddle");
}
}
};
function startGame() {
requestAnimationFrame(startGame);
ctx.clearRect(0, 0, w, h);
ball.x += ball.vx;
ball.y += ball.vy;
ctx.fillStyle = ball.color;
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.radius, 0, 2 * Math.PI, true);
ctx.closePath();
ctx.save();
ctx.fill();
ctx.restore();
ctx.fillStyle = paddle.color;
ctx.beginPath();
ctx.save();
ctx.shadowBlur = 20;
ctx.shadowOffsetX = 4;
ctx.shadowOffsetY = 4;
ctx.shadowColor = "red";
ctx.fillRect(paddle.x, paddle.y, paddle.width, paddle.height);
ctx.closePath();
ctx.restore();
}
//collision with walls
//https://www.khanacademy.org/computer-programming/paddle-ball/830543654
//reset
//https://bl.ocks.org/ruffrey/1e242222aebbcd102a53
//not finished
function reset() {
ball.x;
ball.y;
}
//score
var score = 0;
function drawScore() {
ctx.font = "16px Arial";
ctx.fillStyle = "#0095DD";
ctx.fillText("Score: " + score, w / 2, 20);
var leftScore = this.x > 10;
if (leftScore) {
playerCount.score++;
}
this.reset();
}
canvas {
border: 3px solid yellow;
background-color: black;
}
<!doctype html>
<html>
<head>
<title>Pong</title>
<script src="p5practice.js"></script>
<link rel='stylesheet' href="p5practice.css">
</head>
<body>
<canvas id="canvas" width="600" height="400"></canvas>
</script>
</body>
</html>
I'm making an isometric map for a game, I can draw it, but I don't know how to implement a sort of 3d collision detection without Threejs or other 3d library.
It is possible? Maybe make the block an Object can help? I have searched, but I found only libraries.
This is my JavaScript code:
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
width = canvas.width = window.innerWidth,
height = canvas.height = window.innerHeight,
stop = false;
var tw, th;
var player;
setup();
draw();
function setup(){
ctx.translate(width/2,50);
tw = 60; //tile width
th = 30; // tile height
player = new Player(2,3,3);
};
function draw(){
ctx.clearRect(-width/2,-50,width*1.5,height+50);
for(var i = 0; i < 5; i++){
for(var j = 0; j < 5; j++){
drawBlock(i,j,1,tw,th);
}
}
if(!stop){
requestAnimationFrame(draw);
}
}
function drawBlock(x,y,z,w,h){
var top = "#eeeeee",
right = '#cccccc',
left = '#999999';
ctx.save();
ctx.translate((x-y)*w/2,(x+y)*h/2);
ctx.beginPath();
ctx.moveTo(0,-z*h);
ctx.lineTo(w/2,h/2-z*h);
ctx.lineTo(0,h-z*h);
ctx.lineTo(-w/2,h/2-z*h);
ctx.closePath();
ctx.fillStyle = "black";
ctx.stroke();
ctx.fillStyle = top;
ctx.fill();
ctx.beginPath();
ctx.moveTo(-w/2,h/2-z*h);
ctx.lineTo(0,h-z*h);
ctx.lineTo(0,h);
ctx.lineTo(0,h);
ctx.lineTo(-w/2,h/2);
ctx.closePath();
ctx.fillStyle = "black";
ctx.stroke();
ctx.fillStyle = left;
ctx.fill();
ctx.beginPath();
ctx.moveTo(w/2,h/2-z*h);
ctx.lineTo(0,h-z*h);
ctx.lineTo(0,h);
ctx.lineTo(0,h);
ctx.lineTo(w/2,h/2);
ctx.closePath();
ctx.fillStyle = "black";
ctx.stroke();
ctx.fillStyle = right;
ctx.fill();
ctx.restore();
}
function drawTile(x,y,stroke,col){
ctx.save();
ctx.translate((x-y)*tw/2,(x+y)*th/2);
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(tw/2,th/2);
ctx.lineTo(0,th);
ctx.lineTo(-tw/2,th/2);
ctx.closePath();
if(stroke){
ctx.stroke();
}else{
ctx.fillStyle = col;
ctx.fill();
}
ctx.restore();
}
function Player(x,y,z){
this.x = x;
this.y = y;
this.z = z;
this.w = 10; //width
this.h = 10; //height
}
canvas{
width:100%;
height:100%;
}
<canvas id="canvas"></canvas>
What you're after is cube collision. The first result I get for googling that is an article on MDN named 3D collision detection:
Mathematically this would look like so:
f(A,B) = (AminX <= BmaxX ∧ AmaxX >= BminX) ∧ (AminY <= BmaxY ∧ AmaxY >= BminY) ∧ (AminZ <= BmaxZ ∧ AmaxZ >= BminZ)
And in JavaScript, we'd use this:
function intersect(a, b) {
return (a.minX <= b.maxX && a.maxX >= b.minX) &&
(a.minY <= b.maxY && a.maxY >= b.minY) &&
(a.minZ <= b.maxZ && a.maxZ >= b.minZ);
}
I have a devastating problem that I can't fix.
The JS canvas is screwing up a rectangle next to a player function expression.Here is the player code:
var menuSwitch = 0;
var pocx = 210;
var pocy = 20;
var switch1;
var lvlSwitch = 1;
var spd = 10;
var mx,my;
var pl = pl();
function pl(){
return{
draw: function(){
//draw the player
ctx.clearRect(0,0,w,h);//clears so the player doesn't "drag"
ctx.beginPath();
ctx.fillStyle = 'blue';
ctx.arc(pocx, pocy, 10, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
//move the player
if(switch1 == 0){
pocx = 210;
pocy = 20;
}else if(switch1 == 1){
pocy -= spd;
}else if(switch1 == 2){
pocx -= spd;
}else if(switch1 == 3){
pocy += spd;
}else if(switch1 == 4){
pocx += spd;
}
//rect bounding the player
if(pocx < 5){//since half of the diameter of the player is 5, the edge of the circle "bounces"
switch1 = 4;
}
if(pocy < 5){
switch1 = 3;
}
if(pocx > w){
switch1 = 2;
}
if(pocy > h){
switch1 = 1;
}
}
};
}
The canvas is 420 by 420. The paint() function, which goes 30 milliseconds each time by a setInterval is displayed here:
function paint(){
//pl.draw();
if(menuSwitch == 0){
ctx.fillStyle = 'black';
ctx.fillRect(0,0,w,h);
ctx.fillStyle = 'skyblue';
ctx.fillRect(20,20,380,50);
ctx.font = 'normal 30pt Arial';
ctx.fillStyle = 'lime';
ctx.fillText("Math Path",105,60);
ctx.fillStyle = 'skyblue';
ctx.fillRect(105,150,210,25);//105+210=315
ctx.font = 'normal 15pt Arial';
ctx.fillStyle = 'lime';
ctx.fillText("Start",170,170);
}
if(menuSwitch == 1){
ctx.fillStyle = 'blue';
ctx.fillRect(300,20,120,20);
pl.draw();
}
}
However, I'm focusing on the place where menuSwitch == 1 in the if statement. You can see that I'm calling the player. The player shows up, but not the rectangle. Please help? :(
Useful link: Canvas Tutorial
Html code if you need it:
Jsfiddle
It is because you call ctx.fillRect(300,20,120,20); in the player function. Fo fix it, remove that line and add it to your paint function like:
function paint() {
ctx.clearRect(0, 0, w, h); //clears so the player doesn't "drag"
//pl.draw();
if (menuSwitch == 0) {
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, w, h);
ctx.fillStyle = 'skyblue';
ctx.fillRect(20, 20, 380, 50);
ctx.font = 'normal 30pt Arial';
ctx.fillStyle = 'lime';
ctx.fillText("Math Path", 105, 60);
ctx.fillStyle = 'skyblue';
ctx.fillRect(105, 150, 210, 25); //105+210=315
ctx.font = 'normal 15pt Arial';
ctx.fillStyle = 'lime';
ctx.fillText("Start", 170, 170);
}
if (menuSwitch == 1) {
ctx.fillStyle = 'blue';
pl.draw();
ctx.fillRect(300, 20, 120, 20);
}
}
Fiddle showing example: https://jsfiddle.net/22w9j3p0/
I found a pong game online and wanted to change it around a bit. I want to put a dashed line in the middle of the screen.
if I take out the dashed line the game works. It will work in Chrome but locks up on the Firefox OS simulator.
****Question: Why would this be the case?"****
Code:
function drawDashedLine() {
ctx.beginPath();
ctx.fillStyle = '#eee';
ctx.setLineDash([1,2]);
ctx.moveTo(0,H/2);
ctx.lineTo(320,H/2);
ctx.closePath();
ctx.stroke();
}
HTML:
<html>
<head>
<title>Firefox OS</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
// RequestAnimFrame: a browser API for getting smooth animations
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback ){
return window.setTimeout(callback, 1000 / 60);
};
})();
window.cancelRequestAnimFrame = ( function() {
return window.cancelAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
window.oCancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame ||
clearTimeout
} )();
//all global variables
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d"); // Create canvas context
//W = window.innerWidth, // Window's width
//H = window.innerHeight, // Window's height
var W = 310;
var H = 440;
var particles = []; // Array containing particles
var ball = {}; // Ball object
var paddles = [2]; // Array containing two paddles
var mouse = {}; // Mouse object to store it's current position
var points = 0; // Varialbe to store points
var fps = 60; // Max FPS (frames per second)
var flag = 0; // Flag variable which is changed on collision
var particlePos = {}; // Object to contain the position of collision
var multipler = 1; // Varialbe to control the direction of sparks
var startBtn = {}; // Start button object
var restartBtn = {}; // Restart button object
var over = 0; // flag varialbe, cahnged when the game is over
var init; // variable to initialize animation
var paddleHit;
// Add mousemove and mousedown events to the canvas
canvas.addEventListener("mousemove", trackPosition, true);
canvas.addEventListener("mousedown", btnClick, true);
// Set the canvas's height and width to full screen
canvas.width = W;
canvas.height = H;
// Ball object
ball = {
x: 50,
y: 50,
r: 5,
c: "red",
vx: 3,
vy: 7,
// Function for drawing ball on canvas
draw: function() {
ctx.beginPath();
ctx.fillStyle = this.c;
ctx.arc(this.x, this.y, this.r, 0, Math.PI*2, false);
ctx.fill();
}
};
// Start Button object
startBtn = {
w: 100,
h: 50,
x: W/2 - 50,
y: H/2 - 25,
draw: function() {
ctx.strokeStyle = "white";
ctx.lineWidth = "2";
ctx.strokeRect(this.x, this.y, this.w, this.h);
ctx.font = "18px Arial, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStlye = "white";
ctx.fillText("Start", W/2, H/2 );
}
};
// Restart Button object
restartBtn = {
w: 100,
h: 50,
x: W/2 - 50,
y: H/2 - 50,
draw: function() {
ctx.strokeStyle = "white";
ctx.font = "18px Arial, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("Tap Center Screen To Play Again!", W/2, H/2 - 25 );
}
};
// Function to paint canvas
function paintCanvas() {
ctx.fillStyle = "black";
ctx.fillRect(0, 0, 310, 440);
}
// Function for creating paddles
function Paddle(pos) {
// Height and width
this.h = 8;
this.w = 55;
// Paddle's position
this.x = W/2 - this.w/2;
this.y = (pos == "top") ? 0 : H - this.h;
}
function draw() {
paintCanvas();
for(var i = 0; i < paddles.length; i++) {
p = paddles[i];
ctx.fillStyle = "white";
ctx.fillRect(p.x, p.y, p.w, p.h);
}
ball.draw();
update();
}
function increaseSpd() {
if(points % 2 == 33) {
if(Math.abs(ball.vx) < 15) {
ball.vx += (ball.vx < 0) ? -1 : 1;
ball.vy += (ball.vy < 0) ? -2 : 2;
}
}
}
function trackPosition(e) {
mouse.x = e.pageX;
mouse.y = e.pageY;
}
function movePaddles() {
if(mouse.x && mouse.y) {
for(var i = 1; i < paddles.length; i++) {
p = paddles[i];
p.x = mouse.x - p.w/2;
}
}
}
function collisions() {
if(collides(ball, p1)) {
collideAction(ball, p1);
}
else if(collides(ball, p2)) {
collideAction(ball, p2);
} else {
// Collide with walls, If the ball hits the top/bottom,
// walls, run gameOver() function
if(ball.y + ball.r > H) {
ball.y = H - ball.r;
gameOver(); //the game is over
} else if(ball.y < 0) {
ball.y = ball.r;
gameOver(); //the game is over
}
if(ball.x + ball.r > W) {
ball.vx = -ball.vx;
ball.x = W - ball.r;
} else if(ball.x -ball.r < 0) {
ball.vx = -ball.vx;
ball.x = ball.r;
}
}
}
function drawDashedLine() {
ctx.beginPath();
ctx.fillStyle = '#eee';
ctx.setLineDash([1,2]);
ctx.moveTo(0,H/2);
ctx.lineTo(320,H/2);
ctx.closePath();
ctx.stroke();
}
function update() {
updateScore();
movePaddles();
drawDashedLine()
ball.x += ball.vx;
ball.y += ball.vy;
p1 = paddles[1];
p2 = paddles[2];
collisions();
flag = 0;
}
function collides(b, p) {
if(b.x + ball.r >= p.x &&
b.x - ball.r <=p.x + p.w) {
if(b.y >= (p.y - p.h) && p.y > 0){
paddleHit = 1;
return true;
} else if(b.y <= p.h && p.y == 0) {
paddleHit = 2;
return true;
} else {
return false;
}
}
}
function collideAction(ball, p) {
ball.vy = -ball.vy;
if(paddleHit == 1) {
ball.y = p.y - p.h;
particlePos.y = ball.y + ball.r;
multiplier = -1;
} else if(paddleHit == 2) {
ball.y = p.h + ball.r;
particlePos.y = ball.y - ball.r;
multiplier = 1;
}
points++;
if(collision) {
if(points > 0) {
collision.pause();
}
collision.currentTime = 0;
collision.play();
}
particlePos.x = ball.x;
flag = 1;
}
// Function for updating score
function updateScore() {
ctx.fillStlye = "green";
ctx.font = "20px Arial, sans-serif";
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillText(points, 20, 20 );
}
// Function to run when the game overs
function gameOver() {
ctx.fillStlye = "white";
ctx.font = "20px Arial, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("Game Over! ("+points+")", W/2, H/2 + 25 );
cancelRequestAnimFrame(init); //stops the animation frame
over = 1;
restartBtn.draw(); //This will allow the user to restart the game
}
// Function for running the whole animation
function animloop() {
init = requestAnimFrame(animloop);
draw();
}
// Function to execute at startup
function startScreen() {
draw();
startBtn.draw();
}
// On button click (Restart and start)
function btnClick(e) {
var mx = e.pageX;
var my = e.pageY;
if(mx >= startBtn.x && mx <= startBtn.x + startBtn.w) {
animloop();
startBtn = {};
}
// If the game is over, and the restart button is clicked
if(over == 1) {
if(mx >= restartBtn.x && mx <= restartBtn.x + restartBtn.w) {
ball.x = 20;
ball.y = 20;
points = 0;
ball.vx = 4;
ball.vy = 8;
animloop();
over = 0;
}
}
}
paddles.push(new Paddle("bottom"));
paddles.push(new Paddle("top"));
startScreen();
</script>
</body>
</html>