I`m trying to make a jump system in processing.js and its done, but not quite what I wanted. The thing is that like this, the jump height depends on how long the key is pressed. What I wanted is the same height regardless how long the key is pressed.
Here is my code:
var keys = [];
void keyPressed() {
keys[keyCode] = true;
};
void keyReleased() {
keys[keyCode] = false;
};
var Player = function(x, y) {
this.x = x;
this.y = y;
this.g = 0;
this.vel = 2;
this.jumpForce = 7;
this.jump = false;
};
Player.prototype.draw = function() {
fill(255,0,0);
noStroke();
rect(this.x, this.y, 20, 20);
};
Player.prototype.move = function() {
if(this.y < ground.y) {
this.y += this.g;
this.g += 0.5;
this.jump = false;
}
if(keys[RIGHT]) {
this.x += this.vel;
}
if(keys[LEFT]) {
this.x -= this.vel;
}
//preparing to jump
if(keys[UP] && !this.jump) {
this.jump = true;
}
// if jump is true, than the ball jumps... after, the gravity takes place pulling the ball down...
if(this.jump) {
this.y -= this.jumpForce;
}
};
Player.prototype.checkHits = function() {
if(this.y+20 > ground.y) {
this.g = 0;
this.y = ground.y-20;
jump = false;
}
};
Var Ground = function(x, y, label) {
this.x = x;
this.y = y;this.label = label;
};
Ground.prototype.draw = function() {
fill(0);
rect(0, 580, width, 20);
};
var player = new Player(width/2, height/2);
var ground = new Ground(0, 580, "g");
void draw() {
background(255,255,255);
player.draw();
player.move();
player.checkHits();
ground.draw();
}
Any help would be aprreciated.
What are you doing here is like: "If this(the Player) isn't touching the ground then, if (in addition) key UP is pressed, jump!". So it will allow the player jumping even if he is in the air... increasing the jump height
You should do something like: "if player is touching the ground allow to jump (if key UP pressed), otherwise you are already jumping!".
Something like this:
if(this.y < ground.y) {
this.y += this.g;
this.g += 0.5;
this.jump = true;
}
else{
this.jump = false;
}
if(keys[UP] && !this.jump) {
this.jump = true;
this.y -= this.jumpForce;
}
Related
My game components won't draw onto the canvas after adding if/else statement.
The statement only checks if the game piece hit the game obstacle.
I tried changing attributes and rewrite some functions but it seems the problem hasn't been fixed.
Whenever I remove the if/else function, the components draw.
Here is part of the code that holds that if/else function:
if(gamePieceBorder.crashGame(gameObstacle) || gamePieceRed.crashGame(gameObstacle))
{
gameArea.stop();
}
else
{
obstacle.update();
gamePieceBorder.pos();
gamePieceBorder.move();
gamePieceBorder.update();
gamePieceRed.pos();
gamePieceRed.move();
gamePieceRed.update();
gameArea.clear();
}
For me not pasting an entire code, here is the pastebin link to the code: https://pastebin.com/HuiR7r7D
How can I get the components to draw? If someone fixes the code, what was the issue? I am not an expert at javascript but only a beginner.
There are several problems:
window.EventListener should be window.addEventListener
keyup and keydown should have no upper case letters
gameObstacle in that if is undefined (should be obstacle probably)
clear method should be called before drawing, not after it
Here is the corrected script: https://pastebin.com/bXpQ2qvB
//-----------------------------------------Variables
var gamePieceRed;
var gamePieceBorder;
var gameObstacle;
//-----------------------------------------
//-----------------------------------------Main game function
function startGame()
{
gamePieceRed = new component(22, 22, "rgb(255, 132, 156)", 10, 120);
gamePieceBorder = new component(24, 24, "black", 9, 119);
obstacle = new component(10, 200, "rgb(64, 0 ,12)", 300, 120)
gameArea.start();
}
//-----------------------------------------
//-----------------------------------------Creating game area and applying controls
var gameArea =
{
canvas : document.createElement("canvas"), start : function()
{
this.canvas.width = 510;
this.canvas.height = 280;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(gameUpdate, 20);
window.addEventListener("keydown", function (e)
{
gameArea.keys = (gameArea.keys || []);
gameArea.keys[e.keyCode] = true;
}, true)
window.addEventListener("keyup", function (e)
{
gameArea.keys[e.keyCode] = false;
}, true)
},
clear : function()
{
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop : function()
{
clearInterval(this.interval);
},
keyboard: function() {
if (this.keys) {
if (this.keys[37]) {gamePieceBorder.speedX = gamePieceRed.speedX = -2;}
else if (this.keys[39]) {gamePieceBorder.speedX = gamePieceRed.speedX = 2;}
else {gamePieceBorder.speedX = gamePieceRed.speedX = 0;}
if (this.keys[38]) {gamePieceBorder.speedY = gamePieceRed.speedY = -2;}
else if (this.keys[40]) {gamePieceBorder.speedY = gamePieceRed.speedY = 2;}
else {gamePieceBorder.speedY = gamePieceRed.speedY = 0;}
}
}
}
//-----------------------------------------
//-----------------------------------------Game component
function component(width, height, color, x, y)
{
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.speedX = 0;
this.speedY = 0;
this.update = function()
{
ctx = gameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height)
}
this.move = function()
{
this.x += this.speedX;
this.y += this.speedY;
}
this.crashGame = function(obj)
{
var left = this.x;
var right = this.x + (this.width);
var top = this.y;
var bottom = this.y + (this.height);
var otherLeft = obj.x;
var otherRight = obj.x + (obj.width);
var otherTop = obj.y;
var otherBottom = obj.y + (obj.height);
var crash = true;
if (bottom < otherTop || top > otherBottom || right < otherLeft || left > otherRight)
{
crash = false;
}
return crash;
}
}
//-----------------------------------------
//-----------------------------------------Game area updater
function gameUpdate()
{
if(gamePieceBorder.crashGame(obstacle) || gamePieceRed.crashGame(obstacle))
{
gameArea.stop();
}
else
{
gameArea.clear();
obstacle.update();
gameArea.keyboard();
gamePieceBorder.move();
gamePieceBorder.update();
gamePieceRed.move();
gamePieceRed.update();
}
}
//-----------------------------------------
<html>
<style>
canvas
{
border: 1px solid #d3d3d3;
background-image: url("https://ak0.picdn.net/shutterstock/videos/22492090/thumb/1.jpg");
}
</style>
<body onload = "startGame()">
</body>
</html>
In fact, I'm making a background which has to kinda illustrate "influence".
I tried to make this with particles, generated from a given point on the screen, which are moving toward a random direction, and which blast after some lifetime they have. So the problem is, I succeeded some way to do it, but it's really slow. about 400 generators placed, and the browser starts to lag, and the thing is i need at least 400 of these. So is there anyway to optimise what I did?
Link on this pen.
my particle:
class Particle {
constructor(radius,speed,lifetime,aoe) {
this.speed = speed;
this.life = lifetime;
this.aoe = aoe;
}
throw() {
var r = random(TWO_PI);
var dx = cos(r);
var dy = sin(r);
var speedX = this.speed*dx;
var speedY = this.speed*dy;
return [speedX,speedY];
}
display(rootX,rootY,x,y) {
line(rootX,rootY,x,y);
}
blast(rootX,rootY,x,y) {
line(rootX,rootY,x,y);
ellipse(x,y,this.aoe,this.aoe);
}
}
and here's the generator:
class ParticleGenerator {
constructor(x,y,frequency, particle) {
this.x = x;
this.y = y;
this.f = frequency;
this.p = particle;
this.pX = this.x;
this.pY = this.y;
this.state = 0;
this.wait = 0;
this.dir = this.p.throw();
}
travel(sX,sY) {
this.pX += sX;
this.pY += sY;
}
activate() {
var d = (dist(this.x,this.y,this.pX,this.pY)/this.p.speed)/this.p.life;
if(this.state == 0)
this.dir = this.p.throw();
if (this.state < this.p.life) {
stroke(255,0,0);
fill(11)
this.travel(this.dir[0],this.dir[1]);
this.p.display(this.x,this.y,this.pX,this.pY);
this.state++;
}
if (this.state == this.p.life && this.wait < this.f) {
stroke(255,0,0,255-(this.wait*255)/this.f)
fill(255,0,0,255-(this.wait*255)/this.f);
this.p.blast(this.x,this.y,this.pX,this.pY);
this.wait++;
}
if (this.wait == this.f) {
this.state = 0;
this.wait = 0;
this.pX = this.x;
this.pY = this.y;
}
}
}
I created a collision detection between Snake and BasicEnemy. I created a for loop to make five different enemies but the collision detection doesn't get called on any of the enemies that were created from the for loop. The collision only works with the one BasicEnemy object. Why isn't collision function being called for all of the enemies inside the array? Thank you.
Sketch.js
var snake;
var food;
var basicEnemy;
var scl = 20;
var enemies = [];
function setup() {
createCanvas(600, 500);
snake = new Snake();
basicEnemy = new BasicEnemy();
//** CREATE FIVE ENEMIES **
for (var i = 0; i < 5; i++) {
enemies[i] = new BasicEnemy();
}
}
// **FUNCTION WHEN SNAKE HITS ENEMY**
function collision() {
console.log("hit!");
}
function draw() {
background(51);
//Draw snake
snake.update();
snake.show();
//Draw basicEnemy
basicEnemy.update();
basicEnemy.show();
//** LOOP THROUGH ENEMIES AND UPDATE AND SHOW **
for (var i = 0; i < enemies.length; i++) {
enemies[i].show();
enemies[i].update();
if (enemies[i].hits(snake)) {
collision();
}
}
}
function keyPressed() {
if (keyCode === UP_ARROW){
snake.dir(0, -1);
} else if (keyCode === DOWN_ARROW) {
snake.dir(0, 1);
} else if (keyCode === LEFT_ARROW) {
snake.dir(-1 , 0);
} else if (keyCode === RIGHT_ARROW) {
snake.dir(1 , 0);
}
}
BasicEnemy.js
function BasicEnemy() {
this.x = random(700);
this.y = random(700);
this.velX = 15;
this.velY = 15;
}
//** FUNCTION TO CHECK IF ENEMY AND SNAKE ARE IN THE SAME LOCATION **
this.hits = function (pos) {
var = d = dist(this.x, this.y, pos.x, pos.y);
if(d < 1) {
return true;
} else {
return false;
}
}
this.show = function () {
fill(255, 0, 100);
rect(this.x, this.y, scl, scl);
}
Snake.js
function Snake() {
this.x = 0;
this.y = 0;
this.xspeed = 1;
this.yspeed = 0;
this.update = function() {
this.x = this.x + this.xspeed * scl;
this.y = this.y + this.yspeed * scl;
this.x = constrain(this.x, 0, width - scl);
this.y = constrain(this.y, 0, height - scl);
}
this.show = function() {
fill(255);
rect(this.x, this.y, scl, scl);
}
this.dir = function (x , y) {
this.xspeed = x;
this.yspeed = y;
}
}
Because you're essentially checking for the distance between the top left corners of the snake and the enemy, this'll only return true, if they completely overlap.
Use an AABB collision detection instead:
return this.x + scl >= pos.x && this.x <= pos.x + scl && this.y + scl >= pos.y && this.y <= pos.y + scl;
This returns true, if the first rectangle contains the second rectangle.
MDN says:
One of the simpler forms of collision detection is between two rectangles that are axis aligned — meaning no rotation. The algorithm works by ensuring there is no gap between any of the 4 sides of the rectangles. Any gap means a collision does not exist.
I have the following problem: I'am trying to make a simple game in JavaScript. The idea of the game is to have a canvas, a ball bouncing inside and small pad going left to right to hit the ball. I've done it like this, and it works fine:
var canvasBg;
var contextBg;
var canvasBall;
var contextBall;
function Drawable() {
this.initialize = function(x,y) {
this.x = x;
this.y = y;
};
this.draw = function() {
};
}
function Ball() {
var dx = 2;
var dy = 2;
var radius = 5;
this.draw = function() {
contextBall.beginPath();
contextBall.clearRect(0,0,canvasBall.width,canvasBall.height);
contextBall.closePath();
contextBall.beginPath();
contextBall.fillStyle = "#0000ff";
contextBall.arc(this.x, this.y, radius, 0, Math.PI*2, true);
contextBall.closePath();
contextBall.fill();
// the code seems to stop here
if(this.x<0 || this.x>300)
dx = -dx;
if(this.y<0 || this.y>150)
dy = -dy;
if((this.x+radius)>pad.x && (this.x-radius)<(pad.x+50) && (this.y+radius)>pad.y && (this.y-radius)<(pad.y+10)) {
dy = -dy;
}
if(this.y>(pad.y-2) && this.y<(pad.y+12) && (this.x+radius)>pad.x && (this.x-radius)<(pad.x+50)) {
dx = -dx;
}
this.x += dx;
this.y += dy;
};
}
Ball.prototype = new Drawable();
KEY_CODES = {
37: 'left',
39: 'right',
};
KEY_STATUS = {};
for (code in KEY_CODES) {
KEY_STATUS[ KEY_CODES[ code ]] = false;
}
document.onkeydown = function(e) {
var keyCode = (e.keyCode) ? e.keyCode : e.charCode;
if (KEY_CODES[keyCode]) {
e.preventDefault();
KEY_STATUS[KEY_CODES[keyCode]] = true;
}
};
document.onkeyup = function(e) {
var keyCode = (e.keyCode) ? e.keyCode : e.charCode;
if (KEY_CODES[keyCode]) {
e.preventDefault();
KEY_STATUS[KEY_CODES[keyCode]] = false;
}
};
function Pad() {
var hSpeed = 5;
this.padWidth = 50;
this.padHeight = 10;
this.draw = function() {
contextBg.clearRect(0,0,canvasBg.width,canvasBg.height);
contextBg.fillStyle = "#ffffff";
contextBg.fillRect(this.x,this.y,this.padWidth,this.padHeight);
};
this.move = function() {
if(KEY_STATUS.left || KEY_STATUS.right) {
contextBg.clearRect(0,0,canvasBg.width,canvasBg.height);
if(KEY_STATUS.left) {
this.x -= hSpeed;
if (this.x <= 0)
this.x = 0;
} else if (KEY_STATUS.right) {
this.x += hSpeed;
if (this.x >= 300-this.padWidth)
this.x = 300 - this.padWidth;
}
this.draw();
}
};
}
Pad.prototype = new Drawable();
function init() {
canvasBg = document.getElementById('display');
contextBg = this.canvasBg.getContext('2d');
canvasBall = document.getElementById('ball');
contextBall = this.canvasBall.getContext('2d');
ball = new Ball();
ball.initialize(10,10);
pad = new Pad();
pad.initialize(120,80);
setInterval(function(){animate();},30);
}
function animate() {
ball.draw();
pad.draw();
pad.move();
};
However, I decided to try to improve my code a bit, and i made a class GamePlay:
var game = new GamePlay();
function Drawable() {
this.initialize = function(x,y) {
this.x = x;
this.y = y;
};
this.draw = function() {
};
}
function Ball() {
var dx = 2;
var dy = 2;
var radius = 5;
this.draw = function() {
this.context.beginPath();
this.context.clearRect(0,0,this.canvas.width,this.canvas.height);
this.context.closePath();
this.context.beginPath();
this.context.fillStyle = "#0000ff";
this.context.arc(this.x, this.y, radius, 0, Math.PI*2, true);
this.context.closePath();
this.context.fill();
if(this.x<0 || this.x>300)
dx = -dx;
if(this.y<0 || this.y>150)
dy = -dy;
if((this.x+radius)>pad.x && (this.x-radius)<(pad.x+50) && (this.y+radius)>pad.y && (this.y-radius)<(pad.y+10)) {
dy = -dy;
}
if(this.y>(pad.y-2) && this.y<(pad.y+12) && (this.x+radius)>pad.x && (this.x-radius)<(pad.x+50)) {
dx = -dx;
}
this.x += dx;
this.y += dy;
};
}
Ball.prototype = new Drawable();
KEY_CODES = {
37: 'left',
39: 'right',
};
KEY_STATUS = {};
for (code in KEY_CODES) {
KEY_STATUS[ KEY_CODES[ code ]] = false;
}
document.onkeydown = function(e) {
var keyCode = (e.keyCode) ? e.keyCode : e.charCode;
if (KEY_CODES[keyCode]) {
e.preventDefault();
KEY_STATUS[KEY_CODES[keyCode]] = true;
}
};
document.onkeyup = function(e) {
var keyCode = (e.keyCode) ? e.keyCode : e.charCode;
if (KEY_CODES[keyCode]) {
e.preventDefault();
KEY_STATUS[KEY_CODES[keyCode]] = false;
}
};
function Pad() {
var hSpeed = 5;
this.padWidth = 50;
this.padHeight = 10;
this.draw = function() {
this.context.clearRect(0,0,this.canvas.width,this.canvas.height);
this.context.fillStyle = "#ffffff";
this.context.fillRect(this.x,this.y,this.padWidth,this.padHeight);
};
this.move = function() {
if(KEY_STATUS.left || KEY_STATUS.right) {
this.context.clearRect(0,0,this.canvas.width,this.canvas.height);
if(KEY_STATUS.left) {
this.x -= hSpeed;
if (this.x <= 0)
this.x = 0;
} else if (KEY_STATUS.right) {
this.x += hSpeed;
if (this.x >= 300-this.padWidth)
this.x = 300 - this.padWidth;
}
this.draw();
}
};
}
Pad.prototype = new Drawable();
function GamePlay() {
var ball;
var pad;
this.setUpGame = function() {
this.canvasBg = document.getElementById('display');
this.contextBg = this.canvasBg.getContext('2d');
this.canvasBall = document.getElementById('ball');
this.contextBall = this.canvasBall.getContext('2d');
Ball.prototype.canvas = this.canvasBall;
Ball.prototype.context = this.contextBall;
Pad.prototype.canvas = this.canvasBg;
Pad.prototype.context = this.contextBg;
ball = new Ball();
ball.initialize(10,10);
pad = new Pad();
pad.initialize(120,80);
};
var animate = function() {
ball.draw();
pad.draw();
pad.move();
};
this.startGame = function() {
setInterval(function(){animate();},30);
};
}
function init() {
game.setUpGame();
game.startGame();
}
BUT, it only draws a ball on its initializing coordinates and then seems to stop there. I tried to do some manual testing by putting alert() on certain points in code and I found out that it seems to stop in the middle of ball's draw method and skips calling pad.draw() and pad.move() in animate(). I don't know what is wrong, my guess that is something with prototypes. I am new to JavaScript and this prototype-based OOP is still a bit confusing to me. Thanks.
I've tried code and found next problems:
function init - hope it is called after html is fully loaded
Ball.draw function refers object pad, which is not defined in its context, use game.pad
var animate = function creates local "private" variable, change it to this.animate = function
in setInterval call proper function setInterval(function(){game.animate();},30);
var game = new GamePlay(); is called before GamePlay is defined, move this string below
after these changes it works without errors in console
I believe this is because of your miss-use of paths in your draw method.
First, you don't need to wrap .clearRect with .beginPath and .closePath.
Second, and what is likely causing your script to error is that you are using .fill after .closePathwhen you draw the circle. .fill should be used before .closePath and actually after using .fill you don't need to use .closePath as it will already close your path for you.
I'm having some trouble with Node Socket.IO
I have put all my code in pastebins
Server file
var io = require("socket.io").listen(1337);
io.set("log level", "0");
var particles = [];
var players = [];
var remove_loop;
var particle;
io.sockets.on("connection", function(socket) {
//connection
socket.emit("hello");
console.log("A new connection has been established");
//new player
socket.on("new_player", function() {
players.push(socket.id);
console.log("New player connected.");
console.log("ID: " + socket.id);
});
//new particle
socket.on("new_particle", function(data) {
particle = data;
socket.broadcast.emit("particles_data", particle);
});
});
Game file
window.onload = function() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//display settings
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
setInterval(function() {
if(canvas.width != window.innerWidth || canvas.height != window.innerHeight) {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
}, 1000);
//remove cursor
document.getElementById("canvas").style.cursor = "none";
//server connection
var socket = io.connect("http://localhost:1337");
//variables
var update_loop;
var draw_loop;
var local_player;
var mouse_x;
var mouse_y;
var remote_players;
var particles;
var remove_loop;
var explosion;
var background_color;
init();
function init() {
//initialize
local_player = new Player();
background_color = "000000";
explosion = true;
remote_players = [];
particles = [];
draw_loop = setInterval(function() { draw(); }, 10);
update_loop = setInterval(function() { update(); }, 10);
//server
socket.on("hello", function() {
socket.emit("new_player");
});
socket.on("particles_data", function(data) {
particles.push(data);
});
};
function update() {
for(var i = 0; i < particles.length; i++) {
particles[i].move();
}
};
function draw() {
//background_color
ctx.fillStyle = "#" + background_color;
ctx.fillRect(0, 0, canvas.width, canvas.height);
//remove particles
setInterval(function() {
if(!remove_loop) remove_loop = setInterval(function() {
setTimeout(function() {
if(particles.length > 0) {
particles.shift();
}
}, 1);
}, 20);
}, 10);
//particles
for(var i = 0; i < particles.length; i++) {
if(particles[i].x < canvas.width &&
particles[i].y < canvas.width) {
if(particles[i].x < canvas.width &&
particles[i].y < canvas.height) {
particles[i].draw(ctx);
}
}
}
}
function newParticle() {
socket.emit("new_particle", new Particle(local_player.x, local_player.y, local_player.color));
particles.push(new Particle(local_player.x, local_player.y, local_player.color));
};
//move mouse
canvas.onmousemove = function(event) {
if(!event) event = window.event;
local_player.x = event.pageX;
local_player.y = event.pageY;
newParticle();
};
//touch mouse (phones/tables)
canvas.onmousedown = function(event) {
if(!event) event = window.event;
local_player.x = event.pageX;
local_player.y = event.pageY;
newParticle();
}
};
Player file
function Player() {
this.x = 0;
this.y = 0;
this.color = Math.floor(Math.random() * 999999);
while (this.color < 100000) {
this.color = Math.floor(Math.random() * 999999);
}
};
Particle file
function Particle(x, y, color) {
this.start_x = x;
this.start_y = y;
this.speed = Math.floor(Math.random() * 3 + 1);
this.x = x;
this.y = y;
this.size = Math.floor(Math.random() * 3 + 1);
this.color = "#" + color;
this.direction = Math.floor(Math.random() * 8);
this.move = function() {
this.speedDecreaseChance = Math.random(Math.random() * 100);
//Chance that the particle loses it's velocity like you would
//see with real particles
if(this.speedDecreaseChance > 3) { this.speed -= 0.5 };
//It's important that they move -AWAY- from X and Y.
this.subDirection = Math.floor(Math.random() * 2);
if(this.direction == 0) { //upper left
if(this.subDirection == 0) {
this.x -= this.speed;
} else if(this.subDirection == 1) {
this.y -= this.speed;
}
} else if(this.direction == 1) { //bottom right
if(this.subDirection == 0) {
this.x += this.speed;
} else if(this.subDirection == 1) {
this.y += this.speed;
}
} else if(this.direction == 2) { //upper right
if(this.subDirection == 0) {
this.x += this.speed;
} else if(this.subDirection == 1) {
this.y -= this.speed;
}
} else if(this.direction == 3) { //bottom left
if(this.subDirection == 0) {
this.x -= this.speed;
} else if(this.subDirection == 1) {
this.y += this.speed;
}
} else if(this.direction == 4) { //left
this.x -= this.speed/1.5;
if(this.subDirection == 0) {
this.y -= this.speed;
} else if(this.subDirection == 1) {
this.y += this.speed;
}
} else if(this.direction == 5) { //up
this.y -= this.speed/1.5;
if(this.subDirection == 0) {
this.x -= this.speed;
} else if(this.subDirection == 1) {
this.x += this.speed;
}
} else if(this.direction == 6) { //right
this.x += this.speed/1.5;
if(this.subDirection == 0) {
this.y -= this.speed;
} else if(this.subDirection == 1) {
this.y += this.speed;
}
} else if(this.direction == 7) { //down
this.y += this.speed/1.5;
if(this.subDirection == 0) {
this.x -= this.speed;
} else if(this.subDirection == 1) {
this.x += this.speed;
}
}
};
this.draw = function(ctx) {
ctx.beginPath();
ctx.shadowColor = this.color;
ctx.shadowBlur = 8;
ctx.arc(this.x, this.y, this.size ,0 ,2*Math.PI);
ctx.fillStyle = this.color;
ctx.fill();
ctx.shadowBlur = 0;
};
};
Now the problem is that there's an error in my traffic between the server and all sockets.
What I want to do is make it possible that when one has particle objects to send them to the server and the server sends them to everyone except the original sender.
I did this through socket.broadcast.emit();
This went successful.
However when the objects arrive at the other sockets I get this error:
Uncaught TypeError: Object #<Object> has no method 'move'
Uncaught TypeError: Object #<Object> has no method 'draw'
For every particle object that exists at that moment.
If anyone knows why my objects lose their methods and would be so friendly to help a programmer in distress I'd be absolutely delighted :)
Thanks in advance!
From what I know Socket.IO expected JSON data as 2nd parameter for the emit function. JSON data format doesn't support function as values according to http://www.json.org/
You are sending a javascript object and expecting the object to be created from the json on a different client. This is not how Socket.IO communication works.
Instead of doing that you should send the data required to construct the object and use that to construct the object on the client.
You could do some thing like the following
Change this line
socket.emit("new_particle", new Particle(local_player.x, local_player.y, local_player.color));
to
socket.emit("new_particle", {x:local_player.x, y:local_player.y, color:local_player.color});
and then the event listener
socket.on("particles_data", function(data) {
particles.push(data);
});
to handle the creation of object from the data
socket.on("particles_data", function(data) {
particles.push(new Particle(data.x, data.y, data.color));
});
When an object is serialized to JSON, it loses all type information. This is what socket.io is transmitting.
var particle = new Particle(1, 2, 'ccc');
console.log(JSON.stringify(particle)); // {"start_x":1,"start_y":2,"speed":3,"x":1,"y":2,"size":3,"color":"#ccc","direction":5}
You can't tell if it's a particle or a monkey or something else.
When you receive this object, you need to convert it to a Particle first.
socket.on("particles_data", function(data) {
var particle = ...;
particles.push(particle);
});
You could define a constructor and create it again:
var particle = new Particle(data.x, data.y, data.color);
Or you could change its prototype:
var particle = $.extend(new Particle(), data); // here using jQuery helper method