How to add collision between the player and the image? - javascript

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>

Related

How to move an object across a game board. Multiple Objects

I am an extreme beginner in the field of P5.JS. I am way more knowledgeable in Java which will be apparent in my broken code. I have attempted a multitude of Java approaches to cycling through objects of the same class and applying methods to them. My attempt is to implement buttons that will move them forward as of now and once I understand that move on to more complicated interactions.
https://openprocessing.org/sketch/1564721 6
This is the link to the code I am attempting to fix it currently, but if you have any tips or advice for streamlining this please let me know.
var gridCellSizeX = 80;
var gridCellSizeY = 100;
var gridAlpha = 1000;
let img;
var gridCellSizeSlider;
turnValue = 1;
var count = 1;
var gameOn = true;
var forward = false;
function preload() {
img = loadImage('vagg02.jpg');
}
function setup() {
createCanvas(800, 600);
image(img, 0,0,800,500);
image( img ,0, 500, 800,100);
stroke(0, gridAlpha);
for (var x = 0; x < width; x += gridCellSizeX) {
line(x, 0, x, 500);
}
for (var y = 0; y < height; y += gridCellSizeY) {
line(0, y, width, y);
}
token1 = new token(15, 5, 100, 5000, 'reb', 1)
token2 = new token(15, 205, 100, 5000,'reb', 2 )
token3 = new token(15, 405, 100, 5000, 'reb', 3)
token4 = new token(735, 5, 100, 5000,'union', 4)
token5 = new token(735, 205, 100, 5000, 'union', 5)
token6 = new token(735, 405, 100, 5000, 'union', 6)
const tokens = new Array(token1, token2, token3, token4, token5, token6);
forwardButton = createButton('Move -->')
forwardButton.position(300, 525);
forwardButton.mousePressed(moveForward());
//button = createButton('Move -->'); button.position(300, 525); button.mousePressed();
button2 = createButton('Move Up');
button2.position(400, 525);
button2.mousePressed();
button3 = createButton('Move Down');
button3.position(500, 525);
button3.mousePressed();
button4 = createButton('Move <--');
button4.position(600, 525);
button4.mousePressed();
}
function draw() {
if(forward == true) token1.x =+ 500;
//for(let i = 0; gameOn == true; i++){ if(i > 6){ i = 0; }}
}
function mousePressed() {
if (mouseX >= 300 && mouseX <= 325 &&
mouseY >= 525 && mouseY <= 500){
token1.moveForward();
}
return false;
}
// new file token
class token {
constructor(xpos, ypos, t, a, s, turn) {
this.x = xpos;
this.y = ypos;
this.troopSize = t / 2;
this.accuracy = a / 100.0;
this.side = s;
this.moveTurn = turn;
this.loaded = true;
if(this.side == 'reb'){
fill('red');
rect(this.x, this.y, this.troopSize, 90)
}
if(this.side == 'union'){
fill('blue');
rect(this.x, this.y, this.troopSize, 90)
}
}
getToken(){
if(count > 6){
count = 1;
}
if(count == 1) {
return token1;
}
else if(count == 2){
return token2;
}
else if(count == 3){
return token3;
}
else if(count == 4){
return token4;
}
else if(count == 5){
return token5;
}
else if(count == 6){
return token6;
}
count++;
}
///////// Beginning of Basic Functions for the TOKEN CLASS
moveForward(){
if(this.side == 'reb'){
token1.x += 50;
redraw(token1);
}
if(this.side == 'union'){
this.x += -50;
redraw();
}
}
////
moveBackward(){
if(this.side == 'reb'){
this.x = this.x - 50;
}
if(this.side == 'union'){
this.x = this.x + 50;
}
}
/////
fire(){
if(loaded == true){
}
}
//////
load(){
}
///////
fixBayonet(){
}
////////
charge(){
}
///////// END of Basic Functions for the TOKEN CLASS
}

problems with resizing sprites

