I have start develop small JavaScript game with canvas.
So i need to display multiple cards in the canvas.
But i seems, after i use gameArea.clear(); method within updateGameArea() function one card isn't display. But without using that gameArea.clear(); method those cards are displaying well. But i need multiple cards.
Here my JavaScript code
var cards = [];
var selectedCards = [];
var select = true;
window.addEventListener('DOMContentLoaded', function () {
startGame();
});
function startGame() {
cards.push(new PlayingCard("blue", 5, 150, 10));
cards.push(new PlayingCard("red", 1, 10, 10));
gameArea.click();
gameArea.start();
}
var gameArea = {
canvas: document.createElement("canvas"),
start: function () {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 100);
},
click: function () {
this.canvas.addEventListener('click', getPosition);
},
clear: function () {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
};
function getPosition(e) {
var top = this.offsetTop;
var left = this.offsetLeft;
var x = e.pageX - left;
var y = e.pageY - top;
cards.forEach(function (card) {
if (y > card.y && y < card.y + card.height && x > card.x && x < card.x + card.width) {
card.selected = select;
if (selectedCards.length < 2) {
selectedCards.push(card);
} else {
selectedCards = [];
selectedCards.push(card);
}
if (selectedCards.length === 2) {
selectedCards.forEach(function (selected_card) {
selected_card.x = 400;
if (selected_card.selected === select) {
console.log(selected_card);
}
});
}
}
});
}
function PlayingCard(color, value, x, y) {
this.color = function () {
if (color === 'red') {
return "#E53935";
} else if (color === 'blue') {
return "#0D47A1";
} else {
throw new Error("No Color Code Found!");
}
};
this.value = value;
this.width = 120;
this.height = 160;
this.x = x;
this.y = y;
this.selected = false;
this.update = function () {
var ctx = gameArea.context;
ctx.fillStyle = this.color();
ctx.shadowBlur = 8;
ctx.shadowColor = 'rgba(0, 0, 0, 0.5)';
ctx.fillRect(this.x, this.y, this.width, this.height);
};
}
function updateGameArea() {
cards.forEach(function (card) {
gameArea.clear();
card.update();
});
}
You are calling gameAera.clear() each time you draw a card. So this is why only the last card is displayed.
function updateGameArea() {
gameArea.clear(); // Move the gameArea.clear(); here
cards.forEach(function (card) {
card.update();
});
}
Related
As of now, all I know to be certain is to set the global variable of 'paused' to be false. Adding an eventlistener and updating my loop function, etc. is where I am uncertain on implementation, otherwise the game is "finished" by all means!
var canvas = document.getElementById('canvas');
canvas.width = 1280;
canvas.height = 700;
var ctx = canvas.getContext('2d');
let obstacles = [];
var cancelMe = '';
let difficulty = 10;
let id;
let dis = 0;
let miles = 0;
let paused = false;
function getScore() {
let highScore = localStorage.getItem('highscore');
console.log('highscore is ', highScore);
document.getElementById('score').innerHTML = 'Highscore: ' + highScore + ' ft.';
}
getScore();
function saveScore(score) {
let highScore;
if (!isNaN(localStorage.getItem('highscore'))) {
highScore = localStorage.getItem('highscore');
} else {
highScore = 0;
}
console.log(highScore);
highScore = Math.max(score, highScore);
localStorage.setItem('highscore', highScore);
}
var img = new Image();
img.src = './images/background.jpg';
img.onload = function() {
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
};
var durianImg = new Image();
durianImg.src = './images/durian.png';
durianImg.onload;
var backgroundImage = {
img: img,
x: 0,
speed: -1.5,
move: function() {
backgroundImage.x += this.speed;
backgroundImage.x %= canvas.width;
sprite.distance += 0.2;
},
draw: function() {
ctx.drawImage(this.img, this.x, 0);
if (this.speed < 0) {
ctx.drawImage(this.img, this.x + canvas.width, 0);
} else {
ctx.drawImage(this.img, this.x - this.img.width, 0);
}
}
};
var timeFalling = 0;
function clamp(num, min, max) {
return num <= min ? min : num >= max ? max : num;
}
var sprite = {
name: 'Mr. Sprite',
x: 2,
y: 528,
distance: 0,
int: null,
moveLeft: function() {
sprite.x -= 30;
sprite.x = clamp(this.x, 0, 1280);
sprite.distance -= 30;
},
moveRight: function() {
sprite.x += 30;
sprite.x = clamp(this.x, 0, 1230);
sprite.distance += 30;
},
moveUp: function() {
if ((sprite.y = 528)) {
sprite.y -= 70;
this.beginFall();
}
},
beginFall: function() {
clearInterval(this.int);
timeFalling = 0;
this.int = setInterval(function() {
timeFalling = timeFalling + 1;
}, 10);
},
draw: function() {
spriteImg = new Image();
spriteImg.src = './images/sprite.png';
ctx.drawImage(spriteImg, sprite.x, sprite.y, 50, 60);
},
fall: function() {
if (this.y < 528) {
this.y += 9.8 * timeFalling / 150;
} else {
clearInterval(this.int);
this.y = 528;
}
}
};
class obstacle {
constructor(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
fall() {
if (this.y < 528) {
this.y++;
}
}
}
document.onkeydown = function(e) {
switch (e.keyCode) {
case 37:
case 65:
sprite.moveLeft();
console.log('left', sprite);
break;
case 38:
case 87:
case 32:
sprite.moveUp();
console.log('right', sprite);
break;
case 39:
case 68:
sprite.moveRight();
console.log('right', sprite);
break;
}
};
function checkCollision(obstacle) {
if (obstacle.y + 60 > sprite.y && obstacle.y < sprite.y + 60) {
if (obstacle.x + 50 < sprite.x + 50 && obstacle.x + 50 > sprite.x) {
console.log('Collision');
gameOver();
} else if (obstacle.x < sprite.x + 41 && obstacle.x > sprite.x) {
console.log('Collision');
gameOver();
}
}
}
function updateCanvas() {
backgroundImage.move();
ctx.clearRect(0, 0, canvas.width, canvas.height);
backgroundImage.draw();
dis++;
if (dis % 20 == 0) {
miles++;
}
ctx.fillStyle = '#606060';
ctx.fillText('Distance Traversed: ' + miles + ' ft.', 540, 40);
sprite.draw();
sprite.fall();
if (dis % 40 == 0) {
obstacles.push(randomObstacle());
}
for (let i = 0; i < obstacles.length; i++) {
obstacles[i].draw();
obstacles[i].fall();
checkCollision(obstacles[i]);
if (obstacles[i].y > 520) obstacles.splice(i, 1);
}
}
function startGame() {
difficulty = Number(document.querySelector('#diffSelect').value);
id = setInterval(updateCanvas, difficulty);
startGameButton.disabled = true;
init();
loop();
}
var startGameButton = document.getElementById('startGameButton');
startGameButton.onclick = startGame;
function restartGame() {
clearInterval(id);
obstacles = [];
var timeFalling = 0;
sprite.x = 2;
sprite.y = 528;
sprite.distance = 0;
sprite.int = null;
dis = 0;
miles = 0;
fallSpeed = 1.0005;
startGameButton.disabled = false;
ctx.fillStyle = 'white';
ctx.font = '18px serif';
ctx.clearRect(0, 0, canvas.width, canvas.height);
backgroundImage.draw();
audio.pause();
location.reload();
}
var retryGameButton = document.getElementById('retryGameButton');
retryGameButton.onlick = restartGame;
ctx.fillStyle = 'white';
ctx.font = '18px serif';
function randomObstacle() {
let x = Math.random() * canvas.width;
let y = 0;
return new Durian(x, y);
}
let fallSpeed = 1.0003;
setInterval(function() {
fallSpeed += 0.0008; // tweak this to change how quickly it increases in difficulty
// console.log(fallSpeed);
}, 8000); // timer at which it gets harder
class Durian {
constructor(x, y) {
this.x = x;
this.y = y;
}
draw() {
ctx.drawImage(durianImg, this.x, this.y, 50, 60);
}
fall() {
if (this.y < 528) this.y = (this.y + 1) ** fallSpeed;
this.x -= 1.5;
}
}
var hotbod = document.querySelector('body');
function doStuff() {
hotbod.className += ' animate';
}
window.onload = function() {
doStuff();
};
function gameOver() {
clearInterval(id);
ctx.fillStyle = '#606060';
ctx.font = '70px Anton';
ctx.fillText('GAME OVER', 430, 300);
console.log('save ', miles);
saveScore(miles);
audio.pause();
new Audio('sounds/game_over.wav').play();
}
function init() {
audio = document.getElementById('audio');
// add listener function to loop on end
audio.addEventListener('ended', loop, false);
// set animation on perpetual loop
setInterval(animate);
}
function loop() {
audio.play();
}
And for my index.html where the buttons are displayed:
<div id="menu">
<div class="custom-select instruct">
<select id="diffSelect">
<option value="6.5">Easy</option>
<option value="5.5">Medium</option>
<option value="4.5">Hard</option>
<option value="3">Extreme</option>
</select>
</div>
<input id="startGameButton" type="button" class="instruct" onclick="startGame()" value="Start" />
<input id="retryGameButton" type="button" class="instruct" onclick="restartGame()" value="Reset" />
<p class="disclaimer">DISCLAIMER: Once you wipe out, hit reset & change to a higher difficulty if you dare, then hit start to play again!</p>
</div>
Try the following
btw any ... represents your code I didn't include to save space
...
let gameRunning = false;
...
document.onkeydown = function(e) {
switch (e.keyCode) {
case 80:
if(gameRunning) {
paused = !paused;
startGameButton.value = paused ? "Un-Pause" : "Pause";
}
break;
...
}
};
...
function startGame() {
if(gameRunning){
paused = !paused;
startGameButton.value = paused ? "Un-Pause" : "Pause";
}
else {
difficulty = Number(document.querySelector('#diffSelect').value);
id = setInterval(updateCanvas, difficulty);
gameRunning = true;
startGameButton.value = "Pause";
init();
loop();
}
}
...
When the component or square touches the bottom of the canvas and I press the up arrow afterwards it collides with the bottom, every jump the component jumps when I press the up arrow it jumps upwards less and less until the component eventually does not jump at all. But the component at the same time moves left and right perfectly still when this problem occurs.
I am controlling the square with the arrow keys and it is the player for this platform game that i am creating and i have no clue how i can change it.
var myGamePiece;
var platformWidth = 500;
var platformX = 0;
var platformY = 250;
function startGame() {
myGameArea.start();
myGamePiece = new component(30, 30, "red", 10, 120);
}
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.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(width, height, color, x, y, type) {
this.type = type;
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.speedX = 0;
this.speedY = 0;
this.gravity = 0.05;
this.gravitySpeed = 0;
this.update = function() {
ctx = myGameArea.context;
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;
if (myGameArea.canvas.height - this.height && myGamePiece.key == 38) {
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;
}
if (myGameArea.key && myGameArea.key == 38) {
myGamePiece.speedY = -5;
} else {
myGamePiece.speedY = 5;
}
if (myGameArea.key && myGameArea.key == 40) {
myGamePiece.speedY = 5;
}
myGamePiece.newPos();
myGamePiece.update();
}
startGame();
Did you forget to reset the gravity speed?
this.hitBottom = function() {
// ...
if (this.y > rockbottom) {
// ...
this.gravitySpeed = 0; // reset?
}
};
var myGamePiece;
var platformWidth = 360;
var platformX = 0;
var platformY = 120;
function startGame() {
myGameArea.start();
myGamePiece = new Component(12, 12, "red", 10, 10);
}
var myGameArea = {
canvas: document.createElement("canvas"),
start: function() {
this.canvas.width = platformWidth;
this.canvas.height = platformY;
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;
});
},
fill: function(color) {
this.context.save();
this.context.fillStyle = color;
this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);
this.context.restore();
},
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.width = width;
this.height = height;
this.x = x;
this.y = y;
this.speedX = 0;
this.speedY = 0;
this.gravity = 0.05;
this.gravitySpeed = 0;
this.update = function() {
ctx = myGameArea.context;
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;
if (myGameArea.canvas.height - this.height && myGamePiece.key == 38) {
this.y = this.speedY;
}
this.gravitySpeed = 0; // reset?
}
};
}
function updateGameArea() {
myGameArea.fill('#DE7');
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.key) {
switch (myGameArea.key) {
case 37: // left arrow
myGamePiece.speedX = -5;
break;
case 38: // up arrow
myGamePiece.speedY = -5;
break;
case 39: // right arrow
myGamePiece.speedX = +5;
break;
case 40: // down arrow
default:
myGamePiece.speedY = +5;
}
}
myGamePiece.newPos();
myGamePiece.update();
}
startGame();
body {
background: #000;
}
Here is another approach using classes, you can clean up the vector math, by using actual vector classes e.g. Victor.js.
const main = () => {
new GravityGame({
width : 360,
height : 180,
refreshRate : 20
}).start();
}
class AbstractGameClient {
constructor(options) {
this.refreshRate = options.refreshRate
this.view = new GameArea({
width : options.width,
height : options.height
})
}
update() {
this.view.update()
}
start() {
let self = this
self.intervalId = setInterval(function() { self.update() }, self.refreshRate)
return self
}
stop() {
if (self.intervalId) {
clearInterval(self.intervalId)
}
}
}
class GravityGame extends AbstractGameClient {
constructor(options) {
super(options)
let myGamePiece = new Component({
width : 12,
height : 12,
color : 'red'
})
this.view.addComponent(myGamePiece)
}
}
class GameArea {
constructor(options) {
let self = this
self.canvas = document.createElement('canvas')
self.width = options.width
self.height = options.height
self.key = null
self.components = []
self.addListeners()
self.render()
}
render() {
let self = this
self.canvas.width = self.width
self.canvas.height = self.height
self.context = self.canvas.getContext('2d')
document.body.insertBefore(self.canvas, document.body.childNodes[0])
}
addComponent(component) {
this.centerComponent(component)
this.components.push(component)
}
addListeners() {
let self = this;
window.addEventListener('keydown', function(e) {
self.key = e.keyCode;
});
window.addEventListener('keyup', function(e) {
self.key = false;
});
}
fill(color) {
this.context.save();
this.context.fillStyle = color;
this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);
this.context.restore();
}
clear() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
update() {
let self = this
let speed = { x : 0, y : 0 }
if (self.key) {
switch (self.key) {
case 37: // left arrow
speed.x = -5;
break;
case 38: // up arrow
speed.y = -5;
break;
case 39: // right arrow
speed.x = +5;
break;
case 40: // down arrow
default:
speed.y = +5;
}
}
self.fill('#DE7')
self.components.forEach(component => {
component.speed.x = speed.x
component.speed.y = speed.y
component.reposition(self.context)
component.redraw(self.context)
})
}
centerComponent(component) {
let xOffset = Math.floor((this.canvas.width / 2) - component.width / 2)
let yOffset = Math.floor((this.canvas.height / 2) - component.height / 2)
component.position = { x : xOffset, y : yOffset }
}
};
class Component {
constructor(options) {
let self = this
self.width = options.width
self.height = options.height
self.position = options.position
self.color = options.color
self.type = options.type
self.speed = { x : 0, y : 0 }
self.gravity = { x : 0, y : 0.05 };
self.acceleration = { x : 0, y : 0 };
}
redraw(context) {
context.fillStyle = this.color;
context.fillRect(this.position.x, this.position.y, this.width, this.height);
}
reposition(context) {
let self = this
// Increase acceleration
self.acceleration.x += self.gravity.x;
self.acceleration.y += self.gravity.y;
// pos + speed + acceleration
self.position.x += self.speed.x + self.acceleration.x;
self.position.y += self.speed.y + self.acceleration.y;
self.checkBounds(context);
}
checkBounds(context) {
let self = this
let rockbottom = context.canvas.height - this.height
if (self.position.y > rockbottom) {
self.position.y = rockbottom
if (context.canvas.height - self.height && self.key == 38) {
self.position.y = self.speed.y
}
self.acceleration = { x : 0, y : 0 } // reset
}
}
}
main();
body {
background: #000;
}
I'm trying to make a browser game with pure javascript. I was using codesandbox.io for writing it at first, but the I decided I was done for the day and needed to check if it works in a browser. Lo and behold, it does not. I genuinely have no idea why it's not working.
All the code is supposed to do, is make a square jump. which it does do, however right when you let go of the up key, the page hangs, it won't even refresh. Doesn't crash the browser though. Anyways, here's my code.
class player {
constructor(gameW, gameH) {
this.gameH = gameH;
this.width = 50;
this.heigth = 50;
this.maxUpV = 5;
this.currV = 0;
this.gravConst = 50;
this.position = {
x: 50,
y: 150
};
}
jumpUp() {
this.currV = -this.maxUpV;
}
fall(falling) {
while (this.position.y < 150) {
this.currV = this.maxUpV;
}
return (falling = false);
}
draw(ctx) {
ctx.fillStyle = "#F00";
ctx.fillRect(this.position.x, this.position.y, this.width, this.heigth);
}
update(deltaTime) {
if (!deltaTime) {
return;
}
this.position.y += this.currV;
if (this.position.y + this.heigth > 200) {
this.position.y = 150;
}
}
}
class input {
constructor(Player) {
this.falling = false;
document.addEventListener("keydown", event => {
if (event.keyCode === 38) {
if (!Player.fall(this.falling)) {
Player.jumpUp();
}
}
});
document.addEventListener("keyup", event => {
if (event.keyCode === 38) {
this.falling = true;
Player.fall(this.falling);
}
});
}
}
const GAME_WIDTH = 800;
const GAME_HEIGHT = 300;
var canvas = document.getElementById("gameScreen");
var ctx = canvas.getContext("2d");
var Player = new player(GAME_WIDTH, GAME_HEIGHT);
ctx.clearRect(0, 0, 800, 300);
ctx.fillRect(0, 200, 800, 200);
ctx.fillRect(400, 100, 50, 1);
Player.draw(ctx);
new input(Player);
var lastTime = 0;
function gameLoop(timeStamp) {
var deltaTime = timeStamp - lastTime;
lastTime = timeStamp;
ctx.clearRect(0, 0, 800, 200);
Player.update(deltaTime);
Player.draw(ctx);
requestAnimationFrame(gameLoop);
}
gameLoop();
Oh and also, when I was writing it in codesandbox.io, the classes were separate files that I imported into the main .js file. That gave me an error in the browser, so I just put everything in one file. I tried both Vivaldi and Firefox, to no avail.
I originally misread the question. Your code is locking up in your fall function. Once you hit the max height you were getting stuck in a loop waiting for the fall but never returning control to anywhere that could generate a fall. I'm having some difficulty understanding your max height validation.
The fall function will always return false.
fall(falling) {
while (this.position.y < 150) {
this.currV = this.maxUpV;
}
return (falling = false);
}
The return value of an assignment is the value assigned, so in this case your return value will always be false
I also had to modify the logic for the end button press
if (!Player.fall(this.falling)) {
Player.jumpUp();
}
The conditional was basically always returning true and could be simplified.
I hope this helps!
class player {
constructor(gameW, gameH) {
this.gameH = gameH;
this.width = 50;
this.height = 50;
this.maxUpV = 5;
this.currV = 0;
this.gravConst = 50;
this.position = {
x: 50,
y: 150
};
}
jumpUp() {
this.currV = -this.maxUpV;
}
fall(falling) {
if (this.position.y <150) {
this.currV = this.maxUpV;
return true
}
return false;
}
draw(ctx) {
ctx.fillStyle = "#F00";
ctx.fillRect(this.position.x, this.position.y, this.width, this.height);
}
update(deltaTime) {
if (!deltaTime) {
return;
}
this.position.y += this.currV;
if (this.position.y + this.height > 200) {
this.position.y = 150;
}
}
}
class input {
constructor(Player) {
this.falling = false;
document.addEventListener("keydown", event => {
if (event.keyCode === 38) {
if (!this.falling) {
Player.jumpUp();
}
}
});
document.addEventListener("keyup", event => {
if (event.keyCode === 38) {
this.falling = true;
this.falling = Player.fall();
}
});
}
}
const GAME_WIDTH = 800;
const GAME_HEIGHT = 300;
var canvas = document.getElementById("gameScreen");
var ctx = canvas.getContext("2d");
var Player = new player(GAME_WIDTH, GAME_HEIGHT);
ctx.clearRect(0, 0, 800, 300);
ctx.fillRect(0, 200, 800, 200);
ctx.fillRect(400, 100, 50, 1);
Player.draw(ctx);
new input(Player);
var lastTime = 0;
function gameLoop(timeStamp) {
var deltaTime = timeStamp - lastTime;
lastTime = timeStamp;
ctx.clearRect(0, 0, 800, 200);
Player.update(deltaTime);
Player.draw(ctx);
requestAnimationFrame(gameLoop);
}
gameLoop();
<canvas id="gameScreen" width=400 height=400></canvas>
I have been trying to make a nodal graph visualizer, but I am having trouble getting the lines to display behind the nodal points. I have already tried to use context.globalCompositeOperation, but to no avail. I have tried to implement rendering it in the order I wanted it to be drawn. Here is the full code for the project:
var canvas = document.querySelector('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var c = canvas.getContext('2d');
var nodes = [];
var has_clicked = false;
var user_has_picked_up_object = false;
var picked_up_id;
class Vector2 {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
document.onmousemove = function(e){
mouse_pos.x = e.pageX;
mouse_pos.y = e.pageY;
}
document.onmousedown = function(e) {
has_clicked = true;
}
document.addEventListener('mouseup', function(e) {
has_clicked = false;
user_has_picked_up_object = false;
})
var mouse_pos = new Vector2(0, 0);
class Connection {
constructor(node1, node2) {
this.node1 = node1;
this.node2 = node2;
this.isDrawn = false;
}
}
function DistSQ(p1, p2) {
return Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2);
}
class Node {
constructor(pos, id) {
this.pos = pos;
this.radius = 10;
this.radius_squared = 100;
this.connections = [];
this.id = id;
}
AddConnection(conn) {
this.connections.push(conn);
}
RemoveConnection(conn) {
return this.connections.pop(conn);
}
UpdatePosition() {
if(DistSQ(this.pos, mouse_pos) < this.radius_squared && has_clicked) {
if(user_has_picked_up_object && picked_up_id == this.id) {
this.pos = mouse_pos;
}
else {
user_has_picked_up_object = true;
picked_up_id = this.id;
}
}
else {
this.pos = new Vector2(this.pos.x, this.pos.y);
}
}
}
function DrawLines(conns) {
c.beginPath();
c.lineWidth = 1;
c.strokeStyle = 'black';
conns.forEach(element => {
c.moveTo(element.node1.pos.x, element.node1.pos.y);
c.lineTo(element.node2.pos.x, element.node2.pos.y);
});
c.stroke();
}
function DrawCircles(nds) {
c.beginPath();
c.lineWidth = 1;
nds.forEach(element => {
c.strokeStyle = 'black';
c.moveTo(element.pos.x+element.radius, element.pos.y);
c.arc(element.pos.x, element.pos.y, element.radius, 0, 2 * Math.PI, false);
});
c.stroke();
}
function Update() {
requestAnimationFrame(Update);
c.clearRect(0, 0, window.innerWidth, window.innerHeight);
for(var i = 0; i < nodes.length; i++) {
nodes[i].UpdatePosition();
DrawLines(nodes[i].connections);
}
DrawCircles(nodes);
}
function Initialize() {
for(var y = 0, i = 0; y < 5; y++) {
for(var x = 0; x < 5; x++, i++) {
nodes.push(new Node(new Vector2(x*20+20, y*20+20), i));
}
}
for(var i = 1; i < nodes.length; i++) {
nodes[i].AddConnection(new Connection(nodes[i], nodes[i-1]));
}
Update();
}
Initialize();
Thanks to #enxaneta, for giving me the solution to this problem, so I copied his answer here:
The lines are behind the circles- In your function DrawCircles add c.fillStyle = "white";c.fill() – enxaneta
I've looked at several threads, and I cannot for the life of me get my image to properly rotate to the position of my mouse cursor. I can get the image to translate to the position of my mouse cursor, I know I'm close, I just don't know exactly where I am off at... below is what I have so far. The image needs to rotate at its current position and face the mouse cursor if that makes more sense... PS I am new to coding!
var myGamePiece;
function startGame() {
myGamePiece = new component(50, 50, "Assets/PNG/Soldier 1/soldier1_gun.png", 10, 120, "image"); //size, source, starting location
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateGameArea, 1);
},
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, type) {
this.type = type;
if (type == "image") {
this.image = new Image();
this.image.src = color;
}
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
this.width = window.innerWidth/20; //update width based on window size
this.height = window.innerHeight/20; //update height based on window size
ctx = myGameArea.context;
if (type == "image") {
document.onmousemove = function(e) {
dx = e.pageX;
dy = e.pageY;
console.log(e.pageX, e.pageY);
theta = Math.atan2(dy - this.y, dx - this.x);
theta = theta * (180/Math.PI);
}
//console.log(theta);
ctx.save();
ctx.translate(this.image.width/2,this.image.height/2); // updates the image origin upon rotating
ctx.rotate(theta); // rotates the image to specified position
ctx.drawImage(this.image,
this.x,
this.y,
this.width, this.height);
ctx.restore();
} else {
console.log("failed");
}
}
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
}
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.newPos();
myGamePiece.update();
}
function moveup() {
myGamePiece.speedY = -1;
}
function movedown() {
myGamePiece.speedY = 1;
}
function moveleft() {
myGamePiece.speedX = -1;
}
function moveright() {
myGamePiece.speedX = 1;
}
function clearmove() {
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
}
var keys;
setInterval(mainLoop, 50);
function mainLoop(){
document.addEventListener("keydown", function (e) {
keys = (keys || []);
keys[e.keyCode]=true;
if (keys[37]){ // left
moveleft();
}
if (keys[38]){ // up
moveup();
}
if (keys[39]){ // right
moveright();
}
if (keys[40]){ // down
movedown();
}
} , false);
document.addEventListener("keyup", function (e) {
keys[e.keyCode]=false;
stop();
clearmove();
if (keys[37]){ // left
moveleft();
}
if (keys[38]){ // up
moveup();
}
if (keys[39]){ // right
moveright();
}
if (keys[40]){ // down
movedown();
}
}, false);
}