I-m working on a demo, it's very similar a one example in this page (http://chandlerprall.github.io/Physijs/examples/body.html ). It's just a box falling down. But I want to calculate the time taken since the box starts falling until it gets to the ground so I can calculate the velocity. Is there a way to do that?? Please help.
Here's an algorithm:
Animate : function (cb) {
//the above is whatever your initial animation function is
THREE.Clock.startTime = (new Date()).getMilliseconds();
if (objects touch ground) {
var now = (new Date()).getMilliseconds();
THREE.Clock.duration = now - THREE.Clock.startTime;
}
}
Related
Hi i am trying to move a spite from the top of the screen to the bottom. I want to achieve a gravity like effect. To pre-empt people suggesting using a game engine, A: this js is running on a node.js server and not a client (you may suggest a game engine for node) and B: this is the only place i need to use a gravity effect so i feel that surely it is simpler just to make a loop with some kind of acceleration calculations inside?
In this example i don't need to do anything except the calculations.
var theMeteor = {
"x":500, //the start x position
"y":1000, //the start y position
"v":1 // the velocity
};
function MeteorFall(dt){
theMeteor.y += (theMeteor.v * dt) * -1; // move the meteor down
theMeteor.v++;// increase the velocity
// keep looping until its at the bottom
if(theMeteor.y <= 0){
// its at the bottom so clear the loop
clearInterval(theDeamon);
}
}
var dt = 0.025; //set this to whatever the loop refreshes at (0.025 = 25)
var theDeamon = setInterval(MeteorFall, 25, dt);
This works but it's not very good at all, is there any one who can show me how to do this correctly please?
I know, this is a strange one. I'm trying to make a simple Javascript game where:
The player has to catch the randomly falling head hair.
The hair returns to the head when caught.
Catching the falling hair increases the Score
The hair falls faster and faster over time.
If all of the hair falls then it's GAME OVER.
I've given it a go, and copied most of it to my fiddle here, which is an abstract version of what I'm trying to achieve.
Current Javascript:
$(document).ready(function(){
//randomize hair initial rotation
$('.hair').each(function(){
var random = Math.random()*360;
var degree = "rotate("+random+"deg)";
$(this).css("transform",degree);
});
//set points to 0
$('#points').text(points);
});
function startGame() {
start = true;
var level = 1;
//move catcher with hand
$( document ).on("mousemove", function(event) {
var catcherX = event.pageX - 50;
$('#catcher').css("left",catcherX);
});
$('.hair').each(function() {
var wait = Math.ceil(Math.random()*10000)/level;
randomX = Math.random()*($('#gameDiv').width());
function makeDestination(hair) {
hair.css("top", 510);
hair.css("left", randomX);
}
setTimeout(makeDestination($(this)), wait)
})
};
startGame();
The biggest problems I'm having are:
How can I make the hair fall after a random interval? wait currently isn't doing anything in the setTimout function.
How can I make the hair function start again after being caught?
I also feel like there must be a much better way of writing this game, what do you guys think?
I made the setTimeout reference the function instead of calling it immediately (putting the parens calls it and references the return value, putting just the function name references). Then I tweaked the transition to animate the top over 3 seconds while the left takes just 1 second. Then I made makeDestination call itself after a delay. Lastly, the "hair" needs to jump back up to the top, so I change the transition to be immediate, change the CSS, then change the transition back to animate.
https://jsfiddle.net/9pq6xfxc/1/
I leave it to you to detect the intersection of the cyan box and the hair. While this can obviously be done on mouse movement, it's going to be trickier to find the hairs that fall on a stationary hand.
I was wondering if its possible to create an image using various lines and bez-curves that appears and then moves down the canvas and gets larger as it grows. The animation in question requires the room to fill with gas and so the the gas gets greater and greater as it moves around the canvas.
I had thought about just drawing the image and then using a for loop to move the image down until a certain y coordinate, but this doesnt help with the increasing part of the created image
Any help appreciated
There are different ways to make animations happen. What I normally do for my canvas games is that I have a gameloop that loops at a certain FPS that I decide at the start of my project. Each animation is normally controlled by time an speed.
var fps = 60;
var lastUpdateTime = +new Date(); //when did I last update the game?
function gameloop() {
var updateStartTime = +new Date();
update(updateStartTime-lastUpdateTime); //update the game for the according to the elapsed time since last update
lastUpdateTime = updateStartTime;
//Normally I also handle spawning stuff here
//I also remove old object in my gameloop
setTimeout(gameloop,1000/fps)
}
function update(elapsedTime) {
//This function update the locations of game elements such as player position, bullets, enemies, bananas etc. (or even gas clouds!)
//When I change a value, I use the time-parameter passed along with the call so that I get a smooth game even though the browser might lag.
playerX += velocity*timeElapsed; //as an example
}
Here's an example on your problem where I made a function to create a gas bubble object (yes, I do know how wrong it is to use gas bubbles =P). These objects travel downwards (physics?!) and increase in size (OK, this is starting to sound more and more crazy), just have a look:
http://jsfiddle.net/Niddro/ppa4xuw8/
How would a cheat/auto moving paddle in this hidden html game look like?
There is a
<div id="breakout-ball"><span>●</span></div>
and a
<div id="breakout-paddle"></div>
when moving the mouse the paddle is moved horizontally. How can I connect the movement of the ball with the paddle?
This question will become "community wiki" as soon as possible.
function cheat() {
var ball = document.getElementById('breakout-ball');
var paddle = document.getElementById('breakout-paddle');
paddle.style.left = ball.style.left;
setTimeout(cheat, 20);
}
cheat();
// Add this via the FireBug console.
I modified your solution slightly to account for the scenario of the ball going off screen and breaking the hack and also the ball getting jammed into the corner.
function cheat() {
var ball = document.getElementById('breakout-ball');
var paddle = document.getElementById('breakout-paddle');
var buffer = Math.floor((Math.random()*100)+1);
var leftVal = parseInt(ball.style.left, 10);
if (ball.style.left) {
paddle.style.left = (leftVal - buffer) + 'px';
}
setTimeout(cheat, 100);
}
cheat();
To be honest though, if you are going down that road why not do this?
function cheat() {
var paddle = document.getElementById('breakout-paddle');
paddle.style.width = '100%';
}
cheat();
Anyway I'm going to continue to dig into the code and do some deeper manipulation
in chrome, search the game, ctrl+J, paste the following in, and press enter.
This is a simple goal:
//get the ball's X position from its CSS
function ballx(){
return parseFloat(document.querySelector("#breakout-ball").style.left.split("px")[0]);
}
function update(e){
//throws an exception when the game isn't up. Can be really annoying.
try{document.querySelector("#breakout-paddle").style.left = (ballx() - 75)+"px";}
catch(ex){}
}
var intervalTimer = setInterval(update, 125);//let it have a single weakness in case someone else tries it while I am around.
The lower the interval rate, the faster the paddle will move relative to the ball, but the slower the game goes. The maximum rate can be given with a simple requestAnimationFrame cycle, but that slows the browser down a lot(at least on my laptop).
I tried changing the paddle's size. It doesn't really work.
I'm sure it would be simpler with jQuery, but why make cheating easy when doing it hard core is already so easy?
I have come up with a new way to solve this problem. Whenever the screen size or window size changes, the paddle changes size based on the screen size. To combat this, I simply just added another section that splits the size of the paddle in half then uses that value to find the centre of the paddle. Very simple and very effective.
function autoMove() {
var ball = document.getElementById('breakout-ball')
var paddle = document.getElementById('breakout-paddle')
var leftVal = parseInt(ball.style.left, 10)
var paddleWidth = parseFloat(paddle.style.width, 10) / 2
paddle.style.left = (leftVal - paddleWidth) + 'px'
setTimeout(autoMove, 20)
}
autoMove();
Also, didn't like the function name. It looks way too suspicious so changed it. Hope this helps.
I'm working on a project that uses SVG with Raphael.js. One component is a group of circles, each of which "wiggles" around randomly - that is, slowly moves along the x and y axes a small amount, and in random directions. Think of it like putting a marble on your palm and shaking your palm around slowly.
Is anyone aware of a Raphael.js plugin or code example that already accomplishes something like this? I'm not terribly particular about the effect - it just needs to be subtle/smooth and continuous.
If I need to create something on my own, do you have any suggestions for how I might go about it? My initial idea is along these lines:
Draw a circle on the canvas.
Start a loop that:
Randomly finds x and y coordinates within some circular boundary anchored on the circle's center point.
Animates the circle from its current location to those coordinates over a random time interval, using in/out easing to smooth the effect.
My concern is that this might look too mechanical - i.e., I assume it will look more like the circle is tracing a star pattern, or having a a seizure, or something like that. Ideally it would curve smoothly through the random points that it generates, but that seems far more complex.
If you can recommend any other code (preferably JavaScript) that I could adapt, that would be great too - e.g., a jQuery plugin or the like. I found one named jquery-wiggle, but that seems to only work along one axis.
Thanks in advance for any advice!
Something like the following could do it:
var paper = Raphael('canvas', 300, 300);
var circle_count = 40;
var wbound = 10; // how far an element can wiggle.
var circleholder = paper.set();
function rdm(from, to){
return Math.floor(Math.random() * (to - from + 1) + from);
}
// add a wiggle method to elements
Raphael.el.wiggle = function() {
var newcx = this.attrs.origCx + rdm(-wbound, wbound);
var newcy = this.attrs.origCy + rdm(-wbound, wbound);
this.animate({cx: newcx, cy: newcy}, 500, '<');
}
// draw our circles
// hackish: setting circle.attrs.origCx
for (var i=0;i<circle_count;i++) {
var cx = rdm(0, 280);
var cy = rdm(0, 280);
var rad = rdm(0, 15);
var circle = paper.circle(cx, cy, rad);
circle.attrs.origCx = cx;
circle.attrs.origCy = cy;
circleholder.push(circle);
}
// loop over all circles and wiggle
function wiggleall() {
for (var i=0;i<circleholder.length;i++) {
circleholder[i].wiggle();
}
}
// call wiggleAll every second
setInterval(function() {wiggleall()}, 1000);
http://jsfiddle.net/UDWW6/1/
Changing the easing, and delays between certain things happening should at least help in making things look a little more natural. Hope that helps.
You can accomplish a similar effect by extending Raphael's default easing formulas:
Raphael.easing_formulas["wiggle"] = function(n) { return Math.random() * 5 };
[shape].animate({transform:"T1,1"}, 500, "wiggle", function(e) {
this.transform("T0,0");
});
Easing functions take a ratio of time elapsed to total time and manipulate it. The returned value is applied to the properties being animated.
This easing function ignores n and returns a random value. You can create any wiggle you like by playing with the return formula.
A callback function is necessary if you want the shape to end up back where it began, since applying a transformation that does not move the shape does not produce an animation. You'll probably have to alter the transformation values.
Hope this is useful!
There is a very good set of easing effects available in Raphael.
Here's a random set of circles that are "given" bounce easing.
Dynamically add animation to objects
The full range of easing effects can be found here. You can play around with them and reference the latest documentation at the same time.
Putting calls in a loop is not the thing to do, though. Use callbacks, which are readily available.