I need to resize my spritesheet so it fits the correct dimensions of my game object. I have been looking around the internet and I found that this -ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);- is what i think i need to use. however, i do not know how or where to implement this in my code. i know how it works but i dont know where to put it or where in my code to put it. i use almost completely javascript
var myGamePiece;
var myObstacle;
var object1;
var objects;
var box;
function startGame() {
//creation of objects
wall = new component(30, 100, "black", 300, 200);
myGamePiece = new component(30, 30, "red", 240, 135);
myObstacle = new component(100, 100, "green", 200, 100);
object1 = new component(30, 30, "enemy.png", 340, 125, "image");
box = new component(30, 30, "box.png", 177, 145, "image");
myGameArea.start();
}
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);
},
collide : function() {
object1.x += 1;
object1.y += 1;
},
//what to do when pushing box
boxleft : function() {
box.x -= 1;
x -= 1;
}
}
function component(width, height, color, x, y, type) {
this.type = type;
if (type == "image") {
this.image = new Image();
this.image.src = color;
}
this.sx = x;
this.sy = y;
this.swidth = width;
this.sheight = height;
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
if (type == "image") {
ctx.drawImage(this.image,
this.x,
this.y,
this.width,
this.height
);
} else {
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
}
//code for gray square
this.crashWith = function(object1) {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var otherleft = object1.x;
var otherright = object1.x + (object1.width);
var othertop = object1.y;
var otherbottom = object1.y + (object1.height);
var crash = true;
if ((mybottom < othertop) ||
(mytop > otherbottom) ||
(myright < otherleft) ||
(myleft > otherright)) {
crash = false;
}
return crash;
}
//code to push box
this.pushboxWith = function(box) {
const myleft = this.x;
const myright = this.x + (this.width);
const mytop = this.y;
const mybottom = this.y + (this.height);
const boxleft = box.x-2;
const boxright = box.x + (box.width)+2;
const boxtop = box.y+2;
const boxbottom = box.y + (box.height)-2;
var pushboxleft = true;
var pushboxright = true;
//test if pushing box
if ((myleft < boxright) && (mybottom >= boxtop) && (mytop <= boxbottom) && (myleft > boxleft)) {
pushboxleft = true;
} else {
pushboxleft = false;
}
return pushboxleft;
}
}
function updateGameArea() {
if (myGamePiece.crashWith(object1)) {
myGameArea.collide();
} else if (myGamePiece.pushboxWith(box)) {
myGameArea.boxleft();
} else {
myGameArea.clear();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
//keyboard controls. moves everything but the player
if (myGameArea.key && myGameArea.key == 37) {
myObstacle.x += 2;
object1.x += 2;
box.x += 2;
wall.x += 2;
}
if (myGameArea.key && myGameArea.key == 39) {
myObstacle.x += -2;
object1.x += -2;
box.x += -2;
wall.x += -2;
}
if (myGameArea.key && myGameArea.key == 38) {
myObstacle.y += 2;
object1.y += 2;
box.y += 2;
wall.y += 2
}
if (myGameArea.key && myGameArea.key == 40) {
myObstacle.y += -2;
object1.y += -2;
box.y += -2;
wall.y += -2
}
//other square movement. disabled to isolate code.
/*
if (object1.x < myGamePiece.x) {
object1.x += 1;
}
if (object1.x > myGamePiece.x) {
object1.x += -1;
}
if (object1.y < myGamePiece.y) {
object1.y += 1;
}
if (object1.y > myGamePiece.y) {
object1.y += -1;
}
*/
/* object order: the object that is higher on the list
will be on top of objects lower on the list
*/
myObstacle.update();
myGamePiece.newPos();
myGamePiece.update();
wall.update();
object1.update();
box.update();
//end of list
}
}
i do use some html
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<script src="main.js"></script>
</body>
</html>
if you need to test my code you can find it here- https://eeeegame-2.octopuscat.repl.co/

i cant get my shot to travel directly to my cursor

