I've been following this tutorial (http://creativejs.com/tutorials/three-js-part-1-make-a-star-field/) and everything is going fine, but I'd like to know how I can modify the script so then there's some form of callback when the particle reaches the end. I've modified the code in the tutorial so it's reversed the way the particles are moving.
What I'm wanting to try and create is a load of particles coming together to form a square, is it possible from using the code in the tutorial as a start and build on top of that or should I look elsewhere and start over?
Thanks in advance.
Wouldn't it be easy if you create the same amount of particles as the model's amount of vertices, and move the particles towards the vertices' position?
var p = emitter.geometry.vertices; // the vertices (particles) of your particle emitter
var m = model.geometry.vertices; // the vertices of the target model
for(var i in p) {
p[i].x = (p[i].x + m[i].x) / 2;
p[i].y = (p[i].y + m[i].y) / 2;
p[i].z = (p[i].z + m[i].z) / 2;
}
Related
I would like to make a blobby like attached link effect in my web.
[link]https://codepen.io/JuanFuentes/pen/mNVaBX
but I find the blob is not responsive when I try to scale the webpage.
the blob still in the original position.
can any friend help me?
It's not enough to simply resize the canvas! You should reposition your ball's vertices as well according to the new canvas size / height.
Here is updated code: https://codepen.io/gbnikolov/pen/xxZBVMX?editors=0010
Pay attention to line 52:
this.resize = function (deltaX, deltaY) {
// deltaX and deltaY are the difference between old canvas width / height and new ones
for (let i = 0; i < this.vertex.length; i++) {
const vertex = this.vertex[i]
vertex.x += deltaX
vertex.y += deltaY
}
}
EDIT: as you see, the blob takes some time to animate its vertices to the new position on resize. I am not sure wether this is good or bad for your purposes. A more advanced solution would be to stop the requestAnimationFrame() update loop, update the vertices to their new positions and only then start your loop again (so the blob "snaps" to its right position immediately).
EDIT 2: You don't need to return this from constructor functions when calling them with the new keyword, JS does this for you automatically:
var Blob = function(args) {
// ...
return this // <- thats not needed!
}
Read more about the this property and it's relationship to classes in JS here
The title says it all, I can't get an entity to move around the globe visually, even though its position is moving. This code will reproduce the problem in Sandcastle:
var viewer = new Cesium.Viewer('cesiumContainer');
var e = viewer.entities.add({
name : 'Sphere',
position: Cesium.Cartesian3.fromDegrees(-100, 30.0, 300000.0),
ellipsoid : {
radii : new Cesium.Cartesian3(200000.0, 200000.0, 200000.0)
}
});
viewer.scene.postRender.addEventListener(function(scene, time) {
var pos = e.position._value;
var cart = Cesium.Ellipsoid.WGS84.cartesianToCartographic(pos);
pos = Cesium.Cartesian3.fromRadians(cart.longitude + (1 * Math.PI / 180), cart.latitude, cart.height);
e.position = pos;
});
If you select the sphere in the demo, you'll see that the green selection indicator will be moving around the globe, but the sphere will be stuck in one place. I imagine there's some simple function call I'm missing, but I've been googling for the last few hours and I can't find a solution.
I've already looked at the Picking demo on Sandcastle, but nothing there seems to be relevant. The functionality I'm looking for is just to have a shape looping through the same set of coordinates indefinitely, so I can't use a SampledPositionProperty, as far as I've seen anyway.
I suspect the cause of this is a little tricky: In Cesium, the ellipsoid geometry is build asynchronously by a Web Worker. By asking for a change in position with every postRender event, you're basically thrashing the worker, it can't get one request finished before the next one starts. So we end up never seeing the position update at all. If you relax the speed a bit, you'll notice the position does update.
For example, here's your code again with postRender replaced by setInterval of 400ms. This is more like a clock ticking than a smooth animation, but it shows the position being updated:
var viewer = new Cesium.Viewer('cesiumContainer');
var e = viewer.entities.add({
name : 'Sphere',
position: Cesium.Cartesian3.fromDegrees(-100, 30.0, 300000.0),
ellipsoid : {
radii : new Cesium.Cartesian3(200000.0, 200000.0, 200000.0)
}
});
window.setInterval(function() {
var pos = e.position._value;
var cart = Cesium.Ellipsoid.WGS84.cartesianToCartographic(pos);
pos = Cesium.Cartesian3.fromRadians(cart.longitude + (1 * Math.PI / 180), cart.latitude, cart.height);
e.position = pos;
}, 400);
Currently there's no way to know from the Entity API when the worker is done updating the geometry. You may have to move this example out of Entity API and use the Primitive API instead.
I'm wanting to get some sprites moving between two points in my (very basic) javascript game. Each sprite is randomly placed in the level, so I want them to move back and forth between their base position. I have the code below
function Taniwha(pos) {
this.basePos = this.pos;
this.size = new Vector(0.6, 1);
this.move = basePos + moveDist(5,0));
}
Taniwha.prototype.type = "taniwha"
var moveSpeed = 4;
Taniwha.prototype.act = function(step) {
this.move = ???
and this is where I get stuck. I'm not sure how to tell it to go left, back to base pos, right then back to base pos again (I plan to loop this). Does anyone have any advice? (also using Eloquen Javascript's example game as an outline/guide for this, if how I'm doing things seems odd!)
For horizontal movement, change x coordinate of the position.
var pos = { x: 1, y: 2 };
pos.x++ ; // This will move right
pos.x-- ; // This will move left
Likewise for vertical movement. You also need to update the coordinates after change for the object which you are drawing.
In truth ,there are lots of library to develop a game.
Use those, control a sprite is very easy.
Like:
Pixijs
CreateJS
Both of them are opensource project, you can watch and learn the source.
And have lots of examples and document.
I'm creating a Pentomino puzzle game for a final project in a class I'm taking. I've created all dozen of the required puzzle pieces and can drag those around here. And I've tried this code to rotate the array (without using canvas.rotate() & located at the very bottom of the fiddle), it basically swaps the X & Y coordinates when drawing the new piece:
var newPiece = targetPiece;
pieces.splice(pieces.indexOf(targetPiece), 1);
targetPiece = null;
console.log(newPiece);
var geometry = [];
for (var i = 0; i < newPiece.geometry.length; i++) {
geometry.push([newPiece.geometry[i][3], newPiece.geometry[i][0]]);
}
var offset = [newPiece.offset[1], newPiece.offset[0]];
console.log(geometry);
console.log(offset);
newPiece.geometry = geometry;
newPiece.position = geometry;
newPiece.offset = offset;
pieces.push(newPiece);
console.log(pieces);
for (var j = 0; j < pieces.length; j++) {
draw(pieces[j]);
}
This doesn't work properly, but has promise.
In this fiddle, I've isolated the problem down to a single piece and tried to use canvas.rotate() to rotate the array by double clicking, but what's actually happening is it's rotating each piece of the array (I think), which results in nothing happening because each block of the array is just a 50x50 rectangle and when you rotate a square, it still looks just like a square.
function doubleClickListener(e) {
var br = canvas.getBoundingClientRect();
mouse_x = (e.clientX - br.left) * (canvas.width / br.width);
mouse_y = (e.clientY - br.top) * (canvas.height / br.height);
var pieceToggle = false;
for (var i = 0; i < pieces.length; i++) {
if (onTarget(pieces[i], mouse_x, mouse_y)) {
targetPiece = pieces[i];
rotate(targetPiece);
}
}
}
function rotate() {
targetPiece.rotationIndex = targetPiece.rotationIndex === 0 ?
1 : targetPiece.rotationIndex === 1 ?
2 : targetPiece.rotationIndex === 2 ?
3 : 0;
for (var j = 0; j < pieces.length; j++) {
draw(pieces[j]);
}
}
Just FYI, I've tried creating the puzzle pieces as individual polygons, but could not figure out how to capture it with a mousedown event and move it with mousemove, so I abandoned it for the canvas rectangle arrays which were relatively simple to grab & move.
There's a brute force solution to this, and a total rewrite solution, both of which I'd rather avoid (I'm up against a deadline-ish). The brute force solution is to create geometry for all possible pieces (rotations & mirroring), which requires 63 separate geometry variants for the 12 pieces and management of those states. The rewrite would be to use fabric.js (which I'll probably do after class is over because I want to have a fully functional puzzle).
What I'd like to be able to do is rotate the array of five blocks with a double click (don't care which way it goes as long as it's sequential 90° rotations).
Approaching a usable puzzle:
With lots of help from #absolom, here's what I have, you can drag with a mouse click & drag, rotate a piece by double clicking it, and mirror a piece by right clicking it (well, mostly, it won't actually rotate until you next move the piece, I'm working on that). The Z-order of the pieces are manipulated so that the piece you're working with is always on top (it has to be the last one in the array to appear on top of all the other pieces):
Pentominoes II
The final solution
I've just handed the game in for grading, thanks for all the help! There was a lot more tweaking to be done, and there are still some things I'd change if I rewrite it, but I'm pretty happy with the result.
Pentominoes Final
Quick & Dirty:
The quick & dirty solution is when 2+ pieces are assembled you create a single image of them (using an in-memory canvas). That way you can move / rotate the 2-piece-as-1-image as a single entity.
More Proper:
If the 2+ piece assembly must later be disassembled, then you will need the more proper way of maintaining transformation state per piece. That more proper way is to assign a transformation matrix to each piece.
Stackoverflow contributor Ken Fyrstenberg (K3N) has coded a nice script which allows you to track individual polygons (eg your rects) using transformation matrices: https://github.com/epistemex/transformation-matrix-js
Does this code do what you need? The rotate method looks like this now:
function rotate(piece) {
for (i = 0; i < piece.geometry.length; i++) {
var x = piece.geometry[i][0];
var y = piece.geometry[i][2];
piece.geometry[i][0] = -y;
piece.geometry[i][3] = x;
}
drawAll();
}
I simplified how your geometry and positioning was handled too. It's not perfect, but it can gives you some hints on how to handle your issues.
Please note that this solution works because each piece is composed of blocks with the same color and your rotations are 90 degrees. I only move the blocks around to simulate the rotation but nothing is rotated per-se. If you build your pieces differently or if you need to rotate at different angles, then you would need to go with another approach like transformation matrices.
UPDATE
Here is a better solution: fiddle
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.