js - problems with array variable scope - javascript

In line 164, I'm trying to access the array defined earlier. I get the error:
Uncaught TypeError: Cannot read property '3' of undefined
http://pastebin.com/TtruZd76
I guess it's to do with variable scope. Please advise how I can access it there.
Code:
window.onload = function() {
// A cross-browser requestAnimationFrame
// See https://hacks.mozilla.org/2011/08/animating-with-javascript-from-setinterval-to-requestanimationframe/
var requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback){
window.setTimeout(callback, 1000 / 60);
};
})();
// Create the canvas
var mainContainer = document.querySelector('main');
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 600;
canvas.height = 400;
mainContainer.appendChild(canvas);
// Map 30 x 20 (each square is 20x20)
var mapArray = [
[1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0]
];
// The player's state
var player = {
x: 0,
y: 0,
sizeX: 20,
sizeY: 20,
step: 20
};
var rightPressed = false;
var leftPressed = false;
var upPressed = false;
var downPressed = false;
// Let's play this game!
reset();
var then = Date.now();
var running = true;
main();
// Functions ---
// Drawing Tiles
function tiledMap() {
var cw = canvas.width;
var ch = canvas.height;
var tw = 20;
var th = 20;
var spritesheet = new Image();
spritesheet.onload = function () {
canvas.width = tw * mapArray[0].length;
canvas.height = th * mapArray.length;
popMap();
}
spritesheet.src = 'images/bwtiles.png';
function popMap() {
for (i = 0; i < mapArray.length; i++) {
for (j = 0; j < mapArray[i].length; j++) {
var tile = mapArray[i][j];
ctx.drawImage(spritesheet,
tile * 20, 0, tw, th,
j * 20, i * 20, tw, th
);
}
}
}
}
function mapDetection() {
console.log(player.x, player.y);
}
// Reset game to original state
function reset() {
player.x = 0;
player.y = 0;
}
// Update game objects.
// We'll use GameInput to detect which keys are down.
// If you look at the bottom of index.html, we load GameInput
// from js/input.js right before app.js
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if(e.keyCode == 39) {
rightPressed = false;
}
else if(e.keyCode == 37) {
leftPressed = false;
}
else if(e.keyCode == 38) {
upPressed = false;
}
else if(e.keyCode == 40) {
downPressed = false;
}
}
function keyUpHandler(e) {
if(e.keyCode == 39) {
rightPressed = true;
}
else if(e.keyCode == 37) {
leftPressed = true;
}
else if(e.keyCode == 38) {
upPressed = true;
}
else if(e.keyCode == 40) {
downPressed = true;
}
}
function detectWall() {
// Detect walls from the array
}
function update() {
if (rightPressed && player.x < canvas.width - player.sizeX) {
player.x += player.step;
rightPressed = false;
console.log(mapArray[player.x][3]);
} else if (leftPressed && player.x > 0) {
player.x -= player.step;
leftPressed = false;
console.log(player.x);
} else if (downPressed && player.y < canvas.height - player.sizeY) {
player.y += player.step;
downPressed = false;
} else if (upPressed && player.y > 0) {
player.y -= player.step;
upPressed = false;
} else {
rightPressed = false;
leftPressed = false;
downPressed = false;
upPressed = false;
}
}
// Draw everything
function render() {
// draw the map
tiledMap();
ctx.fillStyle = 'blue';
ctx.fillRect(player.x, player.y, player.sizeX, player.sizeY);
}
// The main game loop
function main() {
if (!running) {
return;
}
update();
render();
requestAnimFrame(main);
}
};

In your code you have this:
player.x += player.step;
console.log(mapArray[player.x][3]);
If you look at player.step you will see that it is 20. Also note that mapArray contains 20 items. So as soon as player.x in incremented by 20 (the step), you are trying to access an array item outside the range that mapArray has in store.

Related

How to get program to correctly detect where mouse is in relation to the center point of a circle