I am making a 2d game with javascript and i can't get the shot to travel in a line directly to the cursor. I want it so when the shoot function is called th make the shot travel to the cursor and not alter the path when the cursor is moved after the shot is already out. Right now it is onnly going diagonal to the player
<!DOCTYPE html>
<html lang="en" onclick="shoot()">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta charset="utf-8">
<style>
canvas {
border:4px solid #000000;
background-color: #26af2d;
}
</style>
<body onload="startGame()">
<div name="buttonDiv">
<button type="button" id="startRoundBtn" onclick= startWave();>dont mind this</button>
</div>
<p id="demo">
</p>
<script>
let playerHealth = 100;
let shot = false;
let enemyOut = false;
let waveActive = false;
let enemyDmg = 25;
let playerImmuneTime = 0;
//start
var player;
var TopEdge;
var BottomEdge;
var RightEdge;
var LeftEdge;
let Enemy;
var projectile;
function startGame() {
player = new component(30, 30, "red", 10, 120);
TopEdge = new component(10000, 200, "purple", 0, -200);
BottomEdge = new component(10000, 1, "purple", 0, 500);
RightEdge = new component(1000, 500, "purple", 1150, 0);
LeftEdge = new component(1000, 500, "purple", -1000, 0);
var x = document.getElementById("startRoundBtn");
myGameArea.start();
}
//game area
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 1150;
this.canvas.height = 500;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas,
document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 10);
window.addEventListener('keydown', function (e) {
myGameArea.keys = (myGameArea.keys || []);
myGameArea.keys[e.keyCode] = (e.type == "keydown");
})
window.addEventListener('keyup', function (e) {
myGameArea.keys[e.keyCode] = (e.type == "keydown");
})
},
clear : function(){
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop : function(){
clearInterval(this.interval);
}
}
//coords
var pointerX = 0;
var pointerY = 0;
document.onmousemove = function(event) {
pointerX = event.pageX;
pointerY = event.pageY;
}
setInterval(pointerCheck, 1);
function pointerCheck() {
var cursorCoords = 'Cursor Location: '+pointerX+'X, '+pointerY+'Y health: ' + playerHealth + ' imune time:' +playerImmuneTime
document.getElementById("demo").innerHTML = cursorCoords;
}
//compenents
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);
}
//new pos
this.newPos = function() {
this.X += this.speedX;
this.Y += this.speedY;
}
//crashing
this.crashWith = function(otherobj) {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var otherleft = otherobj.x;
var otherright = otherobj.x + (otherobj.width);
var othertop = otherobj.y;
var otherbottom = otherobj.y + (otherobj.height);
var crash = true;
if ((mybottom < othertop) ||
(mytop > otherbottom) ||
(myright < otherleft) ||
(myleft > otherright)) {
crash = false;
}
return crash;
}
}
//updates
function updateGameArea() {
myGameArea.clear();
if (playerHealth > 0) {
player.newPos();
player.update();
}
TopEdge.update();
BottomEdge.update();
RightEdge.update();
LeftEdge.update();
if (shot == true) {
projectile.update();
projectile.newPos();
projectile.speedX = 0;
projectile.speedY = 0;
}
if (enemyOut == true && playerHealth > 0) {
if (Enemy.crashWith(player) && playerImmuneTime <= 0) {
playerHealth = playerHealth -= enemyDmg;
playerImmuneTime = 50;
} if (playerImmuneTime >= 0) {
playerImmuneTime -= 1;
}
Enemy.newPos();
Enemy.update();
Enemy.speedX = 0;
Enemy.speedY = 0;
}
player.speedX = 0;
player.speedY = 0;
//movement
if (myGameArea.keys[65] ) {player.speedX = -2.5; }
if (myGameArea.keys[68] ) {player.speedX = 2.5; }
if (myGameArea.keys[87] ) {player.speedY = -2.5; }
if (myGameArea.keys[83] ) {player.speedY = 2.5; }
if (myGameArea.keys[82]) {waveActive = true;}
if (myGameArea.keys[75]) {waveActive = false;}
if (enemyOut == true && player.x >= Enemy.x) {Enemy.speedX = 1; }
if (enemyOut == true && player.x <= Enemy.x) {Enemy.speedX = -1; }
if (enemyOut == true && player.y >= Enemy.y) {Enemy.speedY = 1; }
if (enemyOut == true && player.y <= Enemy.y) {Enemy.speedY = -1; }
if (waveActive == true && enemyOut == false) {
createEnemy();
}
if (shot == true && pointerX > player.x) {projectile.speedX = 10};
if (shot == true && pointerX < player.x) {projectile.speedX = -10};
if (shot == true && pointerY > player.y) {projectile.speedY = 10};
if (shot == true && pointerY < player.y) {projectile.speedY = -10};
if (shot == true && enemyOut == true && projectile.crashWith(Enemy)) {
shot = false;
enemyOut = false;
waveActive = false;
}
//edges of game area
if (player.crashWith(TopEdge) && myGameArea.keys[87]) {
player.speedY = 0;
}
if (player.crashWith(RightEdge) && myGameArea.keys[68]) {
player.speedX = 0;
}
if (player.crashWith(BottomEdge) && myGameArea.keys[83]) {
player.speedY = 0;
}
if (player.crashWith(LeftEdge) && myGameArea.keys[65]) {
player.speedX = 0;
}
player.x += player.speedX;
player.y += player.speedY;
Enemy.x += Enemy.speedX;
Enemy.y += Enemy.speedY;
projectile.x += projectile.speedX;
projectile.y += projectile.speedY;
}
function createEnemy() {
Enemy = new component(30, 30, "purple",
Math.floor(Math.random() * 1100),
Math.floor(Math.random() * 500));
enemyOut = true;
}
function shoot() {
let midPlayerX = player.x + 12;
let midPlayerY = player.y + 12;
projectile = new component(5, 5, "white", midPlayerX, midPlayerY);
shot = true;
}
</script>
</body>
</html>
you need to 'freeze' the pointerX and pointerY values between the shot being fired and reaching its destination (otherwise those values will change on mousemove).
You already have shot=true when the projectile is launched so it can be read in a conditional you add to your mousemove event listener. That will take care of freezing the pointers when the projectile is fired :
document.onmousemove = function (event) {
if (!shot) {
pointerX = event.pageX
pointerY = event.pageY
} // prevent updates to pointers when shot is fired;
}
but you will need to reactivate the listener by setting shot to false when the projectile colides with the stored pointerX and pointerY values.

