Related
Using Adobe Animate HTML5 Canvas which employs Create.js/Easel.js.
I have the following code which drags an object around a circle.
Works Ok, but the object should only be moveable when the cursor is over the object; object being streakRotatorKnob.
var knob_X = 454;
var knob_Y = 175;
var radius = 80;
root.streakRotatorKnob.addEventListener("pressmove",moveF.bind(this));
function moveF(e){
var rads = Math.atan2(stage.mouseY-knob_Y,stage.mouseX-knob_X);
e.currentTarget.x = knob_X + radius * Math.cos(rads);
e.currentTarget.y = knob_Y + radius * Math.sin(rads);
stage.update();
}
I have tried the following but it's not working at all with the if statement:
var knob_X = 454;
var knob_Y = 175;
var radius = 80;
root.streakRotatorKnob.addEventListener("pressmove",moveF.bind(this));
function moveF(e){
if(stage.mouseY == root.streakRotatorKnob.y && stage.mouseX == root.streakRotatorKnob.x){
var rads = Math.atan2(stage.mouseY-knob_Y,stage.mouseX-knob_X);
e.currentTarget.x = knob_X + radius * Math.cos(rads);
e.currentTarget.y = knob_Y + radius * Math.sin(rads);
stage.update();
}
}
UPDATE
Based on Muhammed Maruf's answer below (the Adobe Animate version), the following works better by removing the line:
root.c.addEventListener("rollout", rollout);
So we just have:
stage.enableMouseOver();
var knob_X = 454;
var knob_Y = 169;
var radius = 90;
var root = this;
root.c.addEventListener("rollover", rollover);
//root.c.addEventListener("rollout", rollout);
function rollover(e)
{
console.log("rollover")
root.c.addEventListener("pressmove", moveF);
}
function rollout(e)
{
console.log("rollout")
root.c.removeEventListener("pressmove", moveF);
}
function moveF(e)
{
var rads = Math.atan2(stage.mouseY - knob_Y, stage.mouseX - knob_X);
e.currentTarget.x = knob_X + radius * Math.cos(rads);
e.currentTarget.y = knob_Y + radius * Math.sin(rads);
stage.update();
}
This is how I edited the code. I think you meant that.
stage.enableMouseOver();
var knob_X = canvas.width/2;
var knob_Y = canvas.height/2;
var radius = 90;
var root = this;
root.streakRotatorKnob.addEventListener("rollover", rollover);
root.streakRotatorKnob.addEventListener("rollout", rollout);
function rollover(e)
{
console.log("rollover")
root.streakRotatorKnob.addEventListener("pressmove", moveF);
}
function rollout(e)
{
console.log("rollout")
root.streakRotatorKnob.removeEventListener("pressmove", moveF);
}
function moveF(e)
{
var rads = Math.atan2(stage.mouseY - knob_Y, stage.mouseX - knob_X);
e.currentTarget.x = knob_X + radius * Math.cos(rads);
e.currentTarget.y = knob_Y + radius * Math.sin(rads);
stage.update();
}
(function (cjs, an) {
var p; // shortcut to reference prototypes
var lib={};var ss={};var img={};
lib.ssMetadata = [];
(lib.AnMovieClip = function(){
this.actionFrames = [];
this.ignorePause = false;
this.gotoAndPlay = function(positionOrLabel){
cjs.MovieClip.prototype.gotoAndPlay.call(this,positionOrLabel);
}
this.play = function(){
cjs.MovieClip.prototype.play.call(this);
}
this.gotoAndStop = function(positionOrLabel){
cjs.MovieClip.prototype.gotoAndStop.call(this,positionOrLabel);
}
this.stop = function(){
cjs.MovieClip.prototype.stop.call(this);
}
}).prototype = p = new cjs.MovieClip();
// symbols:
// helper functions:
function mc_symbol_clone() {
var clone = this._cloneProps(new this.constructor(this.mode, this.startPosition, this.loop, this.reversed));
clone.gotoAndStop(this.currentFrame);
clone.paused = this.paused;
clone.framerate = this.framerate;
return clone;
}
function getMCSymbolPrototype(symbol, nominalBounds, frameBounds) {
var prototype = cjs.extend(symbol, cjs.MovieClip);
prototype.clone = mc_symbol_clone;
prototype.nominalBounds = nominalBounds;
prototype.frameBounds = frameBounds;
return prototype;
}
(lib.Sembol1 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// Katman_1
this.shape = new cjs.Shape();
this.shape.graphics.f("#000000").s().p("AhuBuQgtguAAhAQAAg/AtguQAvguA/AAQBBAAAtAuQAuAuAAA/QAABAguAuQgtAuhBAAQg/AAgvgug");
this.timeline.addTween(cjs.Tween.get(this.shape).wait(1));
this._renderFirstFrame();
}).prototype = getMCSymbolPrototype(lib.Sembol1, new cjs.Rectangle(-15.6,-15.6,31.2,31.2), null);
// stage content:
(lib.index = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
this.actionFrames = [0];
this.isSingleFrame = false;
// timeline functions:
this.frame_0 = function() {
if(this.isSingleFrame) {
return;
}
if(this.totalFrames == 1) {
this.isSingleFrame = true;
}
stage.enableMouseOver();
var knob_X = canvas.width/2;
var knob_Y = canvas.height/2;
var radius = 90;
var root = this;
root.streakRotatorKnob.addEventListener("rollover", rollover);
root.streakRotatorKnob.addEventListener("rollout", rollout);
function rollover(e)
{
console.log("rollover")
root.streakRotatorKnob.addEventListener("pressmove", moveF);
}
function rollout(e)
{
console.log("rollout")
root.streakRotatorKnob.removeEventListener("pressmove", moveF);
}
function moveF(e)
{
var rads = Math.atan2(stage.mouseY - knob_Y, stage.mouseX - knob_X);
e.currentTarget.x = knob_X + radius * Math.cos(rads);
e.currentTarget.y = knob_Y + radius * Math.sin(rads);
stage.update();
}
}
// actions tween:
this.timeline.addTween(cjs.Tween.get(this).call(this.frame_0).wait(1));
// Katman_1
this.streakRotatorKnob = new lib.Sembol1();
this.streakRotatorKnob.name = "streakRotatorKnob";
this.streakRotatorKnob.setTransform(207.8,131.8);
this.timeline.addTween(cjs.Tween.get(this.streakRotatorKnob).wait(1));
this._renderFirstFrame();
}).prototype = p = new lib.AnMovieClip();
p.nominalBounds = new cjs.Rectangle(467.2,316.2,-243.79999999999998,-168.79999999999998);
// library properties:
lib.properties = {
id: '214D9CE6C84FD84795816AF703BF00E4',
width: 550,
height: 400,
fps: 24,
color: "#CCCCCC",
opacity: 1.00,
manifest: [],
preloads: []
};
// bootstrap callback support:
(lib.Stage = function(canvas) {
createjs.Stage.call(this, canvas);
}).prototype = p = new createjs.Stage();
p.setAutoPlay = function(autoPlay) {
this.tickEnabled = autoPlay;
}
p.play = function() { this.tickEnabled = true; this.getChildAt(0).gotoAndPlay(this.getTimelinePosition()) }
p.stop = function(ms) { if(ms) this.seek(ms); this.tickEnabled = false; }
p.seek = function(ms) { this.tickEnabled = true; this.getChildAt(0).gotoAndStop(lib.properties.fps * ms / 1000); }
p.getDuration = function() { return this.getChildAt(0).totalFrames / lib.properties.fps * 1000; }
p.getTimelinePosition = function() { return this.getChildAt(0).currentFrame / lib.properties.fps * 1000; }
an.bootcompsLoaded = an.bootcompsLoaded || [];
if(!an.bootstrapListeners) {
an.bootstrapListeners=[];
}
an.bootstrapCallback=function(fnCallback) {
an.bootstrapListeners.push(fnCallback);
if(an.bootcompsLoaded.length > 0) {
for(var i=0; i<an.bootcompsLoaded.length; ++i) {
fnCallback(an.bootcompsLoaded[i]);
}
}
};
an.compositions = an.compositions || {};
an.compositions['214D9CE6C84FD84795816AF703BF00E4'] = {
getStage: function() { return exportRoot.stage; },
getLibrary: function() { return lib; },
getSpriteSheet: function() { return ss; },
getImages: function() { return img; }
};
an.compositionLoaded = function(id) {
an.bootcompsLoaded.push(id);
for(var j=0; j<an.bootstrapListeners.length; j++) {
an.bootstrapListeners[j](id);
}
}
an.getComposition = function(id) {
return an.compositions[id];
}
an.makeResponsive = function(isResp, respDim, isScale, scaleType, domContainers) {
var lastW, lastH, lastS=1;
window.addEventListener('resize', resizeCanvas);
resizeCanvas();
function resizeCanvas() {
var w = lib.properties.width, h = lib.properties.height;
var iw = window.innerWidth, ih=window.innerHeight;
var pRatio = window.devicePixelRatio || 1, xRatio=iw/w, yRatio=ih/h, sRatio=1;
if(isResp) {
if((respDim=='width'&&lastW==iw) || (respDim=='height'&&lastH==ih)) {
sRatio = lastS;
}
else if(!isScale) {
if(iw<w || ih<h)
sRatio = Math.min(xRatio, yRatio);
}
else if(scaleType==1) {
sRatio = Math.min(xRatio, yRatio);
}
else if(scaleType==2) {
sRatio = Math.max(xRatio, yRatio);
}
}
domContainers[0].width = w * pRatio * sRatio;
domContainers[0].height = h * pRatio * sRatio;
domContainers.forEach(function(container) {
container.style.width = w * sRatio + 'px';
container.style.height = h * sRatio + 'px';
});
stage.scaleX = pRatio*sRatio;
stage.scaleY = pRatio*sRatio;
lastW = iw; lastH = ih; lastS = sRatio;
stage.tickOnUpdate = false;
stage.update();
stage.tickOnUpdate = true;
}
}
an.handleSoundStreamOnTick = function(event) {
if(!event.paused){
var stageChild = stage.getChildAt(0);
if(!stageChild.paused || stageChild.ignorePause){
stageChild.syncStreamSounds();
}
}
}
an.handleFilterCache = function(event) {
if(!event.paused){
var target = event.target;
if(target){
if(target.filterCacheList){
for(var index = 0; index < target.filterCacheList.length ; index++){
var cacheInst = target.filterCacheList[index];
if((cacheInst.startFrame <= target.currentFrame) && (target.currentFrame <= cacheInst.endFrame)){
cacheInst.instance.cache(cacheInst.x, cacheInst.y, cacheInst.w, cacheInst.h);
}
}
}
}
}
}
})(createjs = createjs||{}, AdobeAn = AdobeAn||{});
var createjs, AdobeAn;
<!DOCTYPE html>
<!--
NOTES:
1. All tokens are represented by '$' sign in the template.
2. You can write your code only wherever mentioned.
3. All occurrences of existing tokens will be replaced by their appropriate values.
4. Blank lines will be removed automatically.
5. Remove unnecessary comments before creating your template.
-->
<html>
<head>
<meta charset="UTF-8">
<meta name="authoring-tool" content="Adobe_Animate_CC">
<title>index</title>
<!-- write your code here -->
<script src="https://code.createjs.com/1.0.0/createjs.min.js"></script>
<script src="index.js"></script>
<script>
var canvas, stage, exportRoot, anim_container, dom_overlay_container, fnStartAnimation;
function init() {
canvas = document.getElementById("canvas");
anim_container = document.getElementById("animation_container");
dom_overlay_container = document.getElementById("dom_overlay_container");
var comp=AdobeAn.getComposition("214D9CE6C84FD84795816AF703BF00E4");
var lib=comp.getLibrary();
handleComplete({},comp);
}
function handleComplete(evt,comp) {
//This function is always called, irrespective of the content. You can use the variable "stage" after it is created in token create_stage.
var lib=comp.getLibrary();
var ss=comp.getSpriteSheet();
exportRoot = new lib.index();
stage = new lib.Stage(canvas);
//Registers the "tick" event listener.
fnStartAnimation = function() {
stage.addChild(exportRoot);
createjs.Ticker.framerate = lib.properties.fps;
createjs.Ticker.addEventListener("tick", stage);
}
//Code to support hidpi screens and responsive scaling.
AdobeAn.makeResponsive(false,'both',false,1,[canvas,anim_container,dom_overlay_container]);
AdobeAn.compositionLoaded(lib.properties.id);
fnStartAnimation();
}
</script>
<!-- write your code here -->
</head>
<body onload="init();" style="margin:0px;">
<div id="animation_container" style="background-color:rgba(204, 204, 204, 1.00); width:550px; height:400px">
<canvas id="canvas" width="550" height="400" style="position: absolute; display: block; background-color:rgba(204, 204, 204, 1.00);"></canvas>
<div id="dom_overlay_container" style="pointer-events:none; overflow:hidden; width:550px; height:400px; position: absolute; left: 0px; top: 0px; display: block;">
</div>
</div>
</body>
</html>
I just saw what you wrote because of the time difference.
Let me answer your last comment as follows. In the example I posted, I averaged over the canvas. While you are giving the starting position, you need to enter the initial position information as if you were rotating it. I also solved a problem with Mac devices. The example should be:
stage.enableMouseOver();
var knob_X = canvas.width/2/stage.scaleX;
var knob_Y = canvas.height/2/stage.scaleY;
var radius = 90;
var root = this;
var rads = Math.atan2(1-knob_Y,1-knob_X);
root.streakRotatorKnob.x = knob_X + radius * Math.cos(rads);
root.streakRotatorKnob.y = knob_Y + radius * Math.sin(rads);
root.streakRotatorKnob.addEventListener("rollover", rollover);
root.streakRotatorKnob.addEventListener("rollout", rollout);
function rollover(e)
{
console.log("rollover")
root.streakRotatorKnob.addEventListener("pressmove", moveF);
}
function rollout(e)
{
console.log("rollout")
root.streakRotatorKnob.removeEventListener("pressmove", moveF);
}
function moveF(e)
{
var rads = Math.atan2(stage.mouseY/stage.scaleY - knob_Y, stage.mouseX/stage.scaleX - knob_X);
e.currentTarget.x = knob_X + radius * Math.cos(rads);
e.currentTarget.y = knob_Y + radius * Math.sin(rads);
stage.update();
}
I have two javascript in one html but they don't running together however separately yes. Maybe anyone knows why? What is the problem? Thank you!
First javascript:
This is a clock.
<span style='position:absolute;z-index:1;
left:484px;top:440px;font-family: arial; font-weight: bold;font-size: 65';
<div id="txt"></div></span>
<body onload="startTime()">
<script>
function startTime() {
var today = new Date();
var h = today.getUTCHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i};
return i;
}
</script>
Second javascript:
This is a blinking image.
<script>
var tId, images = [],
isBlinking = false;
currImg = 0,
images[0] = new Image(); images[0].src = "a.gif";
images[1] = new Image(); images[1].src = "b.gif";
images[2] = new Image(); images[2].src = "c.gif";
window.onload = function() {
var img = document.getElementById("ID");
img.onclick = function() {
if (isBlinking) {
clearInterval(tId);
isBlinking = false;
currImg = currImg == 0 ? 1 : 0;
img.src = images[currImg].src;
} else {
isBlinking = true;
tId = setInterval(function() {
var src = document.getElementById("ID").src;
// blink
document.getElementById("ID").src = src == images[currImg].src ? images[2].src : images[currImg].src;
}, 300);
}
}
}
</script>
<img id="ID" src="a.gif" />
See changes below. Do a file compare.
<span style='position:absolute;z-index:1;
left:484px;top:440px;font-family: arial; font-weight: bold;font-size: 65'>
</span>
<div id="txt"></div>
<img id="ID" src="a.gif" />
<script>
startTime();
function startTime() {
var today = new Date();
var h = today.getUTCHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) { i = "0" + i };
return i;
}
</script>
<script>
var tId, images = [],
isBlinking = false;
currImg = 0,
images[0] = new Image(); images[0].src = "a.gif";
images[1] = new Image(); images[1].src = "b.gif";
images[2] = new Image(); images[2].src = "c.gif";
window.onload = function () {
var img = document.getElementById("ID");
img.onclick = function () {
if (isBlinking) {
clearInterval(tId);
isBlinking = false;
currImg = currImg == 0 ? 1 : 0;
img.src = images[currImg].src;
} else {
isBlinking = true;
tId = setInterval(function () {
var src = document.getElementById("ID").src;
// blink
document.getElementById("ID").src = src == images[currImg].src ? images[2].src : images[currImg].src;
}, 300);
}
}
}
</script>
try this way window.onload = startTime;
var tId, images = [],
isBlinking = false;
currImg = 0,
images[0] = new Image(); images[0].src = "a.gif";
images[1] = new Image(); images[1].src = "b.gif";
images[2] = new Image(); images[2].src = "c.gif";
var img = document.getElementById("ID");
img.onclick = function () {
if (isBlinking) {
clearInterval(tId);
isBlinking = false;
currImg = currImg == 0 ? 1 : 0;
img.src = images[currImg].src;
} else {
isBlinking = true;
tId = setInterval(function () {
var src = document.getElementById("ID").src;
// blink
document.getElementById("ID").src = src == images[currImg].src ? images[2].src : images[currImg].src;
}, 300);
}
}
function startTime() {
var today = new Date();
var h = today.getUTCHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) { i = "0" + i };
return i;
}
window.onload = startTime;
<div id="txt"></div>
<img id="ID" src="a.gif" />
Im making a multiplayer endless runner game and want to make the background move down in a loop with random obstacles in my way. So far I was able to make the scene with controls for the player, have set up a multiplayer aspect, and a sign in. However, I am not able to figure out how to set the background in a loop or add obstacles moving towards the player.
Heres the code:
App2.JS:
var mongojs = require("mongojs");
var db = mongojs('localhost:27017/myGame', ['account','progress']);
var express = require('express');
var app = express();
var serv = require('http').Server(app);
app.get('/',function(req, res) {
res.sendFile(__dirname + '/client/index2.html');
});
app.use('/client',express.static(__dirname + '/client'));
serv.listen(2000);
console.log("Server started.");
var SOCKET_LIST = {};
var Entity = function(){
var self = {
x:250,
y:250,
spdX:0,
spdY:0,
id:"",
}
self.update = function(){
self.updatePosition();
}
self.updatePosition = function(){
self.x += self.spdX;
self.y += self.spdY;
}
self.getDistance = function(pt){
return Math.sqrt(Math.pow(self.x-pt.x,2) + Math.pow(self.y-pt.y,2));
}
return self;
}
var Player = function(id){
var self = Entity();
self.id = id;
self.number = "" + Math.floor(10 * Math.random());
self.pressingRight = false;
self.pressingLeft = false;
self.pressingUp = false;
self.pressingDown = false;
self.pressingAttack = false;
self.mouseAngle = 0;
self.maxSpd = 25;
self.hp = 10;
self.hpMax = 10;
self.score = 0;
var super_update = self.update;
self.update = function(){
self.updateSpd();
super_update();
if(self.pressingAttack){
self.shootBullet(self.mouseAngle);
}
}
self.shootBullet = function(angle){
var b = Bullet(self.id,angle);
b.x = self.x;
b.y = self.y;
}
self.updateSpd = function(){
if(self.pressingRight && (self.x + 30) < 500)
self.spdX = self.maxSpd;
else if(self.pressingLeft && self.x > 0)
self.spdX = -self.maxSpd;
else
self.spdX = 0;
if(self.pressingUp)
self.spdY = 0;
else if(self.pressingDown)
self.spdY = 0;
else
self.spdY = 0;
}
self.getInitPack = function(){
return {
id:self.id,
x:self.x,
y:self.y,
number:self.number,
hp:self.hp,
hpMax:self.hpMax,
score:self.score,
};
}
self.getUpdatePack = function(){
return {
id:self.id,
x:self.x,
y:self.y,
hp:self.hp,
score:self.score,
}
}
Player.list[id] = self;
initPack.player.push(self.getInitPack());
return self;
}
Player.list = {};
Player.onConnect = function(socket){
var player = Player(socket.id);
socket.on('keyPress',function(data){
if(data.inputId === 'left')
player.pressingLeft = data.state;
else if(data.inputId === 'right')
player.pressingRight = data.state;
else if(data.inputId === 'up')
player.pressingUp = data.state;
else if(data.inputId === 'down')
player.pressingDown = data.state;
else if(data.inputId === 'attack')
player.pressingAttack = data.state;
else if(data.inputId === 'mouseAngle')
player.mouseAngle = data.state;
});
socket.emit('init',{
selfId:socket.id,
player:Player.getAllInitPack(),
bullet:Bullet.getAllInitPack(),
})
}
Player.getAllInitPack = function(){
var players = [];
for(var i in Player.list)
players.push(Player.list[i].getInitPack());
return players;
}
Player.onDisconnect = function(socket){
delete Player.list[socket.id];
removePack.player.push(socket.id);
}
Player.update = function(){
var pack = [];
for(var i in Player.list){
var player = Player.list[i];
player.update();
pack.push(player.getUpdatePack());
}
return pack;
}
var Bullet = function(parent,angle){
var self = Entity();
self.id = Math.random();
self.spdX = Math.cos(angle/180*Math.PI) * 10;
self.spdY = Math.sin(angle/180*Math.PI) * 10;
self.parent = parent;
self.timer = 0;
self.toRemove = false;
var super_update = self.update;
self.update = function(){
if(self.timer++ > 100)
self.toRemove = true;
super_update();
for(var i in Player.list){
var p = Player.list[i];
if(self.getDistance(p) < 32 && self.parent !== p.id){
p.hp -= 1;
if(p.hp <= 0){
var shooter = Player.list[self.parent];
if(shooter)
shooter.score += 1;
p.hp = p.hpMax;
p.x = Math.random() * 500;
p.y = Math.random() * 500;
}
self.toRemove = true;
}
}
}
self.getInitPack = function(){
return {
id:self.id,
x:self.x,
y:self.y,
};
}
self.getUpdatePack = function(){
return {
id:self.id,
x:self.x,
y:self.y,
};
}
Bullet.list[self.id] = self;
initPack.bullet.push(self.getInitPack());
return self;
}
Bullet.list = {};
Bullet.update = function(){
var pack = [];
for(var i in Bullet.list){
var bullet = Bullet.list[i];
bullet.update();
if(bullet.toRemove){
delete Bullet.list[i];
removePack.bullet.push(bullet.id);
} else
pack.push(bullet.getUpdatePack());
}
return pack;
}
Bullet.getAllInitPack = function(){
var bullets = [];
for(var i in Bullet.list)
bullets.push(Bullet.list[i].getInitPack());
return bullets;
}
var DEBUG = true;
var isValidPassword = function(data,cb){
db.account.find({username:data.username,password:data.password},function(err,res){
if(res.length > 0)
cb(true);
else
cb(false);
});
}
var isUsernameTaken = function(data,cb){
db.account.find({username:data.username},function(err,res){
if(res.length > 0)
cb(true);
else
cb(false);
});
}
var addUser = function(data,cb){
db.account.insert({username:data.username,password:data.password},function(err){
cb();
});
}
var io = require('socket.io')(serv,{});
io.sockets.on('connection', function(socket){
socket.id = Math.random();
SOCKET_LIST[socket.id] = socket;
socket.on('signIn',function(data){
isValidPassword(data,function(res){
if(res){
Player.onConnect(socket);
socket.emit('signInResponse',{success:true});
} else {
socket.emit('signInResponse',{success:false});
}
});
});
socket.on('signUp',function(data){
isUsernameTaken(data,function(res){
if(res){
socket.emit('signUpResponse',{success:false});
} else {
addUser(data,function(){
socket.emit('signUpResponse',{success:true});
});
}
});
});
socket.on('disconnect',function(){
delete SOCKET_LIST[socket.id];
Player.onDisconnect(socket);
});
socket.on('sendMsgToServer',function(data){
var playerName = ("" + socket.id).slice(2,7);
for(var i in SOCKET_LIST){
SOCKET_LIST[i].emit('addToChat',playerName + ': ' + data);
}
});
socket.on('evalServer',function(data){
if(!DEBUG)
return;
var res = eval(data);
socket.emit('evalAnswer',res);
});
});
var initPack = {player:[],bullet:[]};
var removePack = {player:[],bullet:[]};
setInterval(function(){
var pack = {
player:Player.update(),
bullet:Bullet.update(),
}
for(var i in SOCKET_LIST){
var socket = SOCKET_LIST[i];
socket.emit('init',initPack);
socket.emit('update',pack);
socket.emit('remove',removePack);
}
initPack.player = [];
initPack.bullet = [];
removePack.player = [];
removePack.bullet = [];
},1000/25);
indexCars2.html:
<div id="signDiv">
Username: <input id="signDiv-username" type="text"></input><br>
Password: <input id="signDiv-password" type="password"></input>
<button id="signDiv-signIn">Sign In</button>
<button id="signDiv-signUp">Sign Up</button>
</div>
<div id="animate"
style = "position: relative;"
style = "border: 1px solid green;"
style = "background: yellow; "
style = "width: 100;"
style = "height: 100;"
style = "z-index: 5;">
Sample
</div>
<div id="gameDiv" style="display:none;">
<canvas id="ctx" width="500" height="500" style="border:1px solid #000000;"></canvas>
<div id="chat-text" style="width:500px;height:100px;overflow-y:scroll">
<div>Hello!</div>
</div>
<form id="chat-form">
<input id="chat-input" type="text" style="width:500px"></input>
</form>
</div>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
$(document).ready(function(e) {
var width = "+=" + $(document).width();
$("#animate").animate({
left: width
}, 5000, function() {
// Animation complete.
});
});</script>
<script>
// var WIDTH = 500;
// var HEIGHT = 500;
var socket = io();
//sign
var signDiv = document.getElementById('signDiv');
var signDivUsername = document.getElementById('signDiv-username');
var signDivSignIn = document.getElementById('signDiv-signIn');
var signDivSignUp = document.getElementById('signDiv-signUp');
var signDivPassword = document.getElementById('signDiv-password');
signDivSignIn.onclick = function(){
socket.emit('signIn',{username:signDivUsername.value,password:signDivPassword.value});
}
signDivSignUp.onclick = function(){
socket.emit('signUp',{username:signDivUsername.value,password:signDivPassword.value});
}
socket.on('signInResponse',function(data){
if(data.success){
signDiv.style.display = 'none';
gameDiv.style.display = 'inline-block';
} else
alert("Sign in unsuccessul.");
});
socket.on('signUpResponse',function(data){
if(data.success){
alert("Sign up successul.");
} else
alert("Sign up unsuccessul.");
});
//chat
var chatText = document.getElementById('chat-text');
var chatInput = document.getElementById('chat-input');
var chatForm = document.getElementById('chat-form');
socket.on('addToChat',function(data){
chatText.innerHTML += '<div>' + data + '</div>';
});
socket.on('evalAnswer',function(data){
console.log(data);
});
chatForm.onsubmit = function(e){
e.preventDefault();
if(chatInput.value[0] === '/')
socket.emit('evalServer',chatInput.value.slice(1));
else
socket.emit('sendMsgToServer',chatInput.value);
chatInput.value = '';
}
//game
var Img = {};
Img.player = new Image();
Img.player.src = '/client/img/lamboS.png';
Img.bullet = new Image();
Img.bullet.src = '/client/img/bullet.png';
Img.map = new Image();
Img.map.src = '/client/img/road.png';
var ctx = document.getElementById("ctx").getContext("2d");
ctx.font = '30px Arial';
var Player = function(initPack){
var self = {};
self.id = initPack.id;
self.number = initPack.number;
self.x = initPack.x;
self.y = initPack.y;
self.hp = initPack.hp;
self.hpMax = initPack.hpMax;
self.score = initPack.score;
self.draw = function(){
// var x = self.x - Player.list[selfId].x + WIDTH/2;
// var y = self.y - Player.list[selfId].y + HEIGHT/2;
var hpWidth = 30 * self.hp / self.hpMax;
ctx.fillStyle = 'red';
ctx.fillRect(self.x - hpWidth/2,self.y - 40,hpWidth,4);
var width = Img.player.width;
var height = Img.player.height;
ctx.drawImage(Img.player,
0,0,Img.player.width,Img.player.height,
self.x-width/2,self.y-height/2,width,height);
//ctx.fillText(self.score,self.x,self.y-60);
}
Player.list[self.id] = self;
return self;
}
Player.list = {};
var Bullet = function(initPack){
var self = {};
self.id = initPack.id;
self.x = initPack.x;
self.y = initPack.y;
self.draw = function(){
var width = Img.bullet.width/2;
var height = Img.bullet.height/2;
// var x = self.x - Player.list[selfId].x + WIDTH/2;
// var y = self.y - Player.list[selfId].y + HEIGHT/2;
ctx.drawImage(Img.bullet,
0,0,Img.bullet.width,Img.bullet.height,
self.x-width/2,self.y-height/2,width,height);
}
Bullet.list[self.id] = self;
return self;
}
Bullet.list = {};
var selfId = null;
socket.on('init',function(data){
if(data.selfId)
selfId = data.selfId;
//{ player : [{id:123,number:'1',x:0,y:0},{id:1,number:'2',x:0,y:0}], bullet: []}
for(var i = 0 ; i < data.player.length; i++){
new Player(data.player[i]);
}
for(var i = 0 ; i < data.bullet.length; i++){
new Bullet(data.bullet[i]);
}
});
socket.on('update',function(data){
//{ player : [{id:123,x:0,y:0},{id:1,x:0,y:0}], bullet: []}
for(var i = 0 ; i < data.player.length; i++){
var pack = data.player[i];
var p = Player.list[pack.id];
if(p){
if(pack.x !== undefined)
p.x = pack.x;
if(pack.y !== undefined)
p.y = pack.y;
if(pack.hp !== undefined)
p.hp = pack.hp;
if(pack.score !== undefined)
p.score = pack.score;
}
}
for(var i = 0 ; i < data.bullet.length; i++){
var pack = data.bullet[i];
var b = Bullet.list[data.bullet[i].id];
if(b){
if(pack.x !== undefined)
b.x = pack.x;
if(pack.y !== undefined)
b.y = pack.y;
}
}
for(var i = 0 ; i < data.bullet.length; i++){
var pack = data.bullet[i];
var b = Bullet.list[data.bullet[i].id];
if(b){
if(pack.x !== undefined)
b.x = pack.x;
if(pack.y !== undefined)
b.y = pack.y;
}
}
});
socket.on('remove',function(data){
//{player:[12323],bullet:[12323,123123]}
for(var i = 0 ; i < data.player.length; i++){
delete Player.list[data.player[i]];
}
for(var i = 0 ; i < data.bullet.length; i++){
delete Bullet.list[data.bullet[i]];
}
});
setInterval(function(){
if(!selfId)
return;
ctx.clearRect(0,0,500,500);
drawMap();
drawScore();
for(var i in Player.list)
Player.list[i].draw();
for(var i in Bullet.list)
Bullet.list[i].draw();
},40);
var drawMap = function(){
var x = 0;
var y = 0;
// var x = WIDTH/2 - Player.list[selfId].x;
// var y = HEIGHT/2 - Player.list[selfId].y;
ctx.drawImage(Img.map, x, y);
// for(x = 0; x < 5; x += 100){
//// ctx.drawImage(Img.map, x, y);
// }
}
var drawScore = function(){
ctx.fillStyle = 'red';
ctx.fillText(Player.list[selfId].score,10,30);
}
document.onkeydown = function(event){
if(event.keyCode === 68) //d
socket.emit('keyPress',{inputId:'right',state:true});
else if(event.keyCode === 83) //s
socket.emit('keyPress',{inputId:'down',state:true});
else if(event.keyCode === 65) //a
socket.emit('keyPress',{inputId:'left',state:true});
else if(event.keyCode === 87) // w
socket.emit('keyPress',{inputId:'up',state:true});
}
document.onkeyup = function(event){
if(event.keyCode === 68) //d
socket.emit('keyPress',{inputId:'right',state:false});
else if(event.keyCode === 83) //s
socket.emit('keyPress',{inputId:'down',state:false});
else if(event.keyCode === 65) //a
socket.emit('keyPress',{inputId:'left',state:false});
else if(event.keyCode === 87) // w
socket.emit('keyPress',{inputId:'up',state:false});
}
document.onmousedown = function(event){
socket.emit('keyPress',{inputId:'attack',state:true});
}
document.onmouseup = function(event){
socket.emit('keyPress',{inputId:'attack',state:false});
}
document.onmousemove = function(event){
var x = -250 + event.clientX - 8;
var y = -250 + event.clientY - 8;
var angle = Math.atan2(y,x) / Math.PI * 180;
socket.emit('keyPress',{inputId:'mouseAngle',state:angle});
}
</script>
The idea in endless runners is to actually move the objects towards the player at constant speed(i.e. speed of the player). As soon as they get off the screen you can stop updating them. Check out this http://blog.sklambert.com/html5-game-tutorial-module-pattern/?utm_content=buffer18ac6&utm_medium=social&utm_source=twitter.com&utm_campaign=buffer
I have a code for a slideshow that runs automatically and all I want is to stop the timer when I click on the image and pause it when i hover over it.
I tried the clearinterval function but it didn't work at all, so I need your help please.
This is the JavaScript code:
var m3D = function() {
var e = 4;
var t = [],
n, r, i, s, o,
u = "",
a = "",
f = {
x: 0,
y: 0,
z: -650,
s: 0,
fov: 500
},
l = 0,
c = 0;
f.setTarget = function(e, t, n) {
if (Math.abs(t - e) > .1) {
f.s = 1;
f.p = 0;
f.d = t - e;
if (n) {
f.d *= 2;
f.p = 9
}
}
};
f.tween = function(e) {
if (f.s != 0) {
f.p += f.s;
f[e] += f.d * f.p * .01;
if (f.p == 10) f.s = -1;
else if (f.p == 0) f.s = 0
}
return f.s
};
var h = function(k, l, c, h, p) {
if (l) {
this.url = l.url;
this.title = l.title;
this.color = l.color;
this.isLoaded = false;
if (document.createElement("canvas").getContext) {
this.srcImg = new Image;
this.srcImg.src = u + l.src;
this.img = document.createElement("canvas");
this.canvas = true;
r.appendChild(this.img)
} else {
this.img = document.createElement("img");
this.img.src = u + l.src;
r.appendChild(this.img)
}
function v(e, t) {
return Math.floor(Math.random() * (t - e + 1)) + e
}
function m() {
var e = t.length;
var n = v(0, t.length);
l.src = u + "photo" + n + ".jpg";
if (f.s) return;
try {
if (t[n].canvas == true) {
f.tz = t[n].z - f.fov;
f.tx = t[n].x;
f.ty = t[n].y;
if (s) {
s.but.className = "button viewed";
s.img.className = "";
s.img.style.cursor = "pointer";
s.urlActive = false;
o.style.visibility = "hidden"
}
t[n].img.className = "button selected";
d(false);
s = t[n]
} else {}
} catch (r) {}
}
// this is the Interval timer
var g = setInterval(m, 6e3);
this.img.onclick = function()
{
/*
i want to reset the timer OR increase it when i click here
*/
alert("click");
if (f.s) return;
if (this.diapo.isLoaded) {
if (this.diapo.urlActive) {
top.location.href = this.diapo.url
} else {
f.tz = this.diapo.z - f.fov;
f.tx = this.diapo.x;
f.ty = this.diapo.y;
if (s) {
s.but.className = "button viewed";
s.img.className = "";
s.img.style.cursor = "pointer";
s.urlActive = false;
o.style.visibility = "hidden"
}
this.diapo.but.className = "button selected";
d(false);
s = this.diapo
}
}
};
this.but = document.createElement("div");
this.Img = document.createElement("Img");
this.but.className = "button";
this.Img.src = a + l.src;
this.but.appendChild(this.Img);
i.appendChild(this.but);
this.but.diapo = this;
this.Img.style.left = Math.round(this.but.offsetWidth * 1.2 * (k % e)) + "px";
this.Img.style.top = Math.round(this.but.offsetHeight * 1.2 * Math.floor(k / e)) + "px";
this.Img.style.zIndex = "50";
this.but.onclick = this.img.onclick;
n = this.img;
this.img.diapo = this;
this.zi = 25e3
} else {
this.img = document.createElement("div");
this.isLoaded = true;
this.img.className = "fog";
r.appendChild(this.img);
this.w = 300;
this.h = 300;
this.zi = 15e3
}
this.x = c;
this.y = h;
this.z = p;
this.css = this.img.style
};
h.prototype.anim = function() {
if (this.isLoaded) {
var e = this.x - f.x;
var t = this.y - f.y;
var n = this.z - f.z;
if (n < 20) n += 5e3;
var r = f.fov / n;
var i = this.w * r;
var s = this.h * r;
this.css.left = Math.round(l + e * r - i * .5) + "px";
this.css.top = Math.round(c + t * r - s * .5) + "px";
this.css.width = Math.round(i) + "px";
this.css.height = Math.round(s) + "px";
this.css.zIndex = this.zi - Math.round(n)
} else {
this.isLoaded = this.loading()
}
};
h.prototype.loading = function() {
if (this.canvas && this.srcImg.complete || this.img.complete) {
if (this.canvas) {
this.w = this.srcImg.width;
this.h = this.srcImg.height;
this.img.width = this.w;
this.img.height = this.h;
var e = this.img.getContext("2d");
e.drawImage(this.srcImg, 0, 0, this.w, this.h)
} else {
this.w = this.img.width;
this.h = this.img.height
}
this.but.className += " loaded";
return true
}
return false
};
var p = function() {
l = r.offsetWidth * .5;
c = r.offsetHeight * .5
};
var d = function(e) {
var n = 0,
r;
while (r = t[n++]) {
if (r.but) {
r.css.msInterpolationMode = e ? "bicubic" : "nearest-neighbor";
r.css.imageRendering = e ? "optimizeQuality" : "optimizeSpeed"
}
}
};
var v = function(e) {
r = document.getElementById("screen");
i = document.getElementById("bar");
o = document.getElementById("urlInfo");
p();
var n = 0,
s, u = e.length;
while (s = e[n++]) {
var a = 1e3 * (n % 4 - 1.5);
var f = Math.round(Math.random() * 4e3) - 2e3;
var l = n * (5e3 / u);
t.push(new h(n - 1, s, a, f, l));
var c = t.length - 1;
for (var d = 0; d < 3; d++) {
var a = Math.round(Math.random() * 4e3) - 2e3;
var f = Math.round(Math.random() * 4e3) - 2e3;
t.push(new h(c, null, a, f, l + 100))
}
/*
var d = t.length - 1;
for (var v = 0; v < 3; v++) {
var a = Math.round(Math.random() * 4e3) - 2e3;
var f = Math.round(Math.random() * 4e3) - 2e3;
t.push(new h(d, null, a, f, l + 100))
}
*/
}
m()
};
var m = function() {
if (f.tx) {
if (!f.s) f.setTarget(f.x, f.tx);
var e = f.tween("x");
if (!e) f.tx = 0
} else if (f.ty) {
if (!f.s) f.setTarget(f.y, f.ty);
var e = f.tween("y");
if (!e) f.ty = 0
} else if (f.tz) {
if (!f.s) f.setTarget(f.z, f.tz);
var e = f.tween("z");
if (!e) {
f.tz = 0;
d(true);
if (s.url) {
s.img.style.cursor = "pointer";
s.urlActive = true;
s.img.className = "href";
o.diapo = s;
o.onclick = s.img.onclick;
o.innerHTML = s.title || s.url;
o.style.visibility = "visible";
o.style.color = s.color || "#fff";
o.style.top = Math.round(s.img.offsetTop + s.img.offsetHeight - o.offsetHeight - 5) + "px";
o.style.left = Math.round(s.img.offsetLeft + s.img.offsetWidth - o.offsetWidth - 5) + "px"
} else {
s.img.style.cursor = "default"
}
/*
i want to pause the timer when i hover here
*/
s.img.onmouseover = function(){
alert("mouseover");
};
}
}
var n = 0,
r;
while (r = t[n++]) r.anim();
var g = setTimeout(m, 32)
};
return {
init: v
}
}()
And as you see, on line 90 I have the setInterval timer function and after it the onclick function where I need to "reset" the timer, and on line 270 the onmouseover function where I need to "pause" the timer.
So how to do this?
Try using a flag variable. Add var pauseSlideshow = false; somewhere at the top of the file, so it will be in the global scope. Change the m()function like so:
var m = function() {
if(!pauseSlideshow) {
/*
*
* all of the code already in m()
*
*/
} // make sure to add this additional curly brace
}
And then you need an onmouseover and an onmouseout function to toggle pauseSlideshow, like this:
s.img.onmouseover = function() {
pauseSlideshow = true;
};
s.img.onmouseout = function() {
pauseSlideshow = false;
};
Having a slight issue getting some coins to generate multiplayer using eureca.io websockets. I've got the players working multiplayer and from remote connections but I can't seem to get the coins to generate across the connection so they appear in the same place on all the players connections. I'm using phaser to generate the game and eureca and engine for my web connection. I've got the coins to spawn on the page with no problems, but whenever a new player joins, the coin always displays in a different place, I wondering how I can make them generate across the connection. My game code is below:
Game Code
var myId = 0;
var background;
var blueSquare;
var player;
var coins;
var goldCoin;
var squareList;
var coinList;
var cursors;
var score;
var highScore;
var ready = false;
var eurecaServer;
var eurecaClientSetup = function () {
var eurecaClient = new Eureca.Client();
eurecaClient.ready(function (proxy) {
eurecaServer = proxy;
});
eurecaClient.exports.setId = function (id)
{
myId = id;
create();
eurecaServer.handshake();
ready = true;
}
eurecaClient.exports.kill = function (id)
{
if (squareList[id]) {
squareList[id].kill();
console.log('Player has left the game ', id, squareList[id]);
}
}
eurecaClient.exports.spawnBlueSquare = function (i, x, y)
{
if (i == myId) return;
console.log('A new player has joined the game');
var blsq = new BlueSquare(i, game, blueSquare);
squareList[i] = blsq;
}
eurecaClient.exports.spawnCoins = function (c, x, y)
{
console.log('A coin has been generated');
var cn = new GenerateCoin(c, game, coin);
coinList[c] = cn;
}
eurecaClient.exports.updateState = function (id, state)
{
if (squareList[id]) {
squareList[id].cursor = state;
squareList[id].blueSquare.x = state.x;
squareList[id].blueSquare.y = state.y;
squareList[id].blueSquare.angle = state.angle;
squareList[id].update();
coinList.cursor = state;
coinList.blueSquare.x = state.x;
coinList.blueSquare.y = state.y;
coinList.update();
}
}
}
BlueSquare = function (index, game, player) {
this.cursor = {
left:false,
right:false,
up:false,
down:false,
}
this.input = {
left:false,
right:false,
up:false,
down:false,
}
var x = 0;
var y = 0;
this.game = game;
this.player = player;
this.currentSpeed = 0;
this.isBlue = true;
this.blueSquare = game.add.sprite(x, y, 'blueSquare');
this.blueSquare.anchor.set(0.5);
this.blueSquare.id = index;
game.physics.enable(this.blueSquare, Phaser.Physics.ARCADE);
this.blueSquare.body.immovable = false;
this.blueSquare.body.collideWorldBounds = true;
this.blueSquare.body.setSize(34, 34, 0, 0);
this.blueSquare.angle = 0;
game.physics.arcade.velocityFromRotation(this.blueSquare.rotation, 0, this.blueSquare.body.velocity);
}
BlueSquare.prototype.update = function () {
var inputChanged = (
this.cursor.left != this.input.left ||
this.cursor.right != this.input.right ||
this.cursor.up != this.input.up ||
this.cursor.down != this.input.down
);
if (inputChanged)
{
if (this.blueSquare.id == myId)
{
this.input.x = this.blueSquare.x;
this.input.y = this.blueSquare.y;
this.input.angle = this.blueSquare.angle;
eurecaServer.handleKeys(this.input);
}
}
if (this.cursor.left)
{
this.blueSquare.body.velocity.x = -250;
this.blueSquare.body.velocity.y = 0;
}
else if (this.cursor.right)
{
this.blueSquare.body.velocity.x = 250;
this.blueSquare.body.velocity.y = 0;
}
else if (this.cursor.down)
{
this.blueSquare.body.velocity.x = 0;
this.blueSquare.body.velocity.y = 250;
}
else if (this.cursor.up)
{
this.blueSquare.body.velocity.x = 0;
this.blueSquare.body.velocity.y = -250;
}
else
{
this.blueSquare.body.velocity.x = 0;
this.blueSquare.body.velocity.y = 0;
}
}
BlueSquare.prototype.kill = function () {
this.alive = false;
this.blueSquare.kill();
}
GenerateCoin = function (game, goldCoin) {
this.game = game;
this.goldCoin = goldCoin;
x = 0;
y = 0;
this.coins = game.add.sprite(x, y, 'coin');
game.physics.enable(this.coins, Phaser.Physics.ARCADE);
this.coins.body.immovable = true;
this.coins.body.collideWorldBounds = true;
this.coins.body.setSize(16, 16, 0, 0);
}
window.onload = function() {
function countdown( elementName, minutes, seconds )
{
var element, endTime, hours, mins, msLeft, time;
function twoDigits( n )
{
return (n <= 9 ? "0" + n : n);
}
function updateTimer()
{
msLeft = endTime - (+new Date);
if ( msLeft < 1000 ) {
element.innerHTML = "Game Over!";
} else {
time = new Date( msLeft );
hours = time.getUTCHours();
mins = time.getUTCMinutes();
element.innerHTML = (hours ? hours + ':' + twoDigits( mins ) : mins) + ':' + twoDigits( time.getUTCSeconds() );
setTimeout( updateTimer, time.getUTCMilliseconds() + 500 );
}
}
element = document.getElementById( elementName );
endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500;
updateTimer();
}countdown( "countdown", 5, 0 );
}
var game = new Phaser.Game(700, 600, Phaser.AUTO, 'Square Hunt', { preload: preload, create: eurecaClientSetup, update: update, render: render });
function preload () {
game.load.spritesheet('coin', 'assets/coin.png', 18, 18);
game.load.image('blueSquare', 'assets/blue-square.png');
game.load.image('redSquare', 'assets/red-square.png');
game.load.image('earth', 'assets/sand.png');
}
function create () {
game.world.setBounds(0, 0, 1500, 1500);
game.stage.disableVisibilityChange = true;
background = game.add.tileSprite(0, 0, 800, 600, 'earth');
background.fixedToCamera = true;
squareList = {};
player = new BlueSquare(myId, game, blueSquare);
squareList[myId] = player;
blueSquare = player.blueSquare;
blueSquare.x = Math.floor(Math.random() * 650);
blueSquare.y = Math.floor(Math.random() * 650);
blueSquare.bringToTop();
game.camera.follow(blueSquare);
game.camera.deadzone = new Phaser.Rectangle(150, 150, 500, 300);
game.camera.focusOnXY(0, 0);
cursors = game.input.keyboard.createCursorKeys();
coinList = {};
goldCoin = new GenerateCoin(game, coins);
coinList = goldCoin;
coins = goldCoin.coins;
coins.x = Math.floor(Math.random() * 650);
coins.y = Math.floor(Math.random() * 650);
coins.bringToTop();
}
function update () {
if (!ready) return;
game.physics.arcade.collide(blueSquare, coins);
player.input.left = cursors.left.isDown;
player.input.right = cursors.right.isDown;
player.input.up = cursors.up.isDown;
player.input.down = cursors.down.isDown;
player.input.fire = game.input.activePointer.isDown;
player.input.tx = game.input.x+ game.camera.x;
player.input.ty = game.input.y+ game.camera.y;
background.tilePosition.x = -game.camera.x;
background.tilePosition.y = -game.camera.y;
for (var i in squareList)
{
if (!squareList[i]) continue;
var curBlue = squareList[i].blueSquare;
for (var j in squareList)
{
if (!squareList[j]) continue;
if (j!=i)
{
var targetBlue = squareList[j].blueSquare;
}
if (squareList[j].isBlue)
{
squareList[j].update();
}
}
}
}
function test(){
console.log('collsion');
}
function render () {}
Server.js Files
var express = require('express')
, app = express(app)
, server = require('http').createServer(app);
app.use(express.static(__dirname));
var clients = {};
var EurecaServer = require('eureca.io').EurecaServer;
var eurecaServer = new EurecaServer({allow:['setId', 'spawnBlueSquare', 'spawnCoins', 'kill', 'updateState']});
eurecaServer.attach(server);
eurecaServer.onConnect(function (conn) {
console.log('New Client id=%s ', conn.id, conn.remoteAddress);
var remote = eurecaServer.getClient(conn.id);
clients[conn.id] = {id:conn.id, remote:remote}
remote.setId(conn.id);
});
eurecaServer.onConnectionLost(function (conn) {
console.log('connection lost ... will try to reconnect');
});
eurecaServer.onDisconnect(function (conn) {
console.log('Client disconnected ', conn.id);
var removeId = clients[conn.id].id;
delete clients[conn.id];
for (var c in clients)
{
var remote = clients[c].remote;
remote.kill(conn.id);
}
});
eurecaServer.exports.handshake = function()
{
for (var c in clients)
{
var remote = clients[c].remote;
for (var cc in clients)
{
var x = clients[cc].laststate ? clients[cc].laststate.x: 0;
var y = clients[cc].laststate ? clients[cc].laststate.y: 0;
remote.spawnBlueSquare(clients[cc].id, x, y);
}
}
}
eurecaServer.exports.handleKeys = function (keys) {
var conn = this.connection;
var updatedClient = clients[conn.id];
for (var c in clients)
{
var remote = clients[c].remote;
remote.updateState(updatedClient.id, keys);
clients[c].laststate = keys;
}
}
server.listen(8000);
Instead of generating coins randomly positioned on each client, you could generate this random position(x and y) in server side(on conexion event) and then send this position to all clients so they can generate the coin in the same position.