In the below code, pressing C or V should change speed of that ball.
Press V ~10 times and after 5-10 seconds press an arrow button. Where is my mistake?
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;
function circle(x, y, radius, fillCircle) {
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2, false);
if (fillCircle) {
ctx.fill();
} else {
ctx.stroke();
}
};
function ball() {
this.speed = 5;
this.x = width / 2;
this.y = height / 2;
this.xSpeed = this.speed;
this.ySpeed = 0;
this.size = 5;
};
ball.prototype.move = function() {
this.x += this.xSpeed;
this.y += this.ySpeed;
if (this.x < 0) {
this.x = width;
} else if (this.x > width) {
this.x = 0;
}
if (this.y > height) {
this.y = 0;
} else if (this.y < 0) {
this.y = height;
}
};
ball.prototype.draw = function() {
circle(this.x, this.y, this.size, true);
};
ball.prototype.setDirection = function(direction) {
if (direction === "up") {
this.xSpeed = 0;
this.ySpeed = -this.speed;
} else if (direction === "down") {
this.xSpeed = 0;
this.ySpeed = this.speed;
} else if (direction === "right") {
this.xSpeed = this.speed;
this.ySpeed = 0;
} else if (direction === "left") {
this.xSpeed = -this.speed;
this.ySpeed = 0;
} else if (direction === "stop") {
this.xSpeed = 0;
this.ySpeed = 0;
}
};
ball.prototype.doCommand = function(direction) {
if (direction === "X") {
this.size += 2;
} else if (direction === "Z") {
this.size -= 2;
} else if (direction === "C") {
this.speed -= 2;
} else if (direction === "V") {
this.speed += 2;
}
if (this.speed < 0) {
this.speed = 1;
}
if (this.size < 0) {
this.size = 1;
}
}
var Ball = new ball();
var commands = ["Z", "X", "C", "V"];
var keyActions = {
32: "stop",
37: "left",
38: "up",
39: "right",
40: "down",
90: "Z",
88: "X",
67: "C",
86: "V"
};
$("body").keydown(function(event) {
var direction = keyActions[event.keyCode];
for (var n = 0; n < commands.length; n++) {
if (direction === commands[n]) {
Ball.doCommand(direction);
} else {
Ball.setDirection(direction);
}
};
});
setInterval(function() {
ctx.clearRect(0, 0, width, height);
Ball.draw();
Ball.move();
ctx.strokeRect(0, 0, width, height);
}, 30);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<canvas id="canvas" width="400" height="400"></canvas>
I have updated your code.
First thing in keydown Handler we don't need for loop. I have changed this.
I have updated Do Command as well. Here is the problem: you are not updating xspeed & yspeed in the doCommand I did that change for c & v.
I hope this is what you are expecting.
Please find the updated code.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"><title>Drawing some circles...</title>
</head>
<body>
<script src = "https://code.jquery.com/jquery-2.1.0.js"></script>
<canvas id = "canvas" width="400" height="400"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;
function circle(x,y,radius,fillCircle)
{
ctx.beginPath();
ctx.arc(x,y,radius,0,Math.PI*2,false);
if(fillCircle)
{
ctx.fill();
}
else
{
ctx.stroke();
}
};
function ball()
{
this.speed = 5;
this.x = width/2;
this.y = height/2;
this.xSpeed = this.speed;
this.ySpeed = 0;
this.size = 5;
};
ball.prototype.move = function()
{
this.x += this.xSpeed;
this.y += this.ySpeed;
if (this.x<0)
{
this.x = width;
}
else if(this.x>width)
{
this.x = 0;
}
if (this.y>height)
{
this.y = 0;
}
else if(this.y<0)
{
this.y = height;
}
};
ball.prototype.draw = function()
{
circle(this.x,this.y,this.size,true);
};
ball.prototype.setDirection = function(direction)
{
if(direction ==="up")
{
this.xSpeed = 0;
this.ySpeed = -this.speed;
}else if(direction ==="down")
{
this.xSpeed = 0;
this.ySpeed = this.speed;
}else if(direction ==="right")
{
this.xSpeed = this.speed;
this.ySpeed = 0;
}else if(direction ==="left")
{
this.xSpeed = -this.speed;
this.ySpeed = 0;
}else if(direction ==="stop")
{
this.xSpeed = 0;
this.ySpeed = 0;
}
};
ball.prototype.doCommand = function(direction)
{
if(direction ==="X")
{
this.size +=2;
}else if(direction ==="Z"){
this.size -=2;
}else if(direction ==="C"){
this.speed -=2;
}else if(direction ==="V"){
this.speed +=2;
}
if(this.speed<0)
{
this.speed = 1;
}
if(this.size<0)
{
this.size = 1;
}
if(direction ==="V" || direction ==="C") {
if(this.xSpeed!=0) {
this.xSpeed = this.speed;
}
if(this.ySpeed!=0) {
this.ySpeed = this.speed;
}
}
}
var Ball = new ball();
var commands = ["Z","X","C","V"];
var keyActions = {
32:"stop",
37:"left",
38:"up",
39:"right",
40:"down",
90:"Z",
88:"X",
67:"C",
86:"V"
};
$("body").keydown(function (event)
{
var direction = keyActions[event.keyCode];
if(commands.includes(direction))
{
Ball.doCommand(direction);
}
else{
Ball.setDirection(direction);
}
});
setInterval(function()
{
ctx.clearRect(0,0,width,height);
Ball.draw();
Ball.move();
ctx.strokeRect(0,0,width,height);
}, 30);
</script>
</body>
</html>
Related
Im making a pong game and I want to make the ball have a speedX and a speedY that is added to the ball that makes it move along the X and Y axis but im not sure how to adjust those variables based off of the balls angle. In function ballPhysics() I need to replace the 0's with something to get the speed it should go along that axis. But if anyone finds anything else that should be worked on itd be great if you let me know thanks.
let cvs, ctx;
let width = 600, height = 500;
let keysPressed = [];
class Wall {
constructor(x, y, w, h, speed) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.speed = speed;
}
}
class Ball {
constructor(x, y , w, h, speedX, speedY, angle) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.speedX = speedX;
this.speedY = speedY;
this.angle = angle;
}
}
let left = new Wall(25, 250, 10, 100, 10);
let right = new Wall(width-25, 250, 10, 100, 10)
let ball = new Ball(width/2, height/2, 5, 5, 0, 0, 0);
function ballPhysics() {
ball.x += ball.speedX;
ball.y += ball.speedY;
ball.speedX = 0//figure out direction;
ball.speedY = 0//figure out direction;
}
function start() {
ball.x = width/2;
ball.y = height/2;
if(Math.random() < 0.5) {
ball.angle = 90;
} else {
ball.angle = -90;
}
console.log(ball.angle);
}
function update() {
setInterval(function () {
ballPhysics();
for(let i = 0; i < keysPressed.length; i++) {
if(keysPressed[i] == 'KeyW' && left.y >= 0) {
left.y -= left.speed;
}
if(keysPressed[i] == 'KeyS' && left.y + left.h <= height) {
left.y += left.speed;
}
if(keysPressed[i] == 'ArrowUp' && right.y >= 0) {
right.y -= right.speed;
}
if(keysPressed[i] == 'ArrowDown' && right.y + right.h <= height) {
right.y += right.speed;
}
if(keysPressed[i] == 'Space') {
start();
}
}
}, 16)
}
function renderPlayers() {
ctx.fillStyle = '#FF0000';
ctx.fillRect(left.x, left.y, left.w, left.h);
ctx.fillRect(right.x, right.y, right.w, right.h);
}
function renderBall() {
ctx.fillStyle = '#0000FF';
ctx.fillRect(ball.x, ball.y, ball.w, ball.h);
}
function render() {
ctx.clearRect(0, 0, cvs.width, cvs.height);
renderBall();
renderPlayers();
requestAnimationFrame(render);
}
window.addEventListener("DOMContentLoaded", function () {
cvs = document.getElementById("cvs");
ctx = cvs.getContext("2d");
cvs.width = width;
cvs.height = height;
update();
render();
});
window.addEventListener('keydown', function(e) {
if(!keysPressed.includes(e.code)) {
keysPressed.push(e.code);
}
});
window.addEventListener('keyup', function(e) {
for(let i = 0; i < keysPressed.length; i++) {
if(keysPressed[i] == e.code) {
keysPressed.splice(i, 1);
}
}
});
#cvs {
border: solid 1px black;
background: #D1C3C3;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Platformer</title>
<link rel="stylesheet" href="/style.css" />
<script src="/script.js" defer></script>
</head>
<body>
<canvas width="0" height="0" id="cvs"></canvas>
</body>
</html>
I'm using Javascript to make a game and my character is supposed to move a box only when it's touching the box, but it always moves and when my character is on the same y-axis as the right side of of the box the game freezes, even if my character is not touching the right side of the box. I only coded the box to be able to be pushed left so far. I want to make sure that it can move left properly before I move on to making it be able to move elsewhere. My character does not move, instead everything but the character moves to make it seem like its moving without having to have different areas and stuff. There is code for other things, but its not used so I can isolate the code for the box. My code is mostly Javascript but does have a little bit of 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="script2.js"></script>
</body>
</html>
var wall
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);
myMap = new component(0, 0, "map.jpeg", -100, -100, "image")
object1 = new component(30, 30, "gray", 340, 125);
box = new component(30, 30, "blue", 290, 145);
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;
},
boxup : function() {
box.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.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;
}
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;
}
this.pushboxleftWith = function(box) {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var boxleft = box.x;
var boxright = box.x + (box.width);
var boxtop = box.y;
var boxbottom = box.y + (box.height);
var pushboxdown = true;
var pushboxup = true;
var pushboxleft = true;
var pushboxright = true;
if (mybottom < boxtop) {
pushboxdown = true;
}
if (mytop > boxbottom) {
pushboxup = true;
}
if (myright < boxleft) {
pushboxright = true;
}
if ((myleft > boxright) && (((myBottom <= boxtop) && (myBottom >= boxbottom)) || ((myTop <= boxtop) && (myTop >= boxbottom)))) {
pushboxleft = false;
}
return pushboxleft;
return pushboxright;
return pushboxdown;
return pushboxup;
}
}
function updateGameArea() {
if (myGamePiece.crashWith(object1)) {
myGameArea.collide();
} else {
if (myGamePiece.pushboxleftWith(box)) {
myGameArea.boxup();
}
myGameArea.clear();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
//keyboard controls. work but look ugly. moves everything but the player
if (myGameArea.key && myGameArea.key == 37) {myObstacle.x += 2; myMap.x += 2;object1.x+=2; box.x += 2; wall.x += 2;}
if (myGameArea.key && myGameArea.key == 39) {myObstacle.x += -2; myMap.x += -2; object1.x+=-2; box.x += -2; wall.x += -2;}
if (myGameArea.key && myGameArea.key == 38) {myObstacle.y += 2; myMap.y += 2; object1.y+=2; box.y += 2; wall.y += 2}
if (myGameArea.key && myGameArea.key == 40) {myObstacle.y+=-2; object1.y += -2; myMap.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
*/
myMap.update();
myObstacle.update();
myGamePiece.newPos();
myGamePiece.update();
wall.update();
object1.update();
box.update();
//end of list
}
}```
My game piece won't move properly and freezes the game
As Baro pointed out, JavaScript variables are case-sensitive, meaning mybottom and myBottom are completely different variables. So when you tried to access myBottom, having only set mybottom, you got an error. Your game froze because you were running that code in your set interval, every 20 milliseconds.
Here is a working version of your code that you can play around with. I have refactored it a little:
let objects;
let wall = new component(30, 100, "black", 300, 200);
let myGamePiece = new component(30, 30, "red", 240, 135);
let myObstacle = new component(100, 100, "green", 200, 100);
let myMap = new component(0, 0, "orange", -100, -100)
let object1 = new component(30, 30, "gray", 340, 125);
let box = new component(30, 30, "blue", 290, 145);
const myGameArea = {
canvas: document.querySelector("#game-area"),
start: function() {
this.context = this.canvas.getContext("2d");
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;
},
boxup: function() {
box.x -= 1;
}
}
myGameArea.start();
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
}
this.crashWith = function(object1) {
let myleft = this.x;
let myright = this.x + (this.width);
let mytop = this.y;
let mybottom = this.y + (this.height);
let otherleft = object1.x;
let otherright = object1.x + (object1.width);
let othertop = object1.y;
let otherbottom = object1.y + (object1.height);
let crash = true;
if ((mybottom < othertop) ||
(mytop > otherbottom) ||
(myright < otherleft) ||
(myleft > otherright)) {
crash = false;
}
return crash;
}
this.pushboxleftWith = function(box) {
let myleft = this.x;
let myright = this.x + (this.width);
let mytop = this.y;
let mybottom = this.y + (this.height);
let boxleft = box.x;
let boxright = box.x + (box.width);
let boxtop = box.y;
let boxbottom = box.y + (box.height);
let pushboxdown = true;
let pushboxup = true;
let pushboxleft = true;
let pushboxright = true;
if (mybottom < boxtop) pushboxdown = true;
if (mytop > boxbottom) pushboxup = true;
if (myright < boxleft) pushboxright = true;
if ((myleft > boxright) && (((mybottom <= boxtop) && (mybottom >= boxbottom)) || ((mytop <= boxtop) && (mytop >= boxbottom)))) {
pushboxleft = false;
}
return pushboxleft;
return pushboxright;
return pushboxdown;
return pushboxup;
}
}
function updateGameArea() {
if (myGamePiece.crashWith(object1)) {
myGameArea.collide();
} else {
if (myGamePiece.pushboxleftWith(box)) {
myGameArea.boxup();
}
myGameArea.clear();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
//keyboard controls. moves everything but the player
if (myGameArea.key && myGameArea.key == 37) {
myObstacle.x += 2;
myMap.x += 2;
object1.x += 2;
box.x += 2;
wall.x += 2;
}
if (myGameArea.key && myGameArea.key == 39) {
myObstacle.x += -2;
myMap.x += -2;
object1.x += -2;
box.x += -2;
wall.x += -2;
}
if (myGameArea.key && myGameArea.key == 38) {
myObstacle.y += 2;
myMap.y += 2;
object1.y += 2;
box.y += 2;
wall.y += 2
}
if (myGameArea.key && myGameArea.key == 40) {
myObstacle.y += -2;
object1.y += -2;
myMap.y += -2;
box.y += -2;
wall.y += -2
}
myMap.update();
myObstacle.update();
myGamePiece.newPos();
myGamePiece.update();
wall.update();
object1.update();
box.update();
}
}
canvas {
border: 1px solid #d3d3d3;
background-color: #f1f1f1;
}
<body>
<script src="script2.js" type="module"></script>
<canvas id="game-area" width="480" height="270"></canvas>
</body>
i was making a javascript game in p5.js. I made a lot of the game, then wanted to add some combat. I made a weapon that shoots bullets. But now the bullet is hard to make. So here is how my weapon works:
it starts from the player location
it founds the y rotation of the mouse click (looks from the center of the screen and looks what degree rotation it is (360 degrees))
looks to the y rotation of the mouse click
goes off in the distance
So how do I make the bullet? I have the base script, but the bullet only gets deleted when it hits a enemy, only goes to the mosue, has a dumb algorthm for path finding to the mouse, you can have only one bullet at once , and if it does not hit any enemies, it just sits on the ground like a mine.
Here is the psuedo code(no programming rules at all lol):
Make bullet(playerPositionX,playerPositionY,mouseX,mousey) as a object:
starter x and y = playerPostionX and playerPositionY
lookTowards a point(mouseX,mouseY)
goto the point(mouseX and mouseY) from the starter X and Y
movespeed is 20pixel per frame
So here is what i got in my game right now is:
The sketch script:
var player;
var enemy;
var bullet;
var score = 0;
function setup(){
createCanvas(600,600);
player = new Player();
enemy = new Enemy();
textSize(20);
}
function draw(){
clear();
background(51);
enemy.show();
enemy.moveToPlayer(player.x, player.y);
player.show();
player.MovePlayer();
if (bullet != undefined){
bullet.show();
bullet.toMouse();
if (dist(bullet.x,bullet.y,enemy.x,enemy.y) <= enemy.r){
enemy = new Enemy();
score += 100;
bullet = undefined;
}
}
fill(255);
text(score,500,500,100,100)
}
function mousePressed(){
//if (enemy.clicked(mouseX,mouseY)){
bullet = new Bullet(mouseX,mouseY,player.x,player.y);
//enemy = new Enemy();
//}
}
The bullet script:
function Bullet(X,Y,PX,PY){
this.speed = 20;
this.x = PX;
this.y = PY;
this.r = 5;
this.show = function(){
fill(255,255,0);
stroke(128,128,0);
circle(this.x,this.y,this.r);
}
this.toMouse = function(){
if (Y < this.y){
this.y += -1*this.speed;
} else if (Y > this.y) {
this.y += 1*this.speed;
}
if (X < this.x){
this.x += -1*this.speed;
} else if (X > this.x){
this.x += 1*this.speed;
}
}
}
The enemy script:
function Enemy(){
this.r = 25;
this.x = 0+this.r;
this.y = 0+this.r;
this.chance = random(0,1);
console.log(this.chance);
if (this.chance <= 0.10){
this.speed = 3;
this.r = 15;
this.red = 0;
this.green = 0;
this.blue = 255;
} else {
this.speed = 2;
this.red = 255;
this.green = 0;
this.blue = 0;
}
this.show = function(){
fill(this.red,this.green,this.blue);
stroke(128,0,0);
circle(this.x,this.y,this.r);
}
this.moveToPlayer = function(playerX,playerY){
if (playerY < this.y){
this.y += -1*this.speed;
} else if (playerY > this.y) {
this.y += 1*this.speed;
}
if (playerX < this.x){
this.x += -1*this.speed;
} else if (playerX > this.x){
this.x += 1*this.speed;
}
}
/*
this.clicked = function(mX,mY){
if (dist(mX,mY,this.x,this.y) <= this.r){
return true;
}
return false;
}
*/
}
The player script:
function Player(){
this.x = width/2;
this.y = height/2;
this.r = 20;
this.speed = 4;
this.show = function(){
fill(0,255,0);
stroke(0,128,0);
circle(this.x,this.y,this.r);
}
this.moveY = function(number){
this.y += (number*this.speed);
}
this.moveX = function(number){
this.x += (number*this.speed);
}
this.MovePlayer = function(){
if (keyIsDown(UP_ARROW)){
if (this.y + (-1*20) > 0)
this.moveY(-1);
}
if (keyIsDown(DOWN_ARROW)){
if (this.y + (1*20) < height)
this.moveY(1);
}
if (keyIsDown(LEFT_ARROW)){
if (this.x + (-1*20) > 0)
this.moveX(-1);
}
if (keyIsDown(RIGHT_ARROW)){
if (this.x + (1*20) < width)
this.moveX(1);
}
}
}
The html file has everything it needs
Thanks for advance!
var player;
var enemy;
var bullet;
var score = 0;
function setup(){
createCanvas(600,600);
player = new Player();
enemy = new Enemy();
textSize(20);
}
function draw(){
clear();
background(51);
enemy.show();
enemy.moveToPlayer(player.x, player.y);
player.show();
player.MovePlayer();
if (bullet != undefined){
bullet.show();
bullet.toMouse();
if (dist(bullet.x,bullet.y,enemy.x,enemy.y) <= enemy.r){
enemy = new Enemy();
score += 100;
bullet = undefined;
}
}
fill(255);
text(score,500,500,100,100)
}
function mousePressed(){
//if (enemy.clicked(mouseX,mouseY)){
bullet = new Bullet(mouseX,mouseY,player.x,player.y);
//enemy = new Enemy();
//}
}
function Bullet(X,Y,PX,PY){
this.speed = 20;
this.x = PX;
this.y = PY;
this.r = 5;
this.show = function(){
fill(255,255,0);
stroke(128,128,0);
circle(this.x,this.y,this.r);
}
this.toMouse = function(){
if (Y < this.y){
this.y += -1*this.speed;
} else if (Y > this.y) {
this.y += 1*this.speed;
}
if (X < this.x){
this.x += -1*this.speed;
} else if (X > this.x){
this.x += 1*this.speed;
}
}
}
function Enemy(){
this.r = 25;
this.x = 0+this.r;
this.y = 0+this.r;
this.chance = random(0,1);
console.log(this.chance);
if (this.chance <= 0.10){
this.speed = 3;
this.r = 15;
this.red = 0;
this.green = 0;
this.blue = 255;
} else {
this.speed = 2;
this.red = 255;
this.green = 0;
this.blue = 0;
}
this.show = function(){
fill(this.red,this.green,this.blue);
stroke(128,0,0);
circle(this.x,this.y,this.r);
}
this.moveToPlayer = function(playerX,playerY){
if (playerY < this.y){
this.y += -1*this.speed;
} else if (playerY > this.y) {
this.y += 1*this.speed;
}
if (playerX < this.x){
this.x += -1*this.speed;
} else if (playerX > this.x){
this.x += 1*this.speed;
}
}
/*
this.clicked = function(mX,mY){
if (dist(mX,mY,this.x,this.y) <= this.r){
return true;
}
return false;
}
*/
}
function Player(){
this.x = width/2;
this.y = height/2;
this.r = 20;
this.speed = 4;
this.show = function(){
fill(0,255,0);
stroke(0,128,0);
circle(this.x,this.y,this.r);
}
this.moveY = function(number){
this.y += (number*this.speed);
}
this.moveX = function(number){
this.x += (number*this.speed);
}
this.MovePlayer = function(){
if (keyIsDown(UP_ARROW)){
if (this.y + (-1*20) > 0)
this.moveY(-1);
}
if (keyIsDown(DOWN_ARROW)){
if (this.y + (1*20) < height)
this.moveY(1);
}
if (keyIsDown(LEFT_ARROW)){
if (this.x + (-1*20) > 0)
this.moveX(-1);
}
if (keyIsDown(RIGHT_ARROW)){
if (this.x + (1*20) < width)
this.moveX(1);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.js"></script>
Create an array of bullets rather than a single bullet and append a new bullet to the array, if the mouse button is pressed:
var bullets = [];
function mousePressed(){
if (mouseX != player.x || mouseY != player.y ) {
bullets.push( new Bullet(mouseX,mouseY,player.x,player.y) )
}
}
Use p5.Vector to calculate the normalized direction from the player position to the mouse position in thee class [Bullet]. This is defines the moving direction of the Bullet, which can be used in toMouse, to update the position of the Bullet object.
Further add method onScreen, which verifies if the Bullet is still in bounds of the screen:
function Bullet(X,Y,PX,PY){
this.speed = 2;
this.x = PX;
this.y = PY;
this.dir = createVector(X-PX, Y-PY).normalize()
this.r = 5;
this.show = function(){
fill(255,255,0);
stroke(128,128,0);
circle(this.x,this.y,this.r);
}
this.toMouse = function() {
this.x += this.dir.x * this.speed;
this.y += this.dir.y * this.speed;
}
this.onScreen = function() {
return this.x > -this.r && this.x < width+this.r &&
this.y > -this.r && this.y < height+this.r;
}
}
Traverse the bullets in draw. Check if a bullet has hit the enemy or has left the screen. Keep the remaining bullets for the next run of draw:
let keepbullets = []
let anyhit = false;
for (let i=0; i < bullets.length; ++ i) {
bullets[i].toMouse();
let hit = dist(bullets[i].x, bullets[i].y, enemy.x, enemy.y) <= enemy.r;
anyhit = anyhit || hit
if (!hit && bullets[i].onScreen()) {
keepbullets.push(bullets[i]);
bullets[i].show();
}
}
bullets = keepbullets;
if (anyhit) {
enemy = new Enemy();
score += 100;
}
See the example, where I applied the suggestions to the original code from the question. Note, I've slowed down the speed of the bullets extremely, to make the effect of multiple bullets visible:
var player;
var enemy;
var bullets = [];
var score = 0;
function setup(){
createCanvas(600,600);
player = new Player();
enemy = new Enemy();
textSize(20);
}
function draw(){
clear();
background(51);
enemy.show();
enemy.moveToPlayer(player.x, player.y);
player.show();
player.MovePlayer();
let keepbullets = []
let anyhit = false;
for (let i=0; i < bullets.length; ++ i) {
bullets[i].toMouse();
let hit = dist(bullets[i].x, bullets[i].y, enemy.x, enemy.y) <= enemy.r;
anyhit = anyhit || hit
if (!hit && bullets[i].onScreen()) {
keepbullets.push(bullets[i]);
bullets[i].show();
}
}
bullets = keepbullets;
if (anyhit) {
enemy = new Enemy();
score += 100;
}
fill(255);
text(score,500,500,100,100)
}
function mousePressed(){
if (mouseX != player.x || mouseY != player.y ) {
bullets.push( new Bullet(mouseX,mouseY,player.x,player.y) )
}
}
function Bullet(X,Y,PX,PY){
this.speed = 2;
this.x = PX;
this.y = PY;
this.dir = createVector(X-PX, Y-PY).normalize()
this.r = 5;
this.show = function(){
fill(255,255,0);
stroke(128,128,0);
circle(this.x,this.y,this.r);
}
this.toMouse = function() {
this.x += this.dir.x * this.speed;
this.y += this.dir.y * this.speed;
}
this.onScreen = function() {
return this.x > -this.r && this.x < width+this.r &&
this.y > -this.r && this.y < height+this.r;
}
}
function Enemy(){
this.r = 25;
this.x = 0+this.r;
this.y = 0+this.r;
this.chance = random(0,1);
console.log(this.chance);
if (this.chance <= 0.10){
this.speed = 3;
this.r = 15;
this.red = 0;
this.green = 0;
this.blue = 255;
} else {
this.speed = 2;
this.red = 255;
this.green = 0;
this.blue = 0;
}
this.show = function(){
fill(this.red,this.green,this.blue);
stroke(128,0,0);
circle(this.x,this.y,this.r);
}
this.moveToPlayer = function(playerX,playerY){
if (playerY < this.y){
this.y += -1*this.speed;
} else if (playerY > this.y) {
this.y += 1*this.speed;
}
if (playerX < this.x){
this.x += -1*this.speed;
} else if (playerX > this.x){
this.x += 1*this.speed;
}
}
/*
this.clicked = function(mX,mY){
if (dist(mX,mY,this.x,this.y) <= this.r){
return true;
}
return false;
}
*/
}
function Player(){
this.x = width/2;
this.y = height/2;
this.r = 20;
this.speed = 4;
this.show = function(){
fill(0,255,0);
stroke(0,128,0);
circle(this.x,this.y,this.r);
}
this.moveY = function(number){
this.y += (number*this.speed);
}
this.moveX = function(number){
this.x += (number*this.speed);
}
this.MovePlayer = function(){
if (keyIsDown(UP_ARROW)){
if (this.y + (-1*20) > 0)
this.moveY(-1);
}
if (keyIsDown(DOWN_ARROW)){
if (this.y + (1*20) < height)
this.moveY(1);
}
if (keyIsDown(LEFT_ARROW)){
if (this.x + (-1*20) > 0)
this.moveX(-1);
}
if (keyIsDown(RIGHT_ARROW)){
if (this.x + (1*20) < width)
this.moveX(1);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.js"></script>
I'm new to programming and I tried to make a game. You move a red block and when you hit a green block the you go back to (0,0) and the green block goes to a random location.
Now my question is how do I put a score counter in the game when I hit the green block that it counts +1.
var myGamePiece;
var myObstacle;
function startGame() {
myGamePiece = new component(40, 40, "red", 0, 0);
myObstacle = new component(40, 40, "green", Math.floor((Math.random() *
560) +
0), Math.floor((Math.random() * 360) + 0));
myGameArea.start();
}
var myGameArea = {
canvas: document.createElement("canvas"),
start: function() {
this.canvas.width = 600;
this.canvas.height = 400;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
},
clear: function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop: function() {
clearInterval(this.interval);
}
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.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;
}
}
function updateGameArea() {
if (myGamePiece.crashWith(myObstacle)) {
return startGame();
} else {
myGameArea.clear();
myObstacle.update();
myGamePiece.x += myGamePiece.speedX;
myGamePiece.y += myGamePiece.speedY;
myGamePiece.update();
if (myGamePiece.x >= 580) {
myGamePiece.x -= 20;
}
if (myGamePiece.x <= -20) {
myGamePiece.x += 20;
}
if (myGamePiece.y <= -20) {
myGamePiece.y += 20;
}
if (myGamePiece.y >= 380) {
myGamePiece.y -= 20;
}
}
}
function anim(e) {
if (e.keyCode == 39) {
myGamePiece.speedX = 1;
myGamePiece.speedY = 0;
}
if (e.keyCode == 37) {
myGamePiece.speedX = -1;
myGamePiece.speedY = 0;
}
if (e.keyCode == 40) {
myGamePiece.speedY = 1;
myGamePiece.speedX = 0;
}
if (e.keyCode == 38) {
myGamePiece.speedY = -1;
myGamePiece.speedX = 0;
}
if (e.keyCode == 32) {
myGamePiece.speedY = 0;
myGamePiece.speedX = 0;
}
}
document.onkeydown = anim;
window.onload=startGame();
canvas {
border: 1px solid #d3d3d3;
background-color: #f1f1f1;
}
<button onmousedown="anim(e)" onmouseup="clearmove()" ontouchstart="moveup()">Start</button>
<br><br>
<p>press start to start
<br> use the buttons ↑ ↓ → ← on your keyboard to move stop with the space</p>
Changes
Added an <output> tag to display score.
Redefined event handlers/listeners
Details on changes are commented in demo
Demo
// Reference output#score
var score = document.getElementById('score');
// Declare points
var points = 0;
var myGamePiece;
var myObstacle;
function startGame() {
myGamePiece = new component(40, 40, "red", 0, 0);
myObstacle = new component(40, 40, "green", Math.floor((Math.random() *
560) +
0), Math.floor((Math.random() * 360) + 0));
myGameArea.start();
}
var myGameArea = {
canvas: document.createElement("canvas"),
start: function() {
this.canvas.width = 600;
this.canvas.height = 400;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
},
clear: function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop: function() {
clearInterval(this.interval);
}
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.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;
}
}
function updateGameArea() {
if (myGamePiece.crashWith(myObstacle)) {
// Convert points to a real number
points = parseInt(points, 10);
// Increment points
points++;
// Set output#score value to points
score.value = points;
return startGame();
} else {
myGameArea.clear();
myObstacle.update();
myGamePiece.x += myGamePiece.speedX;
myGamePiece.y += myGamePiece.speedY;
myGamePiece.update();
if (myGamePiece.x >= 580) {
myGamePiece.x -= 20;
}
if (myGamePiece.x <= -20) {
myGamePiece.x += 20;
}
if (myGamePiece.y <= -20) {
myGamePiece.y += 20;
}
if (myGamePiece.y >= 380) {
myGamePiece.y -= 20;
}
}
}
function anim(e) {
if (e.keyCode == 39) {
myGamePiece.speedX = 1;
myGamePiece.speedY = 0;
}
if (e.keyCode == 37) {
myGamePiece.speedX = -1;
myGamePiece.speedY = 0;
}
if (e.keyCode == 40) {
myGamePiece.speedY = 1;
myGamePiece.speedX = 0;
}
if (e.keyCode == 38) {
myGamePiece.speedY = -1;
myGamePiece.speedX = 0;
}
if (e.keyCode == 32) {
myGamePiece.speedY = 0;
myGamePiece.speedX = 0;
}
}
/* Set on click handler
|| When event occurs call startGame() / exclude
|| parenthesis
*/
document.onclick = startGame;
/* Register keydown event
|| When event occurs call anim() / exclude parenthesis
*/
document.addEventListener('keydown', anim, false);
/* When a callback is a named function / exclude the
|| parenthesis
*/
window.onload = startGame;
canvas {
border: 1px solid #d3d3d3;
background-color: #f1f1f1;
}
button {
font: inherit;
}
<br><br>
<button id='start'>Start</button>
<br><br>
<label for='score'>Score: </label>
<output id='score'>0</output>
<br><br>
<p>Click <kbd>Start</kbd> button</p>
<p>Use the buttons ↑ ↓ → ← on your keyboard to move stop with the spacebar.</p>
add
var chrashed = 0;
and use
if (myGamePiece.crashWith(myObstacle)) {
crashed++;
showCrashed;
return startGame();
}
https://jsfiddle.net/mplungjan/m4w3ahj1/
I'm trying to make a brick game with a ball and a player (platform). If the ball hits the player, it should go off in the other direction like ping pong. However, it's not detecting the collision.
Here's the code
html:
<canvas id="canvas" width= "400" height= "400"></canvas>
css:
#canvas{border:1px solid black}
Js:
var width = 400
var height = 400
var drawRect = function (x, y) {
ctx.fillRect(x, y, 30, 5)
};
// The Ball constructor
var Player = function () {
this.x = 395
this.y = 395
this.xSpeed = 5;
this.ySpeed = 0;
};
// Update the ball's position based on its speed
Player.prototype.move = function () {
this.x += this.xSpeed;
this.y += this.ySpeed;
if (this.x < 0) {
this.x = width;
} else if (this.x > width) {
this.x = 0;
} else if (this.y < 0) {
this.y = height;
} else if (this.y > height) {
this.y = 0;
}
};
// Draw the ball at its current position
Player.prototype.draw = function () {
drawRect(this.x, this.y);
};
// Set the ball's direction based on a string
Player.prototype.setDirection = function (direction) {
if (direction === "left") {
this.xSpeed = -5;
this.ySpeed = 0;
} else if (direction === "right") {
this.xSpeed = 5;
this.ySpeed = 0;
} else if (direction === "stop") {
this.xSpeed = 0;
this.ySpeed = 0;
}
};
// Create the ball object
var player = new Player();
// An object to convert keycodes into action names
var keyActions = {
32: "stop",
37: "left",
38: "up",
39: "right",
40: "down"
};
// The keydown handler that will be called for every keypress
$("html").keydown(function (event) {
var direction = keyActions[event.keyCode];
player.setDirection(direction);
});
var Ball = function () {
this.x = 100;
this.y = 100;
this.xSpeed = -2
this.ySpeed = 3;
};
var circle = function (x, y, radius, fillCircle) {
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2, false)
if (fillCircle) {
ctx.fill();
} else {
ctx.stroke();
}
}
Ball.prototype.move = function () {
this.x += this.xSpeed
this.y += this.ySpeed
};
Ball.prototype.draw = function () {
circle(this.x, this.y, 3, true);
};
Ball.prototype.checkCollision = function () {
if (this.x < 0 || this.x > 400) {
this.xSpeed = -this.xSpeed
}
if (this.y < 0) {
this.ySpeed = -this.ySpeed
}
};
Ball.prototype.checkCollisionPlayer = function () {
if (this.x === Player.x || this.y === player.y) {
this.ySpeed = -this.ySpeed
this.xSpeed = -this.xSpeed
}
}
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
setInterval(function () {
ctx.clearRect(0, 0, 400, 400);
player.draw();
player.move();
ball.draw();
ball.move();
ball.checkCollision();
ball.checkCollisionPlayer();
}, 40);
var ball = new Ball();
Thanks for your support. :)
I've added a simple box collision and update the classes to have the box dimensions of the ball and player. Remember that the ball box has to adjust for radius offset.
update
The kind of collision detection needed for the boxes you have to know side or corner that was hit. I updated the example as a starting point for this but it's needs to have the corners added and I also don't know the optimal detection. The blocks are setup for testing. I hope this helps.
var width = 400
var height = 400
function Brick(x, y, w, h, color) {
this.x = x;
this.y = y;
this.color = color;
this.w = w;
this.h = h;
this.hits = 0;
}
Brick.prototype.draw = function() {
ctx.save();
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.w, this.h);
ctx.fillStyle = "white";
ctx.fillText(this.hits, this.x + 2, this.y + 10);
ctx.restore();
};
var bricks = [
new Brick(80, 120, 15, 15, 'red'),
new Brick(220, 90, 15, 15, 'blue'),
new Brick(340, 100, 50, 20, 'green')
];
// The Ball constructor
var Player = function() {
this.x = 395
this.y = 395
this.xSpeed = 5;
this.ySpeed = 0;
this.w = 30;
this.h = 5;
};
// Update the ball's position based on its speed
Player.prototype.move = function() {
this.x += this.xSpeed;
this.y += this.ySpeed;
if (this.x < 0) {
this.x = width;
} else if (this.x > width) {
this.x = 0;
} else if (this.y < 0) {
this.y = height;
} else if (this.y > height) {
this.y = 0;
}
};
// Draw the ball at its current position
Player.prototype.draw = function() {
ctx.fillRect(this.x, this.y, this.w, this.h);
};
// Set the ball's direction based on a string
Player.prototype.setDirection = function(direction) {
if (direction === "left") {
this.xSpeed = -5;
this.ySpeed = 0;
} else if (direction === "right") {
this.xSpeed = 5;
this.ySpeed = 0;
} else if (direction === "stop") {
this.xSpeed = 0;
this.ySpeed = 0;
}
};
// Create the ball object
var player = new Player();
// An object to convert keycodes into action names
var keyActions = {
32: "stop",
37: "left",
38: "up",
39: "right",
40: "down"
};
// The keydown handler that will be called for every keypress
$("html").keydown(function(event) {
var direction = keyActions[event.keyCode];
player.setDirection(direction);
});
var Ball = function() {
this.x = 100;
this.y = 100;
this.xSpeed = -2
this.ySpeed = 3;
this.radius = 3;
};
var circle = function(x, y, radius, fillCircle) {
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2, false)
if (fillCircle) {
ctx.fill();
} else {
ctx.stroke();
}
}
Ball.prototype.move = function() {
this.x += this.xSpeed
this.y += this.ySpeed
if ((this.y + this.radius) > ctx.canvas.height) {
// floor to ceiling
this.y = 0;
}
};
Ball.prototype.draw = function() {
circle(this.x, this.y, this.radius, true);
};
Ball.prototype.getBox = function() {
return {
x: this.x - this.radius,
y: this.y - this.radius,
w: this.radius * 2,
h: this.radius * 2
};
};
Ball.prototype.checkCollision = function() {
if (this.x < 0 || this.x > 400) {
this.xSpeed = -this.xSpeed
}
if (this.y < 0) {
this.ySpeed = -this.ySpeed
} else {
var boxA = this.getBox();
switch (boxCollide(boxA, player)) {
case 1:
case 3:
this.ySpeed = -this.ySpeed;
break;
case 2:
case 4:
this.xSpeed = -this.xSpeed;
break;
}
}
};
// does box a collide with box b
// box = {x:num,y:num,w:num,h:num}
function boxCollide(a, b) {
var ax2 = a.x + a.w;
var ay2 = a.y + a.h;
var bx2 = b.x + b.w;
var by2 = b.y + b.h;
// simple hit true, false
//if (ax2 < b.x || a.x > bx2 || ay2 < b.y || a.y > by2) return false;
// return true
var xInRange = (a.x >= b.x && a.x <= bx2 || ax2 >= b.x && ax2 <= bx2);
var yInRange = (a.y >= b.y && a.y <= by2 || ay2 >= b.y && ay2 <= by2);
// Clockwise hit from top 1,2,3,4 or -1
if (ay2 > b.y && a.y < by2 && xInRange) return 1; // A hit the top of B
if (a.x < bx2 && ax2 > b.x && yInRange) return 2; // A hit the right of B
if (a.y < by2 && ay2 > b.y && xInRange) return 3; // A hit the bottom of B
if (ax2 > b.x && a.x < bx2 && yInRange) return 4; // A hit the right of B
return -1; // nohit
}
Ball.prototype.checkCollisionPlayer = function() {
if (this.x === Player.x || this.y === player.y) {
this.ySpeed = -this.ySpeed
this.xSpeed = -this.xSpeed
}
}
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
setInterval(function() {
ctx.clearRect(0, 0, 400, 400);
player.draw();
player.move();
ball.draw();
ball.move();
ball.checkCollision();
ball.checkCollisionPlayer();
var boxA = ball.getBox();
for (var i = 0; i < bricks.length; i++) {
switch (boxCollide(boxA, bricks[i])) {
case 1:
ball.y = bricks[i].y - ball.radius - 1;
ball.ySpeed = -ball.ySpeed;
bricks[i].hits++;
break;
case 3:
ball.y = bricks[i].y + ball.radius + bricks[i].h + 1;
ball.ySpeed = -ball.ySpeed;
bricks[i].hits++;
break;
case 2:
ball.x = bricks[i].x + ball.radius + bricks[i].w + 1;
ball.xSpeed = -ball.xSpeed;
bricks[i].hits++;
break;
case 4:
ball.x = bricks[i].x - ball.radius - 1;
ball.xSpeed = -ball.xSpeed;
bricks[i].hits++;
break;
}
bricks[i].draw();
}
},
40);
var ball = new Ball();
#canvas {
border: 1px solid black
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width="400" height="400"></canvas>