Pausing javascript game using style.display in if statements not working

I'm working on a javascript game and trying to add some code to the button that toggles the visibility of the games and acts as a pause button so that it will stop running and not keep shoving scoring alerts down your throat if you have it hidden, and all of the code that I've written has failed miserably. Here it is, hope someone can help me fix it.
<div id = 'games'>
<!-- I only put this canvas in a div because there will be more games here soon. -->
<canvas id='my' width = '640' height = '480'></canvas>
</div>
<script>
var canvas = document.getElementById("my");
var ctx = canvas.getContext("2d");
function paddle(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.speedModifier = 0;
this.hasCollidedWith = function(ball) {
var paddleLeftWall = this.x;
var paddleRightWall = this.x + this.width;
var paddleTopWall = this.y;
var paddleBottomWall = this.y + this.height;
if (ball.x > paddleLeftWall &&
ball.x < paddleRightWall &&
ball.y > paddleTopWall &&
ball.y < paddleBottomWall) {
return true;
}
return false;
};
this.move = function(keyCode) {
var nextY = this.y;
if (keyCode == 40) {
nextY += 5;
this.speedModifer = 1.5;
} else if (keyCode == 38) {
nextY += -5;
this.speedModifier = 1.5;
} else {
this.speedModifier = 0;
}
nextY = nextY < 0 ? 0 : nextY;
nextY = nextY + this.height > 480 ? 480 - this.height : nextY;
this.y = nextY;
};
}
var player = new paddle(5, 200, 25, 100);
var ai = new paddle(610, 200, 25, 100);
var ball = {
x: 320,
y: 240,
radius: 7,
xSpeed: 2,
ySpeed: 0,
playerscore: 0,
aiscore: 0,
reverseX: function() {
this.xSpeed *= -1;
},
reverseY: function() {
this.ySpeed *= -1;
},
reset: function() {
alert('The score is now ' + this.playerscore + ' to ' + this.aiscore);
this.x = 20;
this.y = 24;
this.xSpeed = 2;
this.ySpeed = 0;
},
isBouncing: function() {
return ball.ySpeed != 0;
},
modifyXSpeedBy: function(modification) {
modification = this.xSpeed < 0 ? modification * -1 : modification;
var nextValue = this.xSpeed + modification;
nextValue = Math.abs(nextValue) > 9 ? 9 : nextValue;
this.xSpeed = nextValue;
},
modifyYSpeedBy: function(modification) {
modification = this.ySpeed < 0 ? modification * -1 : modification;
this.ySpeed += modification;
}
};
function tick() {
updateGame();
draw()
window.setTimeout("tick()", 1000 / 60);
}
function updateGame() {
ball.x += ball.xSpeed;
ball.y += ball.ySpeed;
if (ball.x < 0) {
ball.reset();
ball.aiscore = ball.aiscore + 1;
}
if (ball.x > 640) {
ball.reset();
ball.playerscore = ball.playerscore + 1
}
if (ball.y <= 0 || ball.y >= 480) {
ball.reverseY();
}
var collidedWithPlayer = player.hasCollidedWith(ball);
var collidedWithAi = ai.hasCollidedWith(ball);
if (collidedWithPlayer || collidedWithAi) {
ball.reverseX();
ball.modifyXSpeedBy(0.25);
var speedUpValue = collidedWithPlayer ? player.speedModifier : ai.speedModifier;
ball.modifyYSpeedBy(speedUpValue);
}
for (var keyCode in heldDown) {
player.move(keyCode);
}
var aiMiddle = ai.y + (ai.height / 2);
if (aiMiddle < ball.y) {
ai.move(40);
}
if (aiMiddle > ball.y) {
ai.move(38);
}
}
function draw() {
ctx.fillStyle = "black";
ctx.fillRect(0, 0, 640, 480);
renderPaddle(player);
renderPaddle(ai);
renderBall(ball);
}
function renderPaddle(paddle) {
ctx.fillStyle = "blue";
ctx.fillRect(paddle.x, paddle.y, paddle.width, paddle.height);
}
function renderBall(ball) {
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.radius, 0, 2 * Math.PI, false);
ctx.fillStyle = "pink";
ctx.fill();
}
var heldDown = {};
window.addEventListener("keydown", function(keyInfo) {
heldDown[event.keyCode] = true;
}, false);
window.addEventListener("keyup", function(keyInfo) {
delete heldDown[event.keyCode];
}, false);
function playPong(){
if (canvas.style.display == 'none'){canvas.style.display = 'block';}
else {canvas.style.display == 'none';}
if (canvas.style.display === 'block')
{
tick()};
}
</script>
<script>
function hide() {
var games = document.getElementById('games')
if (games.style.display === 'block')
games.style.display = 'none';
else{games.style.display = 'block';}
}
function show(){
var canvas = document.getElementById('my')
canvas.style.display = 'block';
}
</script>
<button onclick = 'hide()'> Hide or show the games</button>
<button onclick = 'playPong();show()'> Play pong </button>
I would try not using the visibility of the canvas as the deciding factor in the if statement and instead maybe trying something like this-
<div id='games'>
<canvas id='my' width='640' height='480'></canvas>
</div>
<script>
var paused = false
function PausePlay() {
if (paused === false) {
paused = true;
} else {
paused = false;
}
}
var canvas = document.getElementById("my");
var ctx = canvas.getContext("2d");
function paddle(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.speedModifier = 0;
this.hasCollidedWith = function(ball) {
var paddleLeftWall = this.x;
var paddleRightWall = this.x + this.width;
var paddleTopWall = this.y;
var paddleBottomWall = this.y + this.height;
if (ball.x > paddleLeftWall &&
ball.x < paddleRightWall &&
ball.y > paddleTopWall &&
ball.y < paddleBottomWall) {
return true;
}
return false;
};
this.move = function(keyCode) {
var nextY = this.y;
if (keyCode == 40) {
nextY += 5;
this.speedModifer = 1.5;
} else if (keyCode == 38) {
nextY += -5;
this.speedModifier = 1.5;
} else {
this.speedModifier = 0;
}
nextY = nextY < 0 ? 0 : nextY;
nextY = nextY + this.height > 480 ? 480 - this.height : nextY;
this.y = nextY;
};
}
var player = new paddle(5, 200, 25, 100);
var ai = new paddle(610, 200, 25, 100);
var ball = {
x: 320,
y: 240,
radius: 7,
xSpeed: 2,
ySpeed: 0,
playerscore: 0,
aiscore: 0,
reverseX: function() {
this.xSpeed *= -1;
},
reverseY: function() {
this.ySpeed *= -1;
},
reset: function() {
alert('The score is now ' + this.playerscore + ' to ' + this.aiscore);
this.x = 20;
this.y = 24;
this.xSpeed = 2;
this.ySpeed = 0;
},
isBouncing: function() {
return ball.ySpeed != 0;
},
modifyXSpeedBy: function(modification) {
modification = this.xSpeed < 0 ? modification * -1 : modification;
var nextValue = this.xSpeed + modification;
nextValue = Math.abs(nextValue) > 9 ? 9 : nextValue;
this.xSpeed = nextValue;
},
modifyYSpeedBy: function(modification) {
modification = this.ySpeed < 0 ? modification * -1 : modification;
this.ySpeed += modification;
}
};
function tick() {
updateGame();
draw()
window.setTimeout("tick()", 1000 / 60);
}
function updateGame() {
if (paused === false) {
ball.x += ball.xSpeed;
ball.y += ball.ySpeed;
if (ball.x < 0) {
ball.reset();
ball.aiscore = ball.aiscore + 1;
}
if (ball.x > 640) {
ball.reset();
ball.playerscore = ball.playerscore + 1
}
if (ball.y <= 0 || ball.y >= 480) {
ball.reverseY();
}
var collidedWithPlayer = player.hasCollidedWith(ball);
var collidedWithAi = ai.hasCollidedWith(ball);
if (collidedWithPlayer || collidedWithAi) {
ball.reverseX();
ball.modifyXSpeedBy(0.25);
var speedUpValue = collidedWithPlayer ? player.speedModifier : ai.speedModifier;
ball.modifyYSpeedBy(speedUpValue);
}
for (var keyCode in heldDown) {
player.move(keyCode);
}
var aiMiddle = ai.y + (ai.height / 2);
if (aiMiddle < ball.y) {
ai.move(40);
}
if (aiMiddle > ball.y) {
ai.move(38);
}
}
}
function draw() {
if (paused === false) {
ctx.fillStyle = "black";
ctx.fillRect(0, 0, 640, 480);
renderPaddle(player);
renderPaddle(ai);
renderBall(ball);
}
}
function renderPaddle(paddle) {
ctx.fillStyle = "blue";
ctx.fillRect(paddle.x, paddle.y, paddle.width, paddle.height);
}
function renderBall(ball) {
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.radius, 0, 2 * Math.PI, false);
ctx.fillStyle = "pink";
ctx.fill();
}
var heldDown = {};
window.addEventListener("keydown", function(keyInfo) {
heldDown[event.keyCode] = true;
}, false);
window.addEventListener("keyup", function(keyInfo) {
delete heldDown[event.keyCode];
}, false);
function playPong() {
tick()
}
</script>
<script>
function getOff() {
alert("you've been on for five minutes now. Time to take a break.");
setTimeout(function() {
alert("it's been 10 minutes now. Get back to work.");
close();
var body = document.getElementById('hide5')
body.style.display = 'none'
}, 300000);
}
setInterval(getOff, 300000)
}
</script>
<script>
function hide() {
var games = document.getElementById('games')
if (games.style.display === 'block')
games.style.display = 'none';
else {
games.style.display = 'block';
}
}
function show() {
var canvas = document.getElementById('my')
canvas.style.display = 'block';
}
</script>
<button onclick='hide()'> Hide or show the games</button>
<button onclick='PausePlay()'> Pause games </button>
<button onclick='playPong()'> Play pong </button>

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>

Categories

Resources