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
Related
so I have been working on a piano game where two people compete against each other and press notes as fast as they can. The game should end when one of the players reaches a certain score, but the database is not updating the game state.
sketch.js
var playercount = 0;
var player;
var database;
var playerIndex = null;
var gamestate = 0;
var game;
var wkey;
var bkey;
var cKey
var dKey
var eKey
var fKey
var gKey
var aKey
var bKey
var csKey
var dsKey
var gsKey
var fsKey
var asKey
var cstate = true;
var dstate = true;
var estate = true;
var fstate = true;
var gstate = true;
var astate = true;
var bstate = true;
var csstate = true;
var dsstate = true;
var fsstate = true;
var gsstate = true;
var asstate = true;
var form;
//var arr = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A"]
function preload() {
//wkey = loadImage("wkey.png");
// bkey = loadImage("bkey.png");
cKey = loadImage("C.png")
dKey = loadImage("D.png")
eKey = loadImage("E.png")
fKey = loadImage("F.png")
gKey = loadImage("G.png")
aKey = loadImage("A.png")
bKey = loadImage("B.png")
csKey = loadImage("Csharp.png")
dsKey = loadImage("Dsharp.png")
gsKey = loadImage("Gsharp.png")
fsKey = loadImage("Fsharp.png")
asKey = loadImage("Asharp.png")
}
function setup() {
createCanvas(windowWidth,windowHeight);
database = firebase.database();
form = new Form();
form.display();
player = new Player();
player.getCount();
game = new Game();
game.getState();
}
function draw() {
background("white");
if(playercount == 2){
game.updateState(1);
}
if(gamestate == 1){
game.start();
}
if(player.score == 10) {
game.updateState(2);
}
if(gamestate == 2){
game.end();
}
drawSprites();
}
game.js
class Game {
constructor() {
}
start() {
form.title.hide();
var resetButton = createSprite(1000, 200, 50, 50);
if(mousePressedOver(resetButton)){
console.log("hi")
database.ref("/").set({
playerCount: 0,
gameState: 0,
players: {},
});
window.location.reload();
}
var C = createSprite(width/2-600, height/2, 100, 400);
C.shapeColor = "grey";
var D = createSprite(width/2-495, height/2, 100, 400);
D.shapeColor = "grey";
var E = createSprite(width/2-390, height/2, 100, 400);
E.shapeColor = "grey";
var F = createSprite(width/2-285, height/2, 100, 400);
F.shapeColor = "grey";
var G = createSprite(width/2-180, height/2, 100, 400);
G.shapeColor = "grey";
var A = createSprite(width/2-75, height/2, 100, 400);
A.shapeColor = "grey";
var B = createSprite(width/2+30, height/2, 100, 400);
B.shapeColor = "grey";
var Cs = createSprite(width/2-550, height/2-100, 50, 200);
Cs.shapeColor = "black";
var Ds = createSprite(width/2-445, height/2-100, 50, 200);
Ds.shapeColor = "black";
//var Es = createSprite(width/2-340, height/2-100, 50, 200);
// Es.shapeColor = "black";
var Fs = createSprite(width/2-235, height/2-100, 50, 200);
Fs.shapeColor = "black";
var Gs = createSprite(width/2-130, height/2-100, 50, 200);
Gs.shapeColor = "black";
var As = createSprite(width/2-25, height/2-100, 50, 200);
As.shapeColor = "black";
var c = new Notes(100, 40, 20, 20, cKey);
var d = new Notes(150, 40, 20, 20, dKey);
var e = new Notes(200, 40, 20, 20, eKey);
var f = new Notes(250, 40, 20, 20, fKey);
var g = new Notes(300, 40, 20, 20, gKey);
var a = new Notes(350, 40, 20, 20, aKey);
var b = new Notes(400, 40, 20, 20, bKey);
var cs = new Notes(450, 40, 20, 20, csKey);
var ds = new Notes(500, 40, 20, 20, dsKey);
var fs = new Notes(550, 40, 20, 20, fsKey);
var gs = new Notes(600, 40, 20, 20, gsKey);
var as = new Notes(200, 40, 20, 20, asKey);
var r1 = Math.round(random(90, 100))
var r2 = Math.round(random(70, 100))
var r3 = Math.round(random(80, 150))
var r4 = Math.round(random(90, 120))
var r5 = Math.round(random(83, 110))
var r6 = Math.round(random(100, 130))
var r7 = Math.round(random(95, 125))
var r8 = Math.round(random(77, 109))
var r9 = Math.round(random(101, 111))
var r10 = Math.round(random(95, 120))
var r11 = Math.round(random(80, 170))
var r12 = Math.round(random(100, 130))
if(frameCount%r1 ===0){
cstate = true
}
if(frameCount%r2 === 0){
dstate= true
}
if(frameCount%r3 === 0){
estate= true
}
if(frameCount%r4 === 0){
fstate= true
}
if(frameCount%r5 === 0){
gstate= true
}
if(frameCount%r6 === 0){
astate= true
}
if(frameCount%r7 === 0){
bstate= true
}
if(frameCount%r8 === 0){
csstate= true
}
if(frameCount%r9 === 0){
dsstate= true
}
if(frameCount%r10 === 0){
fsstate= true
}
if(frameCount%r11 === 0){
gsstate= true
}
if(frameCount%r12 === 0){
asstate= true
}
if(cstate === true){
c.display();
}
if(dstate === true){
d.display();
}
if(estate === true){
e.display();
}
if(fstate === true){
f.display();
}
if(gstate === true){
g.display();
}
if(astate === true){
a.display();
}
if(bstate === true){
b.display();
}
if(csstate === true){
cs.display();
}
if(dsstate === true){
ds.display();
}
if(fsstate === true){
fs.display();
}
if(gsstate === true){
gs.display();
}
if(asstate === true){
as.display();
}
if(mousePressedOver(C)&& cstate){
cstate = false;
C.shapeColor = "green";
player.score += 1;
}
if(mousePressedOver(D)&& dstate){
dstate = false;
D.shapeColor = "green";
player.score += 1;
}
if(mousePressedOver(E)&& estate){
estate = false;
E.shapeColor = "green";
player.score += 1;
}
if(mousePressedOver(F)&& fstate){
fstate = false;
F.shapeColor = "green";
player.score += 1;
}
if(mousePressedOver(G)&& gstate){
gstate = false;
G.shapeColor = "green";
player.score += 1;
}
if(mousePressedOver(A)&& astate){
astate = false;
A.shapeColor = "green";
player.score += 1;
}
if(mousePressedOver(B)&& bstate){
bstate = false;
B.shapeColor = "green";
player.score += 1;
}
if(mousePressedOver(Cs)&& cstate){
csstate = false;
Cs.shapeColor = "green";
player.score += 1;
}
if(mousePressedOver(Ds)&& dsstate){
dsstate = false;
Ds.shapeColor = "green";
player.score += 1;
}
if(mousePressedOver(Fs)&& fsstate){
fsstate = false;
Fs.shapeColor = "green";
player.score += 1;
}
if(mousePressedOver(Gs)&& gsstate){
gsstate = false;
Gs.shapeColor = "green";
player.score += 1;
}
if(mousePressedOver(As)&& asstate){
asstate = false;
As.shapeColor = "green";
player.score += 1;
}
player.updateScore(player.score);
text("score: "+player.score, 650, 40)
console.log(player.score)
}
getState() {
database.ref("gameState").on("value", (data)=>{
gamestate = data.val()
})
}
updateState(state) {
database.ref("/").update({
gameState : state
})
}
end() {
console.log("its the end of the game")
if(player.score >= 10 ){
text("you won", 900, height/2,)
} else {
text("you lost", 900, height/2)
}
}
}
player.js
class Player {
constructor() {
this.score = 0;
this.name = null;
this.index = null;
}
addPlayer() {
var playerIndex = "players/player" + this.index;
database.ref(playerIndex).set({
score : this.score,
name : this.name,
index : this.index,
})
}
getCount() {
database.ref("playerCount").on("value", (data) =>{
playercount = data.val()
})
}
updateCount(count) {
database.ref("/").update({playerCount : count})
}
updateScore(newScore) {
database.ref("players/player" + this.index).update({
score : newScore,
})
}
}
I tried seeing if there was a problem in my function to see why it was not updating in the database.
I am working on making a multi player game but I am having some problems with my log in and sign up system. Every time I try to log in the server stops running and I get the error callBack is not a function.
Here is my app.js code:
var mongojs = require("mongojs");
//Connect to database
var db = mongojs('localhost:27017/myGame', ['users','progress']);
var express = require('express');
var app = express();
var serv = require('http').Server(app);
app.get('/',function(req, res) {
res.sendFile(__dirname + '/client/index.html');
});
app.use('/client',express.static(__dirname + '/client'));
serv.listen(8080);
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.pressingShoot = false;
self.mouseAngle = 0;
self.maxSpd = 10;
var super_update = self.update;
self.update = function(){
self.updateSpd();
super_update();
if(self.pressingShoot){
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.spdX = self.maxSpd;
else if(self.pressingLeft)
self.spdX = -self.maxSpd;
else
self.spdX = 0;
if(self.pressingUp)
self.spdY = -self.maxSpd;
else if(self.pressingDown)
self.spdY = self.maxSpd;
else
self.spdY = 0;
};
Player.list[id] = self;
initPack.player.push({
id:self.id,
x:self.x,
y:self.y,
number:self.number,
});
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 === 'shoot')
player.pressingShoot = data.state;
else if(data.inputId === 'mouseAngle')
player.mouseAngle = data.state;
});
};
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({
id:player.id,
x:player.x,
y:player.y,
});
}
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){
//handle collision ex: hp--;
self.toRemove = true;
}
}
};
Bullet.list[self.id] = self;
initPack.bullet.push({
id: self.id,
x: self.x,
y: self.y,
});
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({
id:bullet.id,
x:bullet.x,
y:bullet.y
});
}
return pack;
};
var isValidPassword = function(data,callBack){
db.users.find({username:data.username,password:data.password}, function(err,res){
if(res.length > 0)
callBack(true);
else
callBack(false);
})
};
//Test to see if username already exists]
var isUsernameTaken = function(data,callBack){
db.users.find({username:data.username}, function(err,res){
if(res.length > 0)
callBack(true);
else
callBack(false);
})
};
//Add user
var addUser = function(data,callBack){
db.users.insert({username:data.username,password:data.password}, function(err){
callBack();
})
};
var io = require('socket.io')(serv,{});
io.sockets.on('connection', function(socket){
socket.id = Math.random();
SOCKET_LIST[socket.id] = socket;
socket.on('logIn', function(data){
if(isValidPassword(data)){
Player.onConnect(socket);
socket.emit('signInResponse', {success:true});
} else {
socket.emit('signInResponse', {success: false});
}
});
//Listen for sign up package
socket.on('signUp', function(data){
if(isUsernameTaken(data)){
socket.emit('signUpResponse',{success:false});
} else {
addUser(data);
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);
}
});
});
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);
and here is my index.html:
<div id="signDiv">
Username: <input id="signDiv-username" type="text"></input><br>
Password: <input id="signDiv-password" type="password"></input>
<button id="signDiv-logIn">Log in</button>
<button id="signDiv-signUp">Sign up</button>
</div>
<div id="gameDiv" style="display:none;">
<canvas id="ctx" width="500" height="500" style="border:1px solid #000000;"></canvas>
<!--Game Chat-->
<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>
var socket = io();
//log in and sign up for game
var signDiv = document.getElementById('signDiv');
var signDivUsername = document.getElementById('signDiv-username');
var signDivLogIn = document.getElementById('signDiv-logIn');
var signDivSignUp = document.getElementById('signDiv-signUp');
var signDivPassword = document.getElementById('signDiv-password');
signDivLogIn.onclick = function(){
socket.emit('logIn', {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("Log in unsuccessful")
});
socket.on('signUpResponse', function(data){
if(data.success){
alert("Sing up successful")
} else
alert("Sign up unsuccessful")
});
//Game chat, get elements
var chatText = document.getElementById('chat-text');
var chatInput = document.getElementById('chat-input');
var chatForm = document.getElementById('chat-form');
//Socket on for chat
socket.on('addToChat', function(data){
chatText.innerHTML += '<div>' + data + '</div>';
});
//Submit chat
chatForm.onsubmit = function(e){
e.preventDefault();
socket.emit('sendMsgToServer', chatInput.value);
chatInput.value = '';
};
//Game
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;
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;
Bullet.list[self.id] = self;
return self;
};
Bullet.list = {};
//Initialisation package
socket.on('init', function(data){
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])
}
});
//Update package
socket.on('update', function(data){
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;
}
}
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;
}
}
});
//Remove package
socket.on('remove',function(data){
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(){
ctx.clearRect(0,0,500,500);
for(var i in Player.list)
ctx.fillText(Player.list[i].number,Player.list[i].x,Player.list[i].y);
for(var i in Bullet.list)
ctx.fillRect(Bullet.list[i].x-5,Bullet.list[i].y-5,10,10);
},40);
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:'shoot', state:true});
};
document.onmouseup = function (event){
socket.emit('keyPress', {inputId:'shoot', 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>
I have tried a few different things and sometimes gotten the sign up working but never the log in. I am using a mongoDB database which all seems to be working fine.
Hey it seems like you are not passing any callback's function to isValidPassword,isUsernameTaken etc.
see this bit,
var isUsernameTaken = function(data,callBack){
db.users.find({username:data.username}, function(err,res){
if(res.length > 0)
callBack(true);
else
callBack(false);
})
};
//Listen for sign up package
socket.on('signUp', function(data){
if(isUsernameTaken(data)){
socket.emit('signUpResponse',{success:false});
} else {
addUser(data);
socket.emit('signUpResponse',{success:true});
}
});
the above can be written as,
//Listen for sign up package
socket.on('signUp', function (data) {
var callback = function (isTaken) {
if (isTaken) {
socket.emit('signUpResponse', {success: false});
} else {
addUser(data);
socket.emit('signUpResponse', {success: true});
}
};
isUsernameTaken(data , callback)
});
I am making a game where it's about clicking on the nearest yellow dot from the green dot.
I got a list named dots.
You can check out my codepen to see the code I'm using.
My problem is that when you're playing the game, sometimes some of the yellow dots are too close to each other. So I am thinking if it's possible to make a collision-detection or something else, to check if the yellow dots collides?
Here is a picture of my game...
I made a red circle around the problem:
The link to my codepen project: /lolkie02/pen/PJVOdy?editors=0010
If you wanna try the game, it only works through iPhone or Android browser since I made the buttons etc. 'touchstart' in the javascript.
function getDistance(obj1, obj2) {
return Math.floor(
Math.sqrt(Math.pow(obj1.cx - obj2.cx, 2) + Math.pow(obj1.cy - obj2.cy, 2))
);
}
function getRandomArbitrary(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
function comparator(a, b) {
if (a[1] < b[1]) return -1;
if (a[1] > b[1]) return 1;
return 0;
}
function difference(source, toRemove) {
return source.filter(function(value) {
return toRemove.indexOf(value) == -1;
});
}
////////////////
// global vars
////////////////
var svg = document.getElementById("svg");
var dotMatrix = document.createElementNS(
"http://www.w3.org/2000/svg",
"circle"
);
var lineMatrix = document.createElementNS("http://www.w3.org/2000/svg", "line");
var screenW = window.innerWidth;
var screenH = window.innerHeight;
var totalDist = document.getElementById("distance");
////////////////
// line constructor
////////////////
function Line(x1, y1, x2, y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.el = document.createElementNS("http://www.w3.org/2000/svg", "line");
this.class = "line";
this.update = function(x1, y1, x2, y2) {
this.el.setAttribute("x1", x1 || this.x1);
this.el.setAttribute("y1", y1 || this.y1);
this.el.setAttribute("x2", x2 || this.x2);
this.el.setAttribute("y2", y2 || this.y2);
this.setAttr("class", this.class);
};
this.setAttr = function(attr, value) {
this.el.setAttribute(attr, value);
};
this.append = function() {
svg.insertBefore(this.el, svg.firstChild);
};
}
////////////////
// dot constructor
////////////////
function Dot(r, cx, cy) {
this.r = r;
this.cx = cx;
this.cy = cy;
this.el = document.createElementNS("http://www.w3.org/2000/svg", "circle");
this.class = "dot";
this.update = function() {
this.el.setAttribute("r", this.r);
this.el.setAttribute("cx", this.cx);
this.el.setAttribute("cy", this.cy);
this.setAttr("class", this.class);
};
// activates a dot
this.activate = function() {
for (i = 0; i < dots.num; i++) {
dots.list[i].setAttr("data-selected", "false");
}
this.setAttr("data-selected", "true");
};
this.visited = function() {
this.setAttr("data-visited", "true");
};
// sets attribute to element
this.setAttr = function(attr, value) {
this.el.setAttribute(attr, value);
};
// gets attribute to element
this.getAttr = function(attr) {
return this.el.getAttribute(attr);
};
// appends element to svg and attaches event listeners
this.append = function() {
svg.appendChild(this.el);
this.el.addEventListener("touchstart", this.onClick);
};
// on click on element
this.onClick = function(event) {
//gets the id and the coords of the dot
var thisId = Number(event.target.getAttribute("data-id").substr(3, 2));
var thisCx = dots.list[thisId].cx;
var thisCy = dots.list[thisId].cy;
// calculates the distance between dots
var distances = [];
for (i = 0; i < dots.num; i++) {
distances[i] = [i, getDistance(dots.selected, dots.list[i])];
}
distances.sort(comparator);
distances.splice(0, 1);
var distancesLeft = [];
for (i = 0; i < distances.length; i++) {
if (dots.left.includes(distances[i][0])) {
distancesLeft.push(distances[i][0]);
}
}
//if the element is the nearest
if (thisId == distancesLeft[0] && dots.left.includes(thisId)) {
// calculates distances
var newDistance = getDistance(dots.list[thisId], dots.selected);
app.score.update(1); // punteggio x numero di poi
// app.score.update(newDistance); punteggio x distanza
//sets the active class to the selected dot
dots.list[thisId].activate();
dots.list[thisId].visited();
// creates the line
lines.list.push(
new Line(
dots.selected.cx,
dots.selected.cy,
dots.list[thisId].cx,
dots.list[thisId].cy
)
);
lines.list[lines.list.length - 1].update();
lines.list[lines.list.length - 1].append();
// creates the preview line
//TODO: eliminare le vecchie preline che rimangono vive
svg.addEventListener("mousemove", function prelineMove(e) {
mouseX = e.pageX;
mouseY = e.pageY;
app.preline.update(thisCx, thisCy, mouseX, mouseY);
});
//saves the selected dots coordinates
dots.selected.id = thisId;
dots.selected.cx = thisCx;
dots.selected.cy = thisCy;
//removes the dot from the list of remaining dots
for (i = 0; i < dots.left.length; i++) {
if (dots.left[i] === thisId) {
dots.left.splice(i, 1);
}
}
if (dots.left.length == 0) {
app.end(true);
}
} else {
app.end(false);
}
};
}
////////////////
// lines group
////////////////
var lines = {
list: []
};
////////////////
// dots group
////////////////
var dots = {};
dots.num = 20;
dots.list = [];
dots.start = 0;
dots.selected = {};
dots.selected.id = dots.start;
dots.left = [];
dots.preline;
////////////////
// app
////////////////
var app = {};
app.level = 2;
app.score = {};
app.score.number = 0;
app.score.el = document.getElementById("score");
app.score.update = function(score) {
app.score.number += score;
app.score.el.textContent = app.score.number;
};
app.score.reset = function() {
app.score.number = 0;
app.score.update(0);
};
app.results = function(points) {
if (points == "reset") {
sessionStorage.setItem("results", 0);
} else {
if (!sessionStorage.getItem("results")) {
sessionStorage.setItem("results", points);
} else {
var newscore = points;
sessionStorage.setItem("results", newscore);
}
}
};
app.launchScreen = function(lastScore, title, description, btnText) {
app.launchScreen.el = document.getElementById("launch-screen");
app.launchScreen.el.setAttribute("class", "is-visible");
var launchScreenTitle = document.getElementById("launch-screen__title");
launchScreenTitle.textContent = title;
var launchScreenDescription = document.getElementById(
"launch-screen__description"
);
launchScreenDescription.textContent = description;
app.launchScreen.btn = document.getElementById("start-btn");
app.launchScreen.btn.textContent = btnText;
app.launchScreen.btn.addEventListener("touchstart", function lauch() {
app.launchScreen.el.setAttribute("class", "");
app.start(app.level);
document.getElementById("score2").style.display = "block";
app.launchScreen.btn.removeEventListener("touchstart", lauch);
});
};
app.preline = new Line(0, 0, 200, 200);
app.preline.setAttr("id", "preline");
app.start = function(dotsNum) {
dots.num = dotsNum;
for (i = 0; i < dots.num; i++) {
var cx = getRandomArbitrary(45, screenW - 45);
var cy = getRandomArbitrary(45, screenH - 45);
dots.list[i] = new Dot(14, cx, cy);
dots.list[i].setAttr("data-id", "id-" + i);
dots.list[i].setAttr(
"style",
"animation-delay:" + i / 10 + "s; transform-origin: " + cx + 'px ' + cy + 'px;');
dots.list[i].update();
dots.list[i].append();
dots.left.push(i);
if (i == dots.start) {
dots.selected.cx = dots.list[dots.start].cx;
dots.selected.cy = dots.list[dots.start].cy;
dots.list[dots.start].setAttr("class", "dot dot--starting");
dots.left.splice(i, 1);
}
// adds the preline
app.preline.update(
dots.selected.cx,
dots.selected.cy,
dots.selected.cx,
dots.selected.cy
);
app.preline.append();
svg.addEventListener("mousemove", function prelineMove(e) {
mouseX = e.pageX;
mouseY = e.pageY;
app.preline.update(dots.selected.cx, dots.selected.cy, mouseX, mouseY);
});
}
// sets starting point
dots.list[dots.start].setAttr("data-selected", "true");
};
app.end = function(win) {
if (win) {
app.level += 2;
app.results(app.score.number);
} else {
app.level = 2;
}
dots.list = [];
dots.selected = {};
dots.left.length = 0;
svg.innerHTML = "";
if (win) {
app.launchScreen(
app.score.number,
"", //"Sådan!",
"", //"Din score er nu: " + sessionStorage.getItem("results") + ' Det næste level vil blive endnu hårdere.',
"NÆSTE LEVEL"
);
} else {
app.launchScreen(
0,
"", //"ARGH!",
"", //"Din endelige score blev: " + sessionStorage.getItem("results"),
"PRØV IGEN"
);
app.results("reset");
app.score.reset();
var score2 = document.getElementById('score2');
var number = score2.innerHTML;
number = 0;
score2.innerHTML = number;
document.getElementById("score2").style.display = "none";
}
};
app.launchScreen(
0,
"STIFINDER",
"Find den tætteste gule prik",
"SPIL"
);
$('.btn').on('touchstart',function(e,data) {
var score2 = document.getElementById('score2');
var number = score2.innerHTML;
number++;
score2.innerHTML = number;
});
Use Pythagorean theorem to determine whether the distance of the centers of two dots are closer (or equal) to the sum of their radii - in that case you have collision.
My answer to the similar question :https://stackoverflow.com/a/46973584/4154250
I have HTML application and someone wrote javascript library for that which is used for scrolling. Now i want to scroll to particular div with that library and i dont have to use location.href or `location.hash`` I have to do this with the JS library the code is something like this..
var ScrollPage = BGBiRepScroller.ScrollPage = function(){
this.animationFunList = [];
}
ScrollPage.prototype = {
$el:null,
$sectionList:null,
sectionPositionsY:null,
startTouchY:0,
startScrollY:0,
initTop:0,
endTouchY:0,
endDistance:0,
acceleration:8,
containerHeight:600,
currentSectionIndex:0,
isScrolling:false,
snapSection:true,
create: function($tEl){
this.$el = $tEl;
this.sectionPositionsY = new Array();
this.$sectionList = this.$el.find(".scrollSection");
var $origParent = this.$el.parent();
var $tempHolder = $("<div></div>");
$("body").append($tempHolder);
$tempHolder.css("opacity",0);
$tempHolder.append(this.$el);
this.$el.transition({ y: 0},0);
if(this.$sectionList.length>0){
this.initTop = this.$sectionList.position().top;
console.log("this.initTop::" + this.initTop);
for(var i=0; i<this.$sectionList.length; i++){
this.sectionPositionsY.push($(this.$sectionList[i]).position().top);
console.log($(this.$sectionList[i]).position().top);
}
}
$origParent.prepend(this.$el);
$tempHolder.remove();
this.createTouchEvents();
},
createTouchEvents: function(){
if(this.$el){
this.$el[0].ScrollPage = this;
this.$el.on(BGBiRep.Events.TOUCH_START, this._onTouchStart);
this.$el.on(BGBiRep.Events.TOUCH_END, this._onTouchEnd);
if(BGBiRep.isTouchDevice){
this.$el.on(BGBiRep.Events.TOUCH_MOVE, this._onTouchMove);
}
}
},
getSnapToY: function(_y){
var middleY = _y - this.containerHeight*.5;
if(this.snapSection){
for(var i=0; i<this.$sectionList.length; i++){
var $_currentEl = $(this.$sectionList[i]),
elTop = this.sectionPositionsY[i]-this.initTop;
if(-middleY<elTop){
//console.log('getSnapToY: middleY::' + middleY + ' ::elTop::' + elTop + ' ::this.initTop::' + this.initTop);
return 0;
}else if((-middleY>=elTop && -middleY<=elTop+$_currentEl.height()+10) || i==this.$sectionList.length-1){
//console.log("entering :: " + i);
this.currentSectionIndex = i;
if(i==0){return 0;}
return -(elTop - (this.containerHeight - $_currentEl.height())*.5);
}
}
}else{
console.log('_y::' + _y);
if(_y<-this.$el.find(".col1").height() + 550){
return -this.$el.find(".col1").height()+550;
}else if(_y>0){
return 0;
}else{
return _y;
}
}
return 0;
},
addAnimation: function(_sectionName, _function){
this.animationFunList.push(new Array(_sectionName, _function));
},
getAnimation: function(_sectionName){
for(var i=0; i<this.animationFunList.length; i++){
if(this.animationFunList[i][0] == _sectionName){
return this.animationFunList[i][1];
}
}
},
stopTransition: function(){
this.$el.css("transition", "transform 0s");
this.$el.css("-webkit-transition", "transform 0s");
},
_onTouchStart: function(event, touch){
var touch ;
this.ScrollPage.isScrolling = true;
if(BGBiRep.isTouchDevice){
touch = event.originalEvent.touches[0] || event.originalEvent.changedTouches[0];
}
var transformY = parseFloat(String(this.ScrollPage.$el.css('translate')).split(',')[1]) ;
this.ScrollPage.startTouchY = this.ScrollPage.endTouchY = (BGBiRep.isTouchDevice) ? touch.pageY : event.pageY;
this.ScrollPage.startScrollY = transformY;
if(!BGBiRep.isTouchDevice){
this.ScrollPage.$el.on(BGBiRep.Events.TOUCH_MOVE, this.ScrollPage._onTouchMove);
}
this.ScrollPage.stopTransition();
//this.ScrollPage.$el.css('-webkit-transition', '');
//this.ScrollPage.$el.css('transition', '');
},
_onTouchMove: function(event){
event.preventDefault();
var touch ;
this.ScrollPage.isScrolling = true;
if(BGBiRep.isTouchDevice){
touch = event.originalEvent.targetTouches[0];
}
var tY = (BGBiRep.isTouchDevice) ? touch.pageY : event.pageY;
var transY = this.ScrollPage.startScrollY - (this.ScrollPage.startTouchY - tY);
var maxY = (this.ScrollPage.snapSection)?(-this.ScrollPage.sectionPositionsY[this.ScrollPage.$sectionList.length-1]+this.ScrollPage.initTop):-this.ScrollPage.$el.find(".col1").height() + 580;
if(this.ScrollPage.currentSectionIndex == 0 && transY>0){
transY=0;
}else if(this.ScrollPage.currentSectionIndex == this.ScrollPage.$sectionList.length-1 && transY<maxY){
transY = maxY;
}else if(!this.ScrollPage.snapSection && transY<maxY){
transY = maxY;
}
this.ScrollPage.$el.transition({ y: transY},0);
this.ScrollPage.endDistance = this.ScrollPage.endTouchY-tY;
this.ScrollPage.endTouchY = tY;
},
_onTouchEnd: function(event, touch){
if(!BGBiRep.isTouchDevice){
this.ScrollPage.$el.off(BGBiRep.Events.TOUCH_MOVE, this.ScrollPage._onTouchMove);
}
if(this.ScrollPage.isScrolling){
var newY = this.ScrollPage.startScrollY - (this.ScrollPage.startTouchY - this.ScrollPage.endTouchY) - this.ScrollPage.endDistance*this.ScrollPage.acceleration;
console.log("newY::" + newY + "::" + this.ScrollPage.startScrollY + "-" + (this.ScrollPage.startTouchY - this.ScrollPage.endTouchY) + "-" +this.ScrollPage.endDistance*this.ScrollPage.acceleration);
this.ScrollPage.startScrollY = this.ScrollPage.startTouchY = this.ScrollPage.endTouchY = this.ScrollPage.endDistance=0;
//console.log("newY::-310::" + this.ScrollPage.getSnapToY(-310));
var tSCCROLL = this.ScrollPage;
this.ScrollPage.$el.css('-webkit-transition', '');
this.ScrollPage.$el.css('transition', '');
var tSnap =this.ScrollPage.getSnapToY(newY);
var transformY = parseFloat(String(this.ScrollPage.$el.css('translate')).split(',')[1]) ;
console.log('tSCCROLL.currentSectionIndex ' +tSCCROLL.currentSectionIndex);
var tFun = function(){
var tDid = $(tSCCROLL.$sectionList[tSCCROLL.currentSectionIndex]).attr("data-id");
console.log('inside tFun');
if(tDid && tDid!=''){
console.log('inside tDid');
tSCCROLL.getAnimation(tDid)();
console.log(tSCCROLL.getAnimation(tDid));
}
}
if(tSnap!=transformY){
tFun();
this.ScrollPage.$el.transition({ y: tSnap}, tFun);
}
}
this.ScrollPage.isScrolling = false;
}
}
There are section of div now on click i want to move to a particular section
$('.purple li').click(function(e)
{
//SOMETHING
});
How could i achieve this please someone help
I got a script which works in IE and chrome but not in FF.. Or it works in all three if I unescape the line where 'x' is alerted!?
in FF 3.6 the div is first visible when the script is half done.. it just jumps to the middle of the "moving line"
<div id="tst" style="position:absolute; top:200px; left:200px; height:100px; width:100px; background:#ff0000"></div>
<script type="text/javascript">
function Tween(){
this.time = 0;
this.duration = 800;
this.x_start = 0;
this.x_end = 0;
this.target_func = null;
this.method_func = null;
this.loop = null;
this.interval = 20;
this.start = function(){
if(!this.method_func){
this.method_func = this.regularEaseOut;
}
var _this = this;
this.loop = setInterval(function(){
if(_this.set_time() > 0){
var x = _this.method_func();
//alert(x);
_this.target_func(x);
}
}, this.interval);
};
this.set_time = function(){
this.time += this.interval;
if(this.time > this.duration){
clearInterval(this.loop);
this.time = 0;
}
return this.time;
};
this.regularEaseInOut = function(){
var t = this.time;
var s = this.x_start;
var e = this.x_end;
var d = this.duration;
if((t/=d/2) < 1){
return c/2*t*t + b;
}
else{
return -c/2 * ((--t)*(t-2) - 1) + b;
}
};
this.regularEaseIn = function(){
var t = this.time;
var s = this.x_start;
var e = this.x_end;
var d = this.duration;
return c*(t/=d)*t + b;
};
this.regularEaseOut = function(){
var t = this.time;
var s = this.x_start;
var e = this.x_end;
var d = this.duration;
return -e *(t/=d)*(t-2) + s;
};
}
var Tween = new Tween();
Tween.x_start = 200;
Tween.x_end = 1200;
Tween.target_func = function(x){
document.getElementById('tst').style.left = x+'px';
};
Tween.start();
</script>
This works:
<html>
<head>
<script type="text/javascript">
function Tween(){
this.time = 0;
this.duration = 800;
this.x_start = 0;
this.x_end = 0;
this.target_func = null;
this.method_func = null;
this.loop = null;
this.interval = 20;
this.start = function(){
if(!this.method_func){
this.method_func = this.regularEaseOut;
}
var _this = this;
this.loop = setInterval(function(){
if(_this.set_time() > 0){
var x = _this.method_func();
//alert(x);
_this.target_func(x);
}
}, this.interval);
};
this.set_time = function(){
this.time += this.interval;
if(this.time > this.duration){
clearInterval(this.loop);
this.time = 0;
}
return this.time;
};
this.regularEaseInOut = function(){
var t = this.time;
var s = this.x_start;
var e = this.x_end;
var d = this.duration;
if((t/=d/2) < 1){
return c/2*t*t + b;
}
else{
return -c/2 * ((--t)*(t-2) - 1) + b;
}
};
this.regularEaseIn = function(){
var t = this.time;
var s = this.x_start;
var e = this.x_end;
var d = this.duration;
return c*(t/=d)*t + b;
};
this.regularEaseOut = function(){
var t = this.time;
var s = this.x_start;
var e = this.x_end;
var d = this.duration;
return -e *(t/=d)*(t-2) + s;
};
}
function doYourThing() {
var tween = new Tween();
tween.x_start = 200;
tween.x_end = 1200;
tween.target_func = function(x){
document.getElementById('tst').style.left = x+'px';
};
tween.start();
}
</script>
</head>
<body onload="doYourThing()">
<div id="tst" style="position:absolute; top:200px; left:200px; height:100px; width:100px; background:#ff0000"></div>
</body>
</html>
So using onload makes sure the method is only run once the document is loaded. Also, you made an instance variable (Tween) with the same name as the "class" you want to instantiate. That will definitely cause you pain and misery down the road.
The alert stops the execution of the code until Ok is pressed. Check if this can be the source of your problems.
What does it mean not works?
if you mean it's not moving to the right, It works for me in my FF 4.0.1