I'm creating a small demo/game in which the player moves around and interacts with objects by clicking them.
let cnt = 0;
var canvas = document.querySelector("canvas");
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvas.style.background = "#91c1ff";
const player = {
x: 1,
y: 2
};
const xy = (x, y) => ({
x,
y
});
const dist = 25;
var speed = 5;
//grabs images for organelles
var ribosome = document.getElementById("ribosome");
var mito = document.getElementById("mito");
document.addEventListener('keydown', keyDownHandler, false);
document.addEventListener('keyup', keyUpHandler, false);
var rightPressed = false;
var leftPressed = false;
var upPressed = false;
var downPressed = false;
function keyDownHandler(event) {
if (event.keyCode == 68) {
rightPressed = true;
}
else if (event.keyCode == 65) {
leftPressed = true;
}
if (event.keyCode == 83) {
downPressed = true;
}
else if (event.keyCode == 87) {
upPressed = true;
}
if (event.keyCode == 39) {
rightPressed = true;
}
else if (event.keyCode == 37) {
leftPressed = true;
}
if (event.keyCode == 40) {
downPressed = true;
}
else if (event.keyCode == 38) {
upPressed = true;
}
}
function keyUpHandler(event) {
if (event.keyCode == 68) {
rightPressed = false;
}
else if (event.keyCode == 65) {
leftPressed = false;
}
if (event.keyCode == 83) {
downPressed = false;
}
else if (event.keyCode == 87) {
upPressed = false;
}
if (event.keyCode == 39) {
rightPressed = false;
}
else if (event.keyCode == 37) {
leftPressed = false;
}
if (event.keyCode == 40) {
downPressed = false;
}
else if (event.keyCode == 38) {
upPressed = false;
}
}
function draw() {
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, canvas.width, canvas.height);
const camX = -player.x + canvas.width / 2;
const camY = -player.y + canvas.height / 2;
ctx.translate(camX, camY);
if (rightPressed) {
player.x += speed;
}
else if (leftPressed) {
player.x -= speed;
}
if (downPressed) {
player.y += speed;
}
else if (upPressed) {
player.y -= speed;
}
class Circle {
constructor(xpoint, ypoint, radius, color) {
this.xpoint = xpoint;
this.ypoint = ypoint;
this.radius = radius;
this.color = color;
}
drawer(ctx){
//ctx.drawImage(ribosome, this.xpoint, this.ypoint, 300, 300);
//ctx.drawImage(mito, this.xpoint, this.ypoint, 300, 300);
ctx.beginPath();
ctx.arc(this.xpoint, this.ypoint, this.radius, 0, Math.PI * 2, false);
ctx.fillStyle = this.color;
ctx.fill();
ctx.stroke();
ctx.closePath();
}
clickCircle(xmouse, ymouse) {
const distance =
Math.sqrt(
((xmouse - this.xpoint ) * ( xmouse - this.xpoint))
+
((ymouse - this.ypoint) * (ymouse - this.ypoint))
);
console.log(distance);
}
}
let circle = new Circle(200, 200, 100, "red");
circle.drawer(ctx);
canvas.addEventListener('click', (event) => {
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
circle.clickCircle(x, y);
});
ctx.beginPath();
ctx.arc(player.x, player.y, 10, 0, Math.PI * 2);
ctx.stroke();
requestAnimationFrame(draw)
}
draw();
let cnt = 0;
var canvas = document.querySelector("canvas");
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvas.style.background = "#91c1ff";
const player = {
x: 1,
y: 2
};
const xy = (x, y) => ({
x,
y
});
const dist = 25;
var speed = 5;
//grabs images for organelles
var ribosome = document.getElementById("ribosome");
var mito = document.getElementById("mito");
document.addEventListener('keydown', keyDownHandler, false);
document.addEventListener('keyup', keyUpHandler, false);
var rightPressed = false;
var leftPressed = false;
var upPressed = false;
var downPressed = false;
function keyDownHandler(event) {
if (event.keyCode == 68) {
rightPressed = true;
}
else if (event.keyCode == 65) {
leftPressed = true;
}
if (event.keyCode == 83) {
downPressed = true;
}
else if (event.keyCode == 87) {
upPressed = true;
}
if (event.keyCode == 39) {
rightPressed = true;
}
else if (event.keyCode == 37) {
leftPressed = true;
}
if (event.keyCode == 40) {
downPressed = true;
}
else if (event.keyCode == 38) {
upPressed = true;
}
}
function keyUpHandler(event) {
if (event.keyCode == 68) {
rightPressed = false;
}
else if (event.keyCode == 65) {
leftPressed = false;
}
if (event.keyCode == 83) {
downPressed = false;
}
else if (event.keyCode == 87) {
upPressed = false;
}
if (event.keyCode == 39) {
rightPressed = false;
}
else if (event.keyCode == 37) {
leftPressed = false;
}
if (event.keyCode == 40) {
downPressed = false;
}
else if (event.keyCode == 38) {
upPressed = false;
}
}
function draw() {
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, canvas.width, canvas.height);
const camX = -player.x + canvas.width / 2;
const camY = -player.y + canvas.height / 2;
ctx.translate(camX, camY);
if (rightPressed) {
player.x += speed;
}
else if (leftPressed) {
player.x -= speed;
}
if (downPressed) {
player.y += speed;
}
else if (upPressed) {
player.y -= speed;
}
class Circle {
constructor(xpoint, ypoint, radius, color) {
this.xpoint = xpoint;
this.ypoint = ypoint;
this.radius = radius;
this.color = color;
}
drawer(ctx){
//ctx.drawImage(ribosome, this.xpoint, this.ypoint, 300, 300);
//ctx.drawImage(mito, this.xpoint, this.ypoint, 300, 300);
ctx.beginPath();
ctx.arc(this.xpoint, this.ypoint, this.radius, 0, Math.PI * 2, false);
ctx.fillStyle = this.color;
ctx.fill();
ctx.stroke();
ctx.closePath();
}
clickCircle(xmouse, ymouse) {
const distance =
Math.sqrt(
((xmouse - this.xpoint ) * ( xmouse - this.xpoint))
+
((ymouse - this.ypoint) * (ymouse - this.ypoint))
);
console.log(distance);
}
}
let circle = new Circle(200, 200, 100, "red");
circle.drawer(ctx);
canvas.addEventListener('click', (event) => {
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
circle.clickCircle(x, y);
});
ctx.beginPath();
ctx.arc(player.x, player.y, 10, 0, Math.PI * 2);
ctx.stroke();
requestAnimationFrame(draw)
}
draw();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Cellbot</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<canvas id="canvas" width="100" height="100" style="border:1px solid #000000;"></canvas>
<img src="images/ribosome.png" id="ribosome">
<img src="images/mitochondrion.png" id="mito">
</head>
<body>
<script src="script.js"></script>
</body>
</html>
I want to use circles as the sort of "hitboxes" for the objects. However, when I tried to do this and test it with a console log using this tutorial it detects the mouse as being about 800-1000 pixels from where it's supposed to be depending on the window size.
(It also registers a single click hundreds of times but that's another issue)

How to add collision between the player and the image?

I'm trying to make a program where the user moves with a circle using the keyboard to collect coins. What I tried so far is using an if statement to see if they collide and if they do, the user gets 1 coin and the image disappears. When I try this method, the code runs normally, but the collision doesn't happen.
/* Credit: https://openprocessing.org/sketch/525131
*/
var left, right, up, down;
var coin = [];
var player, posX, posY, radius, speed, colour, gameScreen, coins;
function setup() {
createCanvas(400, 400);
left = right = up = down = false;
gameScreen = "game";
coins = 0;
for (var i = 0; i < 10; i++) {
coin[i] = new Coin(random(width), random(height), 20, 20);
}
player = new Player();
}
function game() {
background(0);
if (left == true) {
player.moveLeft();
}
if (right == true) {
player.moveRight();
}
if (up == true) {
player.moveUp();
}
if (down == true) {
player.moveDown();
}
for (var i = 0; i < 10; i++) {
coin[i].display();
}
player.display();
//player.collision();
fill(255);
textSize(20);
text("Coins: " + coins, 10, 30);
}
function draw() {
game();
}
function keyPressed() {
// if (keyPressed) { For Processing add this line
if (keyCode == LEFT_ARROW || key == 'a') {
left = true;
}
if (keyCode == RIGHT_ARROW || key == 'd') {
right = true;
}
if (keyCode == UP_ARROW || key == 'w') {
up = true;
}
if (keyCode == DOWN_ARROW || key == 's') {
down = true;
}
// }
}
function keyReleased() {
if (keyCode == LEFT_ARROW || key == 'a') {
left = false;
}
if (keyCode == RIGHT_ARROW || key == 'd') {
right = false;
}
if (keyCode == UP_ARROW || key == 'w') {
up = false;
}
if (keyCode == DOWN_ARROW || key == 's') {
down = false;
}
}
function Coin(coinX, coinY, coinR) {
this.img = loadImage("https://www.paulwheeler.us/files/Coin120.png");
this.coinX = coinX;
this.coinY = coinY;
this.coinR = coinR;
this.display = function() {
image(this.img, this.coinX, this.coinY, this.coinR, this.coinR);
}
}
function Player() {
this.posX = width / 2;
this.posY = height / 2;
this.radius = 10;
this.speed = 4;
this.colour = "blue";
this.display = function() {
fill(this.colour);
ellipse(this.posX, this.posY, this.radius * 2, this.radius * 2);
}
this.moveLeft = function() {
// posX = posX - speed;
this.posX = constrain(this.posX - this.speed, this.radius, width - this.radius);
}
this.moveRight = function() {
// posX = posX + speed;
this.posX = constrain(this.posX + this.speed, this.radius, width - this.radius);
}
this.moveUp = function() {
// posY = posY-speed;
this.posY = constrain(this.posY - this.speed, this.radius, height - this.radius);
}
this.moveDown = function() {
// posY = posY+speed;
this.posY = constrain(this.posY + this.speed, this.radius, height - this.radius);
}
/*this.collision = function(){
if (this.posX > this.coinX && this.posX < this.coinX + this.coinR && this.posY > this.coinY && this.posY < this.coinY + this.coinR){
coins+=1;
//Coin disappears
}
}
*/
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
You can use dist() in p5 to determine the distance between the center of the two circles and then see if it smaller than the two radi combined. Once you have that you can execute whatever code is needed.
for (let i = 0; i < coin.length; i++) {
if (
dist(player.posX, player.posY, coin[i].coinX, coin[i].coinY) <
player.radius + coin[i].coinR
) {
coin.splice(i, 1);
coins++;
i--;
}
}
Snippet
/* Credit: https://openprocessing.org/sketch/525131
*/
var left, right, up, down;
var coin = [];
var player, posX, posY, radius, speed, colour, gameScreen, coins;
function setup() {
createCanvas(400, 400);
left = right = up = down = false;
gameScreen = "game";
coins = 0;
for (var i = 0; i < 10; i++) {
coin[i] = new Coin(random(400), random(400), 20);
}
player = new Player();
}
function game() {
background(0);
if (left == true) {
player.moveLeft();
}
if (right == true) {
player.moveRight();
}
if (up == true) {
player.moveUp();
}
if (down == true) {
player.moveDown();
}
//change to coin.length to prevent error
for (var i = 0; i < coin.length; i++) {
coin[i].display();
}
player.display();
//player.collision();
fill(255);
textSize(20);
text("Coins: " + coins, 10, 30);
for (let i = 0; i < coin.length; i++) {
if (
dist(player.posX, player.posY, coin[i].coinX, coin[i].coinY) <
player.radius + coin[i].coinR
) {
coin.splice(i, 1);
coins++;
i--;
}
}
}
function draw() {
game();
}
function keyPressed() {
// if (keyPressed) { For Processing add this line
if (keyCode == LEFT_ARROW || key == "a") {
left = true;
}
if (keyCode == RIGHT_ARROW || key == "d") {
right = true;
}
if (keyCode == UP_ARROW || key == "w") {
up = true;
}
if (keyCode == DOWN_ARROW || key == "s") {
down = true;
}
// }
}
function keyReleased() {
if (keyCode == LEFT_ARROW || key == "a") {
left = false;
}
if (keyCode == RIGHT_ARROW || key == "d") {
right = false;
}
if (keyCode == UP_ARROW || key == "w") {
up = false;
}
if (keyCode == DOWN_ARROW || key == "s") {
down = false;
}
}
function Coin(coinX, coinY, coinR) {
/*this.img = loadImage(
"https://www.searchpng.com/wp-content/uploads/2019/04/Game-Coins-PNG-jpeg-715x715.png"
);*/
this.coinX = coinX;
this.coinY = coinY;
this.coinR = coinR;
this.colour = "yellow";
this.display = function () {
fill(this.colour);
ellipse(this.coinX, this.coinY, this.coinR * 2, this.coinR * 2);
};
}
function Player() {
this.posX = width / 2;
this.posY = height / 2;
this.radius = 10;
this.speed = 4;
this.colour = "blue";
this.display = function () {
fill(this.colour);
ellipse(this.posX, this.posY, this.radius * 2, this.radius * 2);
};
this.moveLeft = function () {
// posX = posX - speed;
this.posX = constrain(
this.posX - this.speed,
this.radius,
width - this.radius
);
};
this.moveRight = function () {
// posX = posX + speed;
this.posX = constrain(
this.posX + this.speed,
this.radius,
width - this.radius
);
};
this.moveUp = function () {
// posY = posY-speed;
this.posY = constrain(
this.posY - this.speed,
this.radius,
height - this.radius
);
};
this.moveDown = function () {
// posY = posY+speed;
this.posY = constrain(
this.posY + this.speed,
this.radius,
height - this.radius
);
};
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js" integrity="sha512-N4kV7GkNv7QR7RX9YF/olywyIgIwNvfEe2nZtfyj73HdjCUkAfOBDbcuJ/cTaN04JKRnw1YG1wnUyNKMsNgg3g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
Your collision function was trying to access this.coinX, this.coinY, and this.coinR but it was defined on Player which doesn't have any of those properties. You need to use a loop to check each coin for collision:
this.collision = function() {
for (let ix = 0; ix < coin.length; ix++) {
const currentCoin = coin[ix];
if (this.posX > currentCoin.coinX &&
this.posX < currentCoin.coinX + currentCoin.coinR &&
this.posY > currentCoin.coinY &&
this.posY < currentCoin.coinY + currentCoin.coinR) {
coins += 1;
// Coin disappears:
// delete the current coin from the array
coin.splice(ix, 1);
// Since the coin that was at ix + 1 is now at position ix in
// the coin array, we need to set ix back by one.
ix--;
}
}
}
/* Credit: https://openprocessing.org/sketch/525131
*/
var left, right, up, down;
var coin = [];
var player, posX, posY, radius, speed, colour, gameScreen, coins;
function setup() {
createCanvas(400, 400);
left = right = up = down = false;
gameScreen = "game";
coins = 0;
for (var i = 0; i < 10; i++) {
coin[i] = new Coin(random(width), random(height), 20, 20);
}
player = new Player();
}
function game() {
background(0);
if (left == true) {
player.moveLeft();
}
if (right == true) {
player.moveRight();
}
if (up == true) {
player.moveUp();
}
if (down == true) {
player.moveDown();
}
for (var i = 0; i < coin.length; i++) {
coin[i].display();
}
player.display();
player.collision();
fill(255);
textSize(20);
text("Coins: " + coins, 10, 30);
}
function draw() {
game();
}
function keyPressed() {
// if (keyPressed) { For Processing add this line
if (keyCode == LEFT_ARROW || key == 'a') {
left = true;
}
if (keyCode == RIGHT_ARROW || key == 'd') {
right = true;
}
if (keyCode == UP_ARROW || key == 'w') {
up = true;
}
if (keyCode == DOWN_ARROW || key == 's') {
down = true;
}
// }
}
function keyReleased() {
if (keyCode == LEFT_ARROW || key == 'a') {
left = false;
}
if (keyCode == RIGHT_ARROW || key == 'd') {
right = false;
}
if (keyCode == UP_ARROW || key == 'w') {
up = false;
}
if (keyCode == DOWN_ARROW || key == 's') {
down = false;
}
}
function Coin(coinX, coinY, coinR) {
this.img = loadImage("https://www.paulwheeler.us/files/Coin120.png");
this.coinX = coinX;
this.coinY = coinY;
this.coinR = coinR;
this.display = function() {
image(this.img, this.coinX, this.coinY, this.coinR, this.coinR);
}
}
function Player() {
this.posX = width / 2;
this.posY = height / 2;
this.radius = 10;
this.speed = 4;
this.colour = "blue";
this.display = function() {
fill(this.colour);
ellipse(this.posX, this.posY, this.radius * 2, this.radius * 2);
}
this.moveLeft = function() {
// posX = posX - speed;
this.posX = constrain(this.posX - this.speed, this.radius, width - this.radius);
}
this.moveRight = function() {
// posX = posX + speed;
this.posX = constrain(this.posX + this.speed, this.radius, width - this.radius);
}
this.moveUp = function() {
// posY = posY-speed;
this.posY = constrain(this.posY - this.speed, this.radius, height - this.radius);
}
this.moveDown = function() {
// posY = posY+speed;
this.posY = constrain(this.posY + this.speed, this.radius, height - this.radius);
}
this.collision = function() {
for (let ix = 0; ix < coin.length; ix++) {
const currentCoin = coin[ix];
if (this.posX > currentCoin.coinX &&
this.posX < currentCoin.coinX + currentCoin.coinR &&
this.posY > currentCoin.coinY &&
this.posY < currentCoin.coinY + currentCoin.coinR) {
coins += 1;
// Coin disappears:
// delete the current coin from the array
coin.splice(ix, 1);
// Since the coin that was at ix + 1 is now at position ix in
// the coin array, we need to set ix back by one.
ix--;
}
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>

I am trying to move my character with the arrow keys but it doesn't move

I want to make my character move using the arrow keys, but it is not working and I have no idea why.
This is for an offline shooter game I'm trying to make. I have tried not using objects but this will soon become multiplayer so I don't want to make new files constantly.
Here is my code:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var img = new Image();
var x = 0;
var y = 0;
var Keys = {
up: false,
down: false,
left: false,
right: false
};
img.src = "images/char1.png";
let player = function player(x, y) {
this.x = x;
this.y = y;
this.speed = 5;
this.health = 100;
};
window.onkeydown = function(e) {
var kc = e.keyCode;
e.preventDefault();
if (kc === 37) {
Keys.left = true;
} else if (kc === 38) {
Keys.up = true;
} else if (kc === 39) {
Keys.right = true;
} else if (kc === 40) {
Keys.down = true;
}
};
window.onkeyup = function(e) {
var kc = e.keyCode;
e.preventDefault();
if (kc === 37) {
Keys.left = false;
} else if (kc === 38) {
Keys.up = false;
} else if (kc === 39) {
Keys.right = false;
} else if (kc === 40) {
Keys.down = false;
}
};
function move() {
if (Keys.left) {
x -= player.speed;
}else if (Keys.right) {
x += player.speed;
}else if (Keys.up) {
y -= player.speed;
}else if (Keys.down) {
y += player.speed;
}
}
function renderObject() {
ctx.drawImage(img, 0, 0, 32, 48, 0, 0, 32, 48);
}
function draw() {
renderObject();
move();
}
setInterval(draw, 10);
I expect the character to move when I press the arrow keys, but it doesn't move at all.
You have a few issues:
You need to create a player object. At the moment your player function is simply just a "stencil" for your player. Instead, you need to create an instance of this object.
var player = new Player(x, y);
You need to clear your canvas after each redraw, if you don't you will get a trail of images of your character:
ctx.clearRect(0, 0, canvas.width, canvas.height);
Draw your player image at the location of the player, not at 0, 0 each time:
ctx.drawImage(img, x, y, 32, 48);
See working example below:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var img = new Image();
var x = 0;
var y = 0;
var player = new Player(x, y);
var Keys = {
up: false,
down: false,
left: false,
right: false
};
img.src = "https://www.pinclipart.com/picdir/middle/366-3665375_deadpool-2d-video-game-characters-clipart.png";
function Player(x, y) {
this.x = x;
this.y = y;
this.speed = 5;
this.health = 100;
};
window.onkeydown = function(e) {
var kc = e.keyCode;
if (kc === 37) {
Keys.left = true;
} else if (kc === 38) {
Keys.up = true;
} else if (kc === 39) {
Keys.right = true;
} else if (kc === 40) {
Keys.down = true;
}
};
window.onkeyup = function(e) {
var kc = e.keyCode;
if (kc === 37) {
Keys.left = false;
} else if (kc === 38) {
Keys.up = false;
} else if (kc === 39) {
Keys.right = false;
} else if (kc === 40) {
Keys.down = false;
}
};
function move() {
if (Keys.left) {
x -= player.speed;
} else if (Keys.right) {
x += player.speed;
} else if (Keys.up) {
y -= player.speed;
} else if (Keys.down) {
y += player.speed;
}
}
function renderObject() {
ctx.drawImage(img, x, y, 32, 48);
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
renderObject();
move();
}
setInterval(draw, 10);
<canvas height="120" width="400" id="canvas" style="border: 1px solid black;"></canvas>

object moving on own in canvas

Sorry the code is so long. When the hero image is at most 32 pixels away from the mine or monster image, it should be transported back to the spawn point, which is 5 pixels on the x-axis, and 5 on the y axis. The hero image is being transported correctly, the alert is just not working. Thanks in advance for any ideas or suggestions.
<html>
<style>
</style>
<body background="background.jpg">
<canvas id="canvas" width="1300" height="630"></canvas>
<script>
var canvas=document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var H=canvas.height;
var W=canvas.width;
var x=10;
var y=15;
var rightPressed=false;
var leftPressed=false;
var upPressed=false;
var downPressed=false;
var heroX=20;
var monsterX=200;
var monsterY=200;
var heroY=20;
var dx= .68;
var dy= .76;
var score=0;
var monstersCaught=0;
var ballPX = 32 + (Math.random() * (canvas.width - 64));
var ballPY = 32 + (Math.random() * (canvas.height - 64));
var h=178;
var i=333;
var mineX=778;
var mineY=178;
Window.onload=dank();
function dank(){
alert("How to play: move your hero using the arrow keys, and collect colored balls for powerups and points!Get the highest score you can without touching a monster, which makes you start over!Collect the colored balls for more and better special powerups.");
}
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function draw(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
var heroImage=new Image();
heroImage.onload=function(){
ctx.drawImage(heroImage , heroX, heroY);
}
heroImage.src="hero.jpg";
dope();
checkMonster();
drawMines();
checkDeath();
}
function keyDownHandler(e) {
if(e.keyCode == 39) {
rightPressed = true;
}
else if(e.keyCode == 37) {
leftPressed = true;
}
else if(e.keyCode == 40) {
downPressed = true;
}
else if(e.keyCode == 38) {
upPressed = true;
}
}
function keyUpHandler(e) {
if(e.keyCode == 39) {
rightPressed = false;
}
else if(e.keyCode == 37) {
leftPressed = false;
}
else if(e.keyCode == 40) {
downPressed = false;
}
else if(e.keyCode == 38) {
upPressed = false;
}
}
function dope(){
if(rightPressed) {
heroX += 7;
}
else if(leftPressed) {
heroX -= 7;
}
else if(upPressed){
heroY -= 7;
}
else if(downPressed){
heroY +=7;
}
}
function checkMonster(){
var monsterImage=new Image();
monsterImage.onload=function(){
ctx.drawImage(monsterImage, monsterX, monsterY)
}
monsterImage.src="monster.jpg";
monsterX += dx;
monsterY += dy;
if(monsterX>canvas.width || monsterX<0){
monsterX = -dx;
}
else if(monsterY>canvas.height || monsterY<0){
monsterY = -dy;
}
if (
heroX <= (monsterX + 32)
&& monsterX <= (heroX + 32)
&& heroY <= (monsterY + 32)
&& monsterY <= (heroY + 32)
) {
the alert that isn't working
alert("DEATH");
heroY=5;
heroX=5;
monsterX=100;
monsterY=100;
upPressed=false;
downPressed=false;
leftPressed=false;
rightPressed=false;
}
}
function drawMines(){
var rsz_mineImage=new Image();
rsz_mineImage.onload=function(){
ctx.drawImage(rsz_mineImage , mineX, mineY);
}
rsz_mineImage.src="rsz_mineimg.jpg";
if (
heroX <= (mineX + 32)
&& mineX <= (heroX + 32)
&& heroY <= (mineY + 32)
&& mineY <= (heroY + 32)
){
rightPressed=false;
leftPressed=false;
upPressed=false;
downPressed=false;
heroX=5;
heroY=5;
one of the alerts not working
alert("DEATH");
}
}
setInterval(draw, 10);
</script>
</body>
</html>
It's working for me. You had images loading in the animation loop which created a flickering effect. It's best to load your assets onto a canvas and when the images load place them on their canvas. This way you don't have to check if the image is loaded and can have a background color as a stand-in. Also running the animation in an interval loop isn't as efficient as using requestAnimationFrame. Also use preventDefault on the key input to prevent scrolling.
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var H = canvas.height;
var W = canvas.width;
var x = 10;
var y = 15;
var rightPressed = false;
var leftPressed = false;
var upPressed = false;
var downPressed = false;
var heroX = 20;
var monsterX = 200;
var monsterY = 200;
var heroY = 20;
var dx = .68;
var dy = .76;
var score = 0;
var monstersCaught = 0;
var ballPX = 32 + (Math.random() * (canvas.width - 64));
var ballPY = 32 + (Math.random() * (canvas.height - 64));
var h = 178;
var i = 333;
var mineX = 778;
var mineY = 178;
Window.onload = dank();
function dank() {
alert("How to play: move your hero using the arrow keys, and collect colored balls for powerups and points!Get the highest score you can without touching a monster, which makes you start over!Collect the colored balls for more and better special powerups.");
}
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function loadImage(w,h,color,url) {
var can = document.createElement('canvas');
can.width = w;
can.height = h;
var ctx = can.getContext('2d');
ctx.fillStyle=color;
ctx.fillRect(0,0,w,h);
var img = document.createElement('image');
img.onLoad = function() {
ctx.clearRect(0,0,w,h);
ctx.drawImage(img, 0, 0);
};
img.src=url;
return can;
}
// load assets
var heroImage = loadImage(32,32,'#FF9900',"hero.jpg");
var monsterImage = loadImage(32,32,'purple',"monster.jpg");
var rsz_mineImage = loadImage(32,32,'#FF3300',"rsz_mineimg.jpg");
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(heroImage, heroX, heroY);
dope();
checkMonster();
drawMines();
//checkDeath();
requestAnimationFrame(draw);
}
function keyDownHandler(e) {
if (e.keyCode == 39) {
rightPressed = true;
} else if (e.keyCode == 37) {
leftPressed = true;
} else if (e.keyCode == 40) {
downPressed = true;
} else if (e.keyCode == 38) {
upPressed = true;
}
e.preventDefault();
}
function keyUpHandler(e) {
if (e.keyCode == 39) {
rightPressed = false;
} else if (e.keyCode == 37) {
leftPressed = false;
} else if (e.keyCode == 40) {
downPressed = false;
} else if (e.keyCode == 38) {
upPressed = false;
}
e.preventDefault();
}
function dope() {
if (rightPressed) {
heroX += 7;
} else if (leftPressed) {
heroX -= 7;
} else if (upPressed) {
heroY -= 7;
} else if (downPressed) {
heroY += 7;
}
}
function checkMonster() {
ctx.drawImage(monsterImage, monsterX, monsterY)
monsterX += dx;
monsterY += dy;
if (monsterX > canvas.width || monsterX < 0) {
monsterX = -dx;
} else if (monsterY > canvas.height || monsterY < 0) {
monsterY = -dy;
}
if (
heroX <= (monsterX + 32) && monsterX <= (heroX + 32) && heroY <= (monsterY + 32) && monsterY <= (heroY + 32)
) {
alert("DEATH");
heroY = 5;
heroX = 5;
monsterX = 100;
monsterY = 100;
upPressed = false;
downPressed = false;
leftPressed = false;
rightPressed = false;
}
}
function drawMines() {
ctx.drawImage(rsz_mineImage, mineX, mineY);
if (
heroX <= (mineX + 32) && mineX <= (heroX + 32) && heroY <= (mineY + 32) && mineY <= (heroY + 32)
) {
rightPressed = false;
leftPressed = false;
upPressed = false;
downPressed = false;
heroX = 5;
heroY = 5;
alert("DEATH");
}
}
draw();
#canvas {
width:100%;
background-color:#eff0de;
}
body {
background-color:#AADDFF;
}
<canvas id="canvas" width="1300" height="630"></canvas>

Moving up and down on javascript based canvas game

I am making game based on this tutorial: https://developer.mozilla.org/en-US/docs/Games/Workflows/2D_Breakout_game_pure_JavaScript
I think i understand how the paddle moves right and left. But when i try to make it move up and down, its not working at all. I have literally tried everyting but still its not working. So the question is how i can make it move up and down?
Here is the whole code:
<script>
var canvas = document.getElementById("tausta");
var ctx = canvas.getContext("2d");
var ballRadius = 10;
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 2;
var dy = -2;
var paddleHeight = 10;
var paddleWidth = 75;
var paddleX = (canvas.width-paddleWidth)/2;
var paddleY = canvas.height-paddleHeight;
var rightPressed = false;
var leftPressed = false;
var upPressed = false;
var downPressed = false;
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if(e.keyCode == 39) {
rightPressed = true;
}
if(e.keyCode == 37) {
leftPressed = true;
}
if(e.keycode == 38){
upPressed = true;
}
if(e.keycode == 40){
downPressed = true;
}
}
function keyUpHandler(e) {
if(e.keyCode == 39) {
rightPressed = false;
}
if(e.keyCode == 37) {
leftPressed = false;
}
if(e.keycode == 38){
upPressed = false;
}
if(e.keycode == 40){
downPressed = false;
}
}
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI*2);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
function drawPaddle() {
ctx.beginPath();
ctx.rect(paddleX, paddleY, paddleWidth, paddleHeight);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
drawPaddle();
if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
dx = -dx;
}
if(y + dy > canvas.height-ballRadius || y + dy < ballRadius) {
dy = -dy;
}
if(rightPressed && paddleX < canvas.width-paddleWidth) {
paddleX += 5;
}
if(leftPressed && paddleX > 0) {
paddleX -= 5;
}
if(upPressed && paddleY < canvas.height-paddleHeight) {
paddleY += 5;
}
if(downPressed && paddleY > 0) {
paddleY -= 5;
}
x += dx;
y += dy;
}
setInterval(draw, 10);
</script>
Turns out it was a simple mistake.
You typed
if(e.keycode == 38){
if(e.keycode == 40){
But it should be
if(e.keyCode== 38){
if(e.keyCode== 40){
capital C
http://jsfiddle.net/cagwyd6m/4/

Categories

Resources