How to make a realistic roulette ball spinning animation - javascript

I'm using PhysicsJS to make a 2D roulette ball spinning animation.
So far, I've implemented the following:
used a constraint so that the ball wouldn't "fly away":
rigidConstraints.distanceConstraint( wheel, ball, 1 );
used drag to slow down the ball:
world.add(Physics.integrator('verlet', { drag: 0.9 }));
made the wheel attract the ball, so that it would fall towards it when the drag has slowed down the ball enough
My questions:
how do I gradually slow down the ball spinning?
I have already a very high drag value, but it doesn't look like it's doing anything
how do I make attraction towards the wheel work?
The distance constraint should keep the ball from escaping, not from getting closer to the wheel.
why does angularVelocity: -0.005 not work at all on the wheel?
My code, also on JSfiddle
Physics(function (world) {
var viewWidth = window.innerWidth
,viewHeight = window.innerHeight
,renderer
;
world.add(Physics.integrator('verlet', {
drag: 0.9
}));
var rigidConstraints = Physics.behavior('verlet-constraints', {
iterations: 10
});
// create a renderer
renderer = Physics.renderer('canvas', {
el: 'viewport'
,width: viewWidth
,height: viewHeight
});
// add the renderer
world.add(renderer);
// render on each step
world.on('step', function () {
world.render();
});
// create some bodies
var ball = Physics.body('circle', {
x: viewWidth / 2
,y: viewHeight / 2 - 300
,vx: -0.05
,mass: 0.1
,radius: 10
,cof: 0.99
,styles: {
fillStyle: '#cb4b16'
,angleIndicator: '#72240d'
}
})
var wheel = Physics.body('circle', {
x: viewWidth / 2
,y: viewHeight / 2
,angularVelocity: -0.005
,radius: 100
,mass: 100
,restitution: 0.35
// ,cof: 0.99
,styles: {
fillStyle: '#6c71c4'
,angleIndicator: '#3b3e6b'
}
,treatment: "static"
});
world.add(ball);
world.add(wheel);
rigidConstraints.distanceConstraint( wheel, ball, 1 );
world.add( rigidConstraints );
// add things to the world
world.add([
Physics.behavior('interactive', { el: renderer.el })
,Physics.behavior('newtonian', { strength: 5 })
,Physics.behavior('body-impulse-response')
,Physics.behavior('body-collision-detection')
,Physics.behavior('sweep-prune')
]);
// subscribe to ticker to advance the simulation
Physics.util.ticker.on(function( time ) {
world.step( time );
});
// start the ticker
Physics.util.ticker.start();
});

Drag has a bug in that version of PhysicsJS, try using the most updated version from github. https://github.com/wellcaffeinated/PhysicsJS/issues/94
Unfortunately the distance constraint imposes a fixed distance. So to prevent the ball's escape in that way, you'd need to implement your own behavior. (more below)
You'll have to change behavior: "static" to be behavior: "kinematic". Static bodies don't ever move on their own.
To create a custom behavior check out the documentation here: https://github.com/wellcaffeinated/PhysicsJS/wiki/Behaviors#creating-a-custom-behavior
In order to get the functionality you're describing, you'll need to do something like this:
// in the behave method
// calculate the displacement of the ball from the wheel... something like....
disp.clone( wheel.state.pos ).vsub( ball.state.pos );
// if it's greater than max distance, then move it back inside the max radius
if ( disp.norm() > maxDist ){
var moveBy = disp.norm() - maxDist;
disp.normalize(); // unit vector towards the wheel
disp.mult( moveBy );
ball.state.pos.vadd( disp ); // move it back inside the max radius
}
Of course, this is a "just get it done" way of doing this but it should work.

Related

Phaser 3: Change "Hitbox"/Interactive area of sprite without physics

