Why doesn't the Triangle clear? - javascript

I have a question, why doesn't the triangle clear here?
Here is the image:
Here is the JSFIddle
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Snake Game</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- Basic styling, centering the canvas -->
<style>
canvas {
position: absolute;
top: 20px;
bottom: 0px;
left: 250px;
right: 0px;
}
</style>
</head>
<body>
<canvas id="game" width="500" height="500"></canvas>
<script>
$(document).ready(function() {
var loadcount = 0;
var loadtotal = 0;
var preloaded = false;
var WIDTH = 500;
var HEIGHT = 500;
var keys = {};
var canvas = document.getElementById('game');
var ctx = canvas.getContext('2d');
var images = loadImages(["spaceship.png"]);
var player = {
x: null,
y: null,
width: 40,
height: 40,
speed: 5,
update: function() {
if (keys[39]) {
ctx.clearRect(this.x, this.y, this.width, this.height);
this.x += this.speed;
}
if (keys[37]) {
ctx.clearRect(this.x, this.y, this.width, this.height);
this.x -= this.speed;
}
if (keys[38]) {
ctx.clearRect(this.x, this.y, this.width, this.height);
this.y -= this.speed;
}
if (keys[40]) {
ctx.clearRect(this.x, this.y, this.width, this.height);
this.y += this.speed;
}
//Checks if it is out of Bounds
if (this.x > WIDTH - this.width) {
this.x = WIDTH - this.width;
}
if (this.x < 0) {
this.x = 0;
}
if (this.y > HEIGHT - 15) {
this.y = HEIGHT - 15;
}
if (this.y < 0) {
this.y = 0;
}
},
draw: function() {
ctx.save();
ctx.beginPath();
ctx.strokeStyle = 'blue'
ctx.moveTo(this.x, this.y);
ctx.lineWidth = 16;
ctx.lineTo(this.x + 15, this.y + 25);
ctx.lineTo(this.x - 15, this.y + 25);
ctx.closePath();
ctx.stroke();
ctx.restore();
}
}
function main() {
document.addEventListener("keydown", function(event) {
keys[event.keyCode] = true;
})
document.addEventListener("keyup", function(event) {
delete keys[event.keyCode];
})
init();
var loop = function() {
update();
draw();
window.requestAnimationFrame(loop, canvas);
};
window.requestAnimationFrame(loop, canvas);
}
function init() {
player.x = (WIDTH / 2);
player.y = (HEIGHT / 2) + 150;
}
function draw() {
//Drawing the Square
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(0, HEIGHT);
ctx.lineTo(HEIGHT, WIDTH);
ctx.lineTo(WIDTH, 0)
ctx.lineTo(0, 0)
ctx.stroke();
player.draw();
}
function update() {
player.update();
}
function loadImages(imagefiles) {
// Initialize variables
loadcount = 0;
loadtotal = imagefiles.length;
preloaded = false;
// Load the images
var loadedimages = [];
for (var i = 0; i < imagefiles.length; i++) {
// Create the image object
var image = new Image();
// Add onload event handler
image.onload = function() {
loadcount++;
if (loadcount == loadtotal) {
// Done loading
preloaded = true;
}
};
// Set the source url of the image
image.src = imagefiles[i];
// Save to the image array
loadedimages[i] = image;
}
// Return an array of images
return loadedimages;
}
main();
})
</script>
</body>
</html>

While using clearRect, clear entire canvas
Try this:
$(document).ready(function() {
var loadcount = 0;
var loadtotal = 0;
var preloaded = false;
var WIDTH = 500;
var HEIGHT = 500;
var keys = {};
var canvas = document.getElementById('game');
var ctx = canvas.getContext('2d');
var images = loadImages(["spaceship.png"]);
var player = {
x: null,
y: null,
width: 40,
height: 40,
speed: 5,
update: function() {
if (keys[39]) {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
this.x += this.speed;
}
if (keys[37]) {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
this.x -= this.speed;
}
if (keys[38]) {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
this.y -= this.speed;
}
if (keys[40]) {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
this.y += this.speed;
}
//Checks if it is out of Bounds
if (this.x > WIDTH - this.width) {
this.x = WIDTH - this.width;
}
if (this.x < 0) {
this.x = 0;
}
if (this.y > HEIGHT - 15) {
this.y = HEIGHT - 15;
}
if (this.y < 0) {
this.y = 0;
}
},
draw: function() {
ctx.save();
ctx.beginPath();
ctx.strokeStyle = 'blue'
ctx.moveTo(this.x, this.y);
ctx.lineWidth = 16;
ctx.lineTo(this.x + 15, this.y + 25);
ctx.lineTo(this.x - 15, this.y + 25);
ctx.closePath();
ctx.stroke();
ctx.restore();
}
}
function main() {
document.addEventListener("keydown", function(event) {
keys[event.keyCode] = true;
})
document.addEventListener("keyup", function(event) {
delete keys[event.keyCode];
})
init();
var loop = function() {
update();
draw();
window.requestAnimationFrame(loop, canvas);
};
window.requestAnimationFrame(loop, canvas);
}
function init() {
player.x = (WIDTH / 2);
player.y = (HEIGHT / 2) + 150;
}
function draw() {
//Drawing the Square
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(0, HEIGHT);
ctx.lineTo(HEIGHT, WIDTH);
ctx.lineTo(WIDTH, 0)
ctx.lineTo(0, 0)
ctx.stroke();
player.draw();
}
function update() {
player.update();
}
function loadImages(imagefiles) {
// Initialize variables
loadcount = 0;
loadtotal = imagefiles.length;
preloaded = false;
// Load the images
var loadedimages = [];
for (var i = 0; i < imagefiles.length; i++) {
// Create the image object
var image = new Image();
// Add onload event handler
image.onload = function() {
loadcount++;
if (loadcount == loadtotal) {
// Done loading
preloaded = true;
}
};
// Set the source url of the image
image.src = imagefiles[i];
// Save to the image array
loadedimages[i] = image;
}
// Return an array of images
return loadedimages;
}
main();
});
canvas {
position: absolute;
top: 20px;
bottom: 0px;
left: 250px;
right: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="game" width="500" height="500"></canvas>
Fiddle here

Related

How stay on the floor

Can you help with the code? I'm creating a parkour game and everything went well but I got stuck on it: as the cube will stand on the floor. Here is my js code:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//Налаштування
var width = canvas.width;
var height = canvas.height;
var gameOver = function() {
clearInterval(intervalId);
ctx.font = "60px Caurier";
ctx.textAlign = "cener";
ctx.textBaseline = "middle";
ctxfillText("GAME OVER", width / 2, height / 2);
};
var cicle = function(x, y, radius, fillCircle) {
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2, false);
if (fillCircle) {
ctx.fill();
} else {
ctx.stroke();
}
}; //Людина
//намалювати
function Draw() {
this.x = 10;
this.y = 10;
}
Draw.prototype.draw = function() {
ctx.beginPath();
ctx.moveTo(this.x, this.y);
ctx.lineTo(this.x + 50, this.y);
ctx.lineTo(this.x + 50, this.y + 50);
ctx.lineTo(this.x, this.y + 50);
ctx.lineTo(this.x, this.y);
ctx.fill();
}
Draw.prototype.move = function() {
if (this.x < 0) {
this.x = 0;
} else if (this.x > 1250) {
this.x = 1250;
}
if (this.y < 0) {
this.y = 0;
} else if (this.y > 450) {
this.y = 450;
}
while (this.y < 450) {
this.y++;
}
}
Draw.prototype.setDirection = function(direction) {
if (direction === "left") {
this.x = this.x - 10;
} else if (direction === "right") {
this.x = this.x + 10;
} else if (direction === "up") {
this.y = this.y - 150;
}
}
var person = new Draw;
var keyActions = {
37: "left",
38: "up",
39: "right"
};
$("body").keydown(function(event) {
var direction = keyActions[event.keyCode];
person.setDirection(direction);
});
setInterval(function() {
ctx.clearRect(0, 0, 1300, 500);
person.draw();
person.move();
//карта
var floor = ctx.strokeStyle = "LimeGreen";
ctx.lineWidth = 4;
ctx.strokeRect(0, 312, 1300, 362);
}, 30);
body {
background-color: rgb(44, 235, 225);
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>parcur</title>
</head>
<body>
<canvas id="canvas" width="1300" height="500"></canvas>
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
</body>
</html>
I tried a lot but it didn't work out. For example, I tried this: first the code checks whether the cube and the floor are in the same coordinates, if so it reflects, if not, then no.I want the cube to be able to walk on the floor which is painted green, and not pass through it.

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

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

line rotation in class javascript canvas

I try to create a class with a function which might be use to change the angle of a line already drawn.
With what I write, the line doesn't move. When I press the right or left key, I have this error :
TypeError: this.changeAngle is not a function
Indeed, I don't have "function" keyword in my code ... I don't know what to use instead.
Could you help me ?
Thank you very much.
window.onload = init;
let canvas, ctx;
let mousePos;
let angle = 0;
class Lanceur {
constructor() {
this.changeAngle(this.angle);
}
update(ctx) {
this.drawAiguille(ctx);
}
drawSocleLanceur(ctx) {
ctx.save();
ctx.beginPath();
ctx.lineWidth = 2;
ctx.arc(w/2, h, 20, 0, 2 * Math.PI);
ctx.stroke();
ctx.restore();
}
drawAiguille(ctx) {
ctx.save();
ctx.rotate(this.angle);
ctx.strokeStyle = "rgb(255, 0, 0)";
ctx.lineWidth=3;
ctx.beginPath();
ctx.moveTo(w/2, h-h*0.12);
ctx.lineTo(w/2, h-h*0.035);
ctx.stroke();
ctx.restore();
}
changeAngle(a) {
this.angle = a;
}
getAngle() {
return this.angle;
}
}
function init() {
canvas = document.querySelector("#jeu");
ctx = canvas.getContext("2d");
w = canvas.width;
h = canvas.height;
a = new Lanceur();
requestAnimationFrame(mainloop);
}
function mainloop() {
ctx.clearRect(0, 0, w, h);
a.update(ctx);
requestAnimationFrame(mainloop);
}
document.addEventListener('keypress', function(event){
gereTouches(event);
});
function gereTouches(event) {
if(event.key == "ArrowRight") {
this.changeAngle(this.getAngle - 1);
console.log("ça bouge : " + this.angle);
}else if(event.key == "ArrowLeft") {
this.changeAngle(this.getAngle + 1);
}
}
Main changes:
added this.angle to thr constructor()
using keydown event
the function gereTouches(event) uses a instead of this and a.getAngle() instead of a.getAngle
also 1 for the the angle is way too big (those are radians). I'm using .01 instead.
I hope it helps.
window.onload = init;
let canvas, ctx;
let mousePos;
let angle = 0;
class Lanceur {
constructor() {
this.angle = 0;
this.changeAngle(this.angle);
}
update(ctx) {
this.drawAiguille(ctx);
}
drawSocleLanceur(ctx) {
ctx.save();
ctx.beginPath();
ctx.lineWidth = 2;
ctx.arc(w/2, h, 20, 0, 2 * Math.PI);
ctx.stroke();
ctx.restore();
}
drawAiguille(ctx) {
ctx.save();
ctx.rotate(this.angle);
ctx.strokeStyle = "rgb(255, 0, 0)";
ctx.lineWidth=3;
ctx.beginPath();
ctx.moveTo(w/2, h-h*0.12);
ctx.lineTo(w/2, h-h*0.035);
ctx.stroke();
ctx.restore();
}
changeAngle(a) {
this.angle = a;
}
getAngle() {
return this.angle;
}
}
function init() {
canvas = document.querySelector("#jeu");
ctx = canvas.getContext("2d");
w = canvas.width = 500;
h = canvas.height = 500;
a = new Lanceur();
requestAnimationFrame(mainloop);
}
function mainloop() {
ctx.clearRect(0, 0, w, h);
a.update(ctx);
requestAnimationFrame(mainloop);
}
document.addEventListener('keydown', function(event){
gereTouches(event);
});
function gereTouches(event) {
if(event.key == "ArrowRight") {
a.changeAngle(a.getAngle() - .01);
console.log("ça bouge : " + a.angle);
}else if(event.key == "ArrowLeft") {
a.changeAngle(a.getAngle() + .01);
}
}
canvas{border:1px solid}
<canvas id="jeu"></canvas>

nothing is drawn on page using javascript and canvas

I am trying to develop a game and i am starting to dip my toes into the HTML <canvas> tag and using it with javascript. My program here is my work in progress clone of PONG. I have managed to add the two paddles with no error but as i have added the Ball function it simply refuses to draw anything on the screen and thus i am given a page covered in black.
Could it be because i am using classes?
Here is the code:
// ctx.fillStyle = 'rgba(red, green, blue, alpha)';
// ctx.fillRect(x, y, width, height);
var canvas;
var ctx;
var dx = 5;
var dy = 5;
//Class Definitions
function Game(width, height, colour) {
this.width = width;
this.height = height;
this.colour = colour;
}
function Player(width, height, colour, x, y, up, down) {
this.width = width;
this.height = height;
this.colour = colour;
this.x = x;
this.y = y;
this.up = up;
this.down = down;
this.move = function(ny) {
this.y = this.y + ny;
ctx.fillStyle = this.colour;
ctx.fillRect(this.x, this.y, this.width, this.height);
};
}
function Ball(width, height, colour, x , y, isTouched, isInGoal) {
this.width = width;
this.height = height;
this.colour = colour;
this.x = x;
this.y = y;
this.isTouched = isTouched;
this.isInGoal = isInGoal;
this.move = function() {
clear();
this.x = this.x + 1;
ctx.fillStyle = this.colour;
ctx.fillRect(this.x, this.y, this.width, this.height);
};
}
//Creating new Classes
var gameStage = new Game((window.innerWidth), (window.innerHeight), 'rgb(0,0,0)');
var paddleOne = new Player(10, 150, 'rgb(255,255,255)', (gameStage.width/10), (gameStage.height/2), 38, 40);
var paddleTwo = new Player(10, 150, 'rgb(255,255,255)', (gameStage.width/1.1), (gameStage.height/2), 87, 83);
var ball = new Ball(20, 20, 'rgb(255,255,255)', (gameStage.width/2), (gameStage.height/2), 0, 0);
//Initialisation
function init(){
canvas = document.getElementById('game');
canvas.setAttribute('width', gameStage.width);
canvas.setAttribute('height', gameStage.height);
canvas.setAttribute('tabindex', 0);
if (game.getContext){
ctx = canvas.getContext('2d');
return setInterval(ball.move, 10);
return setInterval(draw, 10);
}
}
//Canvas Functions
function clear(){
ctx.clearRect(0, 0, gameStage.width, gameStage.height);
}
function draw() {
clear();
ctx.fillStyle = gameStage.colour;
ctx.fillRect(0, 0, gameStage.width, gameStage.height);
ctx.fillStyle = paddleOne.colour;
ctx.fillRect(paddleOne.x, paddleOne.y, paddleOne.width, paddleOne.height);
ctx.fillStyle = paddleTwo.colour;
ctx.fillRect(paddleTwo.x, paddleTwo.y, paddleTwo.width, paddleTwo.height);
console.log("PlayerOne Y Coordinate: " + paddleOne.y + "\n");
console.log("PlayerTwo Y Coordinate: " + paddleTwo.y + "\n");
}
//Player Control
function doKeyDown(e) {
if (e.keyCode == paddleOne.up){
paddleOne.move(-5);
} else if (e.keyCode == paddleOne.down) {
paddleOne.move(5);
} else if (e.keyCode == paddleTwo.up) {
paddleTwo.move(-5);
} else if (e.keyCode == paddleTwo.down) {
paddleTwo.move(5);
}
}
//For HTML
function beginStuff(){
init();
window.addEventListener('keydown', doKeyDown, true);
}
* { margin: 0; padding: 0;}
body, html {height: 100%;}
#game {
position: absolute;
width:100%;
height:100%;
background-color: #000000;
}
<!DOCTYPE HTML>
<htmL>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>A game</title>
<script type="text/javascript" src="game.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body onload="beginStuff();" >
<canvas id="game">
Please upgrade your browser to support HTML5. <br/>
</canvas>
</body>
</htmL>
This looks wrong to me:
return setInterval(ball.move, 10);
return setInterval(draw, 10);
Firstly, you've got 2 returns. Secondly, you've lost the binding on the move method:
return setInterval(ball.move.bind(ball), 10);
If that doesn't fix it I suggest stepping through in a debugger, line-by-line, making sure that everything is doing exactly what you expect it to.
With help from #skirtle, i moved the ball.move(); to the draw() function and removed the clear() call from the ball.move() function.

Collision detection between circle and rectangle in Javascript game?

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

Categories

Resources