The game I'm creating doesn't require any physics, however you are able to interact when hovering over/clicking on the sprite by using sprite.setInteractive({cursor: "pointer"});, sprite.on('pointermove', function(activePointer) {...}); and similar. However I noticed two issues with that:
The sprite has some area which are transparent. The interactive functions will still trigger when clicking on those transparent areas, which is unideal.
When playing a sprite animation, the interactive area doesn't seem to entirely (at all?) change, thus if the sprite ends on a frame bigger than the previous, there end up being small areas I can't interact with.
One option I thought of was to create a polygon over my sprite, which covers the area I want to be interactive. However before I do that, I simply wanted to ask if there are simpler ways to fix these issues.
Was trying to find an answer for this myself just now..
Think Make Pixel Perfect is what you're looking for.
this.add.sprite(x, y, key).setInteractive(this.input.makePixelPerfect());
https://newdocs.phaser.io/docs/3.54.0/focus/Phaser.Input.InputPlugin-makePixelPerfect
This might not be the best solution, but I would solve this problem like this. (If I don't want to use physics, and if it doesn't impact the performance too much)
I would check in the event-handler, if at the mouse-position the pixel is transparent or so, this is more exact and less work, than using bounding-boxes.
You would have to do some minor calculations, but it should work well.
btw.: if the origin is not 0, you would would have to compensate in the calculations for this. (in this example, the origin offset is implemented)
Here is a demo, for the click event:
let Scene = {
preload ()
{
this.load.spritesheet('brawler', 'https://labs.phaser.io/assets/animations/brawler48x48.png', { frameWidth: 48, frameHeight: 48 });
},
create ()
{
// Animation set
this.anims.create({
key: 'walk',
frames: this.anims.generateFrameNumbers('brawler', { frames: [ 0, 1, 2, 3 ] }),
frameRate: 8,
repeat: -1
});
// create sprite
const cody = this.add.sprite(200, 100).setOrigin(0);
cody.play('walk');
cody.setInteractive();
// just info text
this.mytext = this.add.text(10, 10, 'Click the Sprite, or close to it ...', { fontFamily: 'Arial' });
// event to watch
cody.on('pointerdown', function (pointer) {
// calculate x,y position of the sprite to check
let x = (pointer.x - cody.x) / (cody.displayWidth / cody.width)
let y = (pointer.y - cody.y) / (cody.displayHeight / cody.height);
// just checking if the properties are set
if(cody.anims && cody.anims.currentFrame){
let currentFrame = cody.anims.currentFrame;
let pixelColor = this.textures.getPixel(x, y, currentFrame.textureKey, currentFrame.textureFrame);
// alpha > 0 a visible pixel of the sprite, is clicked
if(pixelColor.a > 0) {
this.mytext.text = 'Hit';
} else {
this.mytext.text = 'No Hit';
}
// just reset the textmessage
setTimeout(_ => this.mytext.text = 'Click the Sprite, or close to it ...' , 1000);
}
}, this);
}
};
const config = {
type: Phaser.AUTO,
width: 400,
height: 200,
scene: Scene
};
const game = new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>

Three.js OrbitControls tween animation to face(front) of the target object

When I click a button, I want OrbitControls(camera) be in front of the object(face side) smoothly by using tween.js.
I use this code but find that after changing controls.target and panning far from the target object, I only can zoom in a little level, and after I zoom in, I can't pan.
Is there another way to look at a object? Thanks!
var from = {
x: controls.target.x,
y: controls.target.y,
z: controls.target.z
};
var to = {
x: object.getWorldPosition().x,
y: object.getWorldPosition().y,
z: object.getWorldPosition().z
};
var tween = new TWEEN.Tween(from)
.to(to, 1000)
.easing(TWEEN.Easing.Quadratic.InOut) // | TWEEN.Easing.Linear.None
.onUpdate(function () {
controls.target.set( this.x, this.y, this.z )
})
.onComplete(function () {
controls.target.set( this.x, this.y, this.z )
})
.start();
Try the following: When the animation starts, disable the controls via controls.enabled = false; to prevent any interference with your animation. Next, implement the onComplete() callback of one of your tweens like so:
.onComplete(function() {
controls.enabled = true;
camera.getWorldDirection( lookDirection );
controls.target.copy( camera.position ).add( lookDirection.multiplyScalar( 10 ) );
})
The idea is enabling the controls again, computing the current look direction of your view and then setting a new target for the controls. You can also set a predefined target if you need an exact target spot for each camera position. The value 10 is in world units and determines how far away the target should be along the look direction.
Updated fiddle: https://jsfiddle.net/ckgo7qu8/

orbitcontrols.js: How to Zoom In/ Zoom Out

Using orbitcontrols.js (with THREE.js), I want to achieve the same effect in code as rotating the mouse wheel. For example, I want to call something like camera.zoomIn() and have it move a set distance toward the target. Anyone know how to do this?
At least for simple cases, you can change the position of the camera (e.g. multiply x, y and z by a factor), which automagically updates the OrbitControls.
Example with a <input type="range"> slider:
zoomer.addEventListener('input', function(e) {
var zoomDistance = Number(zoomer.value),
currDistance = camera.position.length(),
factor = zoomDistance/currDistance;
camera.position.x *= factor;
camera.position.y *= factor;
camera.position.z *= factor;
});
https://codepen.io/Sphinxxxx/pen/yPZQMV
From looking at the source code you can call .dollyIn(dollyScale) and .dollyOut(dollyScale) on the OrbitalControls object.
Edit: these aren't public methods; one can access them by editing OrbitalControls.js though.
I added this.dIn = dollyIn; to the THREE.OrbitControls function, I can now zoom in by calling controls.dIn(1.05); controls.update(); from outside.
You can set values on OrbitControls.maxDistance and OrbitControls.minDistance to zoom in and out programmatically.
For example, if you wanted to animate a zoom out with gsap you could do something like this:
gsap.to(myOrbitControls, {
minDistance: 20, // target min distance
duration: 1,
overwrite: 'auto',
ease: 'power1.inOut',
onComplete: () => {
myOrbitControls.minDistance = 0 // reset to initial min distance
},
})

Laser Animation with TweenJS and EaselJS

So, I'm trying to create a laser effect, similar to the one located at http://map.norsecorp.com/
For this example, I have a 500x500 canvas. The current javascript part of the solution is located below:
function shootLaser(x, y) {
var beam = new createjs.Shape();
beam.graphics.beginFill("red");
beam.graphics.moveTo(0,1.5).lineTo(70,0).lineTo(70,3).closePath();
beam.x = 80;
beam.y = 50;
stage.addChild(beam);
beam.setBounds(0,0,70,3);
createjs.Tween.get(beam,{ loop: true, onChange: beamUpdate })
.to({ x: 400 }, 1000, createjs.Ease.linear());
}
function beamUpdate(e) {
var beam = e.currentTarget.target;
var targetX = e.currentTarget._curQueueProps.x;
if( targetX - beam.x < beam.getBounds().width ) {
beam.scaleX = (targetX - beam.x) / targetX;
} else {
beam.scaleX = 1;
}
}
This draws the line the way that I want to. However the scaleX method doesn't quite work (not even close really, it just gets extremely small very fast).
The problem is that I can't find a way to shrink the "laser" once it hits it's target. If I shoot it from 0px to 250px. It should hit 250px and begin shrinking until the 250th pixel has "consumed" it for lack of a better term. Any help is greatly appreciated.
P.S. I'm also open to doing this with other libraries or tools. I just haven't found them yet.

Zoom and Pan in KineticJS

Is there a way one could zoom and pan on a canvas using KineticJS? I found this library kineticjs-viewport, but just wondering if there is any other way of achieving this because this library seems to be using so many extra libraries and am not sure which ones are absolutely necessary to get the job done.
Alternatively, I am even open to the idea of drawing a rectangle around the region of interest and zooming into that one particular area. Any ideas on how to achieve this? A JSFiddle example would be awesome!
You can simply add .setDraggable("draggable") to a layer and you will be able to drag it as long as there is an object under the cursor. You could add a large, transparent rect to make everything draggable. The zoom can be achieved by setting the scale of the layer. In this example I'm controlling it though the mousewheel, but it's simply a function where you pass the amount you want to zoom (positive to zoom in, negative to zoom out). Here is the code:
var stage = new Kinetic.Stage({
container: "canvas",
width: 500,
height: 500
});
var draggableLayer = new Kinetic.Layer();
draggableLayer.setDraggable("draggable");
//a large transparent background to make everything draggable
var background = new Kinetic.Rect({
x: -1000,
y: -1000,
width: 2000,
height: 2000,
fill: "#000000",
opacity: 0
});
draggableLayer.add(background);
//don't mind this, just to create fake elements
var addCircle = function(x, y, r){
draggableLayer.add(new Kinetic.Circle({
x: x*700,
y: y*700,
radius: r*20,
fill: "rgb("+ parseInt(255*r) +",0,0)"
})
);
}
var circles = 300
while (circles) {
addCircle(Math.random(),Math.random(), Math.random())
circles--;
}
var zoom = function(e) {
var zoomAmount = e.wheelDeltaY*0.001;
draggableLayer.setScale(draggableLayer.getScale().x+zoomAmount)
draggableLayer.draw();
}
document.addEventListener("mousewheel", zoom, false)
stage.add(draggableLayer)
http://jsfiddle.net/zAUYd/
Here's a very quick and simple implementation of zooming and panning a layer. If you had more layers which would need to pan and zoom at the same time, I would suggest grouping them and then applying the on("click")s to that group to get the same effect.
http://jsfiddle.net/renyn/56/
If it's not obvious, the light blue squares in the top left are clicked to zoom in and out, and the pink squares in the bottom left are clicked to pan left and right.
Edit: As a note, this could of course be changed to support "mousedown" or other events, and I don't see why the transformations couldn't be implemented as Kinetic.Animations to make them smoother.
this is what i have done so far.. hope it will help you.
http://jsfiddle.net/v1r00z/ZJE7w/
I actually wrote kineticjs-viewport. I'm happy to hear you were interested in it.
It is actually intended for more than merely dragging. It also allows zooming and performance-focused clipping. The things outside of the clip region aren't rendered at all, so you can have great rendering performance even if you have an enormous layer with a ton of objects.
That's the use case I had. For example, a large RTS map which you view via a smaller viewport region -- think Starcraft.
I hope this helps.
As I was working with Kinetic today I found a SO question that might interest you.
I know it would be better as a comment, but I don't have enough rep for that, anyway, I hope that helps.
These answers seems not to work with the KineticJS 5.1.0. These do not work mainly for the signature change of the scale function:
stage.setScale(newscale); --> stage.setScale({x:newscale,y:newscale});
However, the following solution seems to work with the KineticJS 5.1.0:
JSFiddle: http://jsfiddle.net/rpaul/ckwu7u86/3/
Unfortunately, setting state or layer draggable prevents objects not draggable.
Duopixel's zooming solution is good, but I would rather set it for stage level, not layer level.
Her is my solution
var stage = new Kinetic.Stage({
container : 'container',
width: $("#container").width(),
height: $("#container").height(),
});
var layer = new Kinetic.Layer();
//layer.setDraggable("draggable");
var center = { x:stage.getWidth() / 2, y: stage.getHeight() / 2};
var circle = new Kinetic.Circle({
x: center.x-100,
y: center.y,
radius: 50,
fill: 'green',
draggable: true
});
layer.add(circle);
layer.add(circle.clone({x: center.x+100}));
// zoom by scrollong
document.getElementById("container").addEventListener("mousewheel", function(e) {
var zoomAmount = e.wheelDeltaY*0.0001;
stage.setScale(stage.getScale().x+zoomAmount)
stage.draw();
e.preventDefault();
}, false)
// pan by mouse dragging on stage
stage.on("dragstart dragmove", function(e) {window.draggingNode = true;});
stage.on("dragend", function(e) { window.draggingNode = false;});
$("#container").on("mousedown", function(e) {
if (window.draggingNode) return false;
if (e.which==1) {
window.draggingStart = {x: e.pageX, y: e.pageY, stageX: stage.getX(), stageY: stage.getY()};
window.draggingStage = true;
}
});
$("#container").on("mousemove", function(e) {
if (window.draggingNode || !window.draggingStage) return false;
stage.setX(window.draggingStart.stageX+(e.pageX-window.draggingStart.x));
stage.setY(window.draggingStart.stageY+(e.pageY-window.draggingStart.y));
stage.draw();
});
$("#container").on("mouseup", function(e) { window.draggingStage = false } );
stage.add(layer);
http://jsfiddle.net/bighostkim/jsqJ2/

Categories

Resources