Creating gravity point with Matter.js [duplicate] - javascript

Is it possible to create a single gravity / force point in matter.js that is at the center of x/y coordinates?
I have managed to do it with d3.js but wanted to enquire about matter.js as it has the ability to use multiple polyshapes.
http://bl.ocks.org/mbostock/1021841

The illustrious answer has arisen:
not sure if there is any interest in this. I'm a fan of what you have created. In my latest project, I used matter-js but I needed elements to gravitate to a specific point, rather than into a general direction. That was very easily accomplished. I was wondering if you are interested in that feature as well, it would not break anything.
All one has to do is setting engine.world.gravity.isPoint = true and then the gravity vector is used as point, rather than a direction. One might set:
engine.world.gravity.x = 355;
engine.world.gravity.y = 125;
engine.world.gravity.isPoint = true;
and all objects will gravitate to that point.
If this is not within the scope of this engine, I understand. Either way, thanks for the great work.

You can do this with the matter-attractors plugin. Here's their basic example:
Matter.use(
'matter-attractors' // PLUGIN_NAME
);
var Engine = Matter.Engine,
Events = Matter.Events,
Runner = Matter.Runner,
Render = Matter.Render,
World = Matter.World,
Body = Matter.Body,
Mouse = Matter.Mouse,
Common = Matter.Common,
Bodies = Matter.Bodies;
// create engine
var engine = Engine.create();
// create renderer
var render = Render.create({
element: document.body,
engine: engine,
options: {
width: Math.min(document.documentElement.clientWidth, 1024),
height: Math.min(document.documentElement.clientHeight, 1024),
wireframes: false
}
});
// create runner
var runner = Runner.create();
Runner.run(runner, engine);
Render.run(render);
// create demo scene
var world = engine.world;
world.gravity.scale = 0;
// create a body with an attractor
var attractiveBody = Bodies.circle(
render.options.width / 2,
render.options.height / 2,
50,
{
isStatic: true,
// example of an attractor function that
// returns a force vector that applies to bodyB
plugin: {
attractors: [
function(bodyA, bodyB) {
return {
x: (bodyA.position.x - bodyB.position.x) * 1e-6,
y: (bodyA.position.y - bodyB.position.y) * 1e-6,
};
}
]
}
});
World.add(world, attractiveBody);
// add some bodies that to be attracted
for (var i = 0; i < 150; i += 1) {
var body = Bodies.polygon(
Common.random(0, render.options.width),
Common.random(0, render.options.height),
Common.random(1, 5),
Common.random() > 0.9 ? Common.random(15, 25) : Common.random(5, 10)
);
World.add(world, body);
}
// add mouse control
var mouse = Mouse.create(render.canvas);
Events.on(engine, 'afterUpdate', function() {
if (!mouse.position.x) {
return;
}
// smoothly move the attractor body towards the mouse
Body.translate(attractiveBody, {
x: (mouse.position.x - attractiveBody.position.x) * 0.25,
y: (mouse.position.y - attractiveBody.position.y) * 0.25
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.12.0/matter.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/matter-attractors#0.1.6/build/matter-attractors.min.js"></script>
Historical note: the "gravity point" functionality was proposed as a feature in MJS as PR #132 but it was closed, with the author of MJS (liabru) offering the matter-attractors plugin as an alternate. At the time of writing, this answer misleadingly seems to indicate that functionality from the PR was in fact merged.
Unfortunately, the attractors library is 6 years outdated at the time of writing and raises a warning when using a newer version of MJS than 0.12.0. From discussion in issue #11, it sounds like it's OK to ignore the warning and use this plugin with, for example, 0.18.0. Here's the warning:
matter-js: Plugin.use: matter-attractors#0.1.4 is for matter-js#^0.12.0 but installed on matter-js#0.18.0.
Behavior seemed fine on cursory glance, but I'll keep 0.12.0 in the above example to silence it anyway. If you do update to a recent version, note that Matter.World is deprecated and should be replaced with Matter.Composite and engine.gravity.

Related

Surrounding 3d sound effects using howler.js or another library?

I'm working on a project and I need to add 3d sounds effects, like the sound is continually moving around the listener effects. Is it possible to achieve that with howlerjs i see that with howler i'm able to play a sound from specific coordinates/orientation but how to achieve surrounding/ambisonics sounds ?
Or another library in JavaScript to achieve that?
Thanks for your help.
Half a year late, but yeah that's entirely possible in howler.js, haven't used it myself but judging from the docs you can just update the position. there's some more libraries that do it that I've found, check here how 3dage does exactly what you want:
https://codepen.io/naugtur/pen/QgmvOB?editors=1010
var world = IIIdage.World({
tickInterval: 200
})
var annoyingFly = IIIdage.Thing({
is: ['fly'],
sounds: {
'buzzing constantly': {
sound: 'buzz',
times: Infinity
}
},
reacts: [
{
// to: world.random.veryOften(),
to: world.time.once(),
with: 'buzzing constantly'
}
]
})
// scene should create and expose a default world or accept one
var scene = IIIdage.Scene({
title: 'Annoying fly',
library: {
sounds: {
'buzz': {
src: ['https://webaudiogaming.github.io/3dage/fly.mp3']
}
}
},
world: world,
things: [ // scene iterates all things and spawns them into the world. same can be done manually later on.
annoyingFly({
pos: [-1, -15, 0],
dir: [1, 0, 0],
v: 1
})
]
}).load().run()
setTimeout(function () {
scene.dev.trace(IIIdage.dev.preview.dom())
}, 500)
setInterval(function rotateVector() {
var angleRad = 0.15
var d=scene.things[0].attributes.dir
var x=d[0], y=d[1]
var cosAngle = Math.cos(angleRad), sinAngle = Math.sin(angleRad)
scene.things[0].attributes.dir = [x * cosAngle - y * sinAngle, y * cosAngle + x * sinAngle, 0]
}, 500)
window.scene = scene
There's still some others that do similar stuff:
https://www.npmjs.com/package/songbird-audio
https://www.npmjs.com/package/ambisonics
Hope this pushes you in the right direction if you still want help with it.

Openlayers3 - fractional zoom on touch device using pinch gesture?

Openlayers3 can display a map at a fractional zoom level programmatically by specifying a fractional number in setZoom().
However, I want my users to be able to get a fractional zoom level on a mobile touch-driven device (ie, a smart phone). Pinch or reverse pinch zooms out/in by jumping to the nearest whole zoom level when the fingers are removed from the screen.
How can a touch/mobile user get Openlayers3 to stay at the exact extent (fractional zoom level) that the user has pinched to?
Is there something I can add to the javascript for my Openlayers3 map or view to get this to work as desired?
In particular, I note that Openlayers3 has a ol.interaction.PinchZoom() class ( https://openlayers.org/en/latest/apidoc/ol.interaction.PinchZoom.html ). This is a subclass of ol.interaction.Pointer which has a handleUpEvent and a handleEvent (which should be a function). So in theory, I should be able to either replace the handleUpEvent in PinchZoom OR replace the default PinchZoom interaction with one that has a custom event handler function. But with both of these approaches, I can't get my new handleUpEvent function to be called.
(While trawling the OL code for PinchZoom I have found that the default PinchZoom does what I want if one finger is lifted from the touch-screen before the other finger, but I still want to get this working when both fingers are lifted simultaneously.)
Here is what I've tried so far...
FIRST ATTEMPT - This just attempts to replace the standard PinchZoom's handleUpEvent with a custom one, and set this as the only interaction for the map. However, the event function is never called (never logs anything).
function handleUpEvent(evt) {
console.log("Up event handler");
return true; // Stop drag
}
map = new ol.Map({
layers: [],
target: 'map',
controls: controls,
interactions: [new ol.interaction.PinchZoom({handleEvent: handleUpEvent})],
view: new ol.View({projection: projCode})
});
SECOND ATTEMPT - This attempt is based on the actual OL code for creating the standard PinchZoom interaction. In this case, all my event handler functions DO get called, the number of touches ( targetPointers ) is always zero (as logged). I'm no javascript guru, but I suspect that this is because the symbols in ol.js are different to in ol-debug.js which I'm basing this on. In fact I had to declare targetPointers myself to even get this to run, even though it is declared by OL itself already (but presumably using a different symbol name in the non-debug version).
function handleDownEvent(mapBrowserEvent) {
console.log("DOWN event handler");
this.anchor_ = null;
this.lastDistance_ = undefined;
this.lastScaleDelta_ = 1;
mapBrowserEvent.map.render();
return true; // Start drag
}
function handleDragEvent(mapBrowserEvent) {
if ( this.targetPointers.length < 2 ) {
console.log("DRAG event ignored - touches ", this.targetPointers.length);
} else {
console.log("DRAG event handled");
var scaleDelta = 1.0;
var touch0 = this.targetPointers[0];
var touch1 = this.targetPointers[1];
var dx = touch0.clientX - touch1.clientX;
var dy = touch0.clientY - touch1.clientY;
// distance between touches
var distance = Math.sqrt(dx * dx + dy * dy);
if (this.lastDistance_ !== undefined) {
scaleDelta = this.lastDistance_ / distance;
}
this.lastDistance_ = distance;
if (scaleDelta != 1.0) {
this.lastScaleDelta_ = scaleDelta;
}
var map = mapBrowserEvent.map;
var view = map.getView();
var resolution = view.getResolution();
// scale anchor point.
var viewportPosition = map.getViewport().getBoundingClientRect();
var centroid = ol.interaction.Pointer.centroid(this.targetPointers);
centroid[0] -= viewportPosition.left;
centroid[1] -= viewportPosition.top;
this.anchor_ = map.getCoordinateFromPixel(centroid);
// scale, bypass the resolution constraint
map.render();
ol.interaction.Interaction.zoomWithoutConstraints(
map, view, resolution * scaleDelta, this.anchor_);
}
}
function handleUpEvent(mapBrowserEvent) {
console.log("UP event handler");
return true; // Stop drag
}
var pinchZoom = new ol.interaction.Pointer({
handleDownEvent: handleDownEvent,
handleDragEvent: handleDragEvent,
handleUpEvent: handleUpEvent
});
pinchZoom.targetPointers = [];
map = new ol.Map({
interactions: ol.interaction.defaults().extend([pinchZoom]),
layers: [
new ol.layer.Tile({
source: new ol.source.TileJSON({url: 'https://api.tiles.mapbox.com/v3/mapbox.geography-class.json?secure'})
})
],
target: 'map',
view: new ol.View({center: [0, 0], zoom: 3})
});
The problems with your attempts:
First attempt
The option handleEvent for ol.interaction.PinchZoom does not exists. That is why your callback is not executed.
Second attempt
As you already noted you try to use openlayers internals. This might work with the debug build but will not work in the release build as the names are different than.
Solution
Add the option to keep a fractional resolution at the pinch zoom end in the openlayers sources.
Issue: https://github.com/openlayers/ol3/issues/6223
Pull request: https://github.com/openlayers/ol3/issues/6224
The pinch zoom will by default keep the fractional zoom level as chosen by the user .. starting with OpenLayers 3.20
An earlier idea:
As an example I added the option keepFractionalZoomLevel to ol.interaction.PinchZoom: https://github.com/aAXEe/ol3/commit/7639cb20d17858492652896bcd4a6ff7992a9bb0
See this fiddle for a working example: https://jsfiddle.net/wm78prro/5/
Note: The fiddle uses a custom openlayers build: https://github.com/aAXEe/ol3/pull/1
The deploy url is: https://deploy-preview-1--pump-attendant-rhinoceros-42285.netlify.com/ol-debug.js
Does this example behave as you want?
As this may be usefull for others we can try to integrate it into openlayers.

Three.js - how can I use an EllipseCurve as an extrusion path?

The problem:
In the awesome Three.js, I can't figure out how to convert an EllipseCurve into a path that I can extrude along.
In the example below, if I uncomment the LineCurve3, my square extrudes along it nicely. If I run it as the EllipseCurve, there are no errors but nothing shows on screen. I have tried zooming the camera right out to make sure it's not off the screen for any reason.
I know the EllipseCurve is being generated correctly as I can write it out with a line material (not shown in the code below).
The code
var radius = 1100;
var degreesStart = 75;
var degreesEnd = 30;
var radiansStart = (degreesStart * Math.PI) / 180;
var radiansEnd = ((degreesEnd) * Math.PI) / 180;
// this won't seem to work as an extrude path, but doesn't give any errors
var path = new THREE.EllipseCurve(0, 0, radius, radius, radiansStart, radiansEnd, true);
// this works fine as an extrude path
//var path = new THREE.LineCurve3(new THREE.Vector3(0, 0, 0), new THREE.Vector3(1000, 1000, 0));
var extrusionSettings = { steps: 100, bevelEnabled: false, extrudePath: path };
// draw a square to extrude along the path
var sectionSize = [];
sectionSize.push(new THREE.Vector2(0, 0));
sectionSize.push(new THREE.Vector2(1000, 0));
sectionSize.push(new THREE.Vector2(1000, 1000));
sectionSize.push(new THREE.Vector2(0, 1000));
var sectionShape = new THREE.Shape(sectionSize);
var componentGeometry = new THREE.ExtrudeGeometry(sectionShape, extrusionSettings);
var component = new THREE.Mesh(componentGeometry, material);
group.add(component);
What I have tried:
My attempts to make it work have all tried to extract the points from the curve into a path to use in the extrusion. The closest I felt I got was
var ellipsePath = new THREE.CurvePath(path.getSpacedPoints(20));
// where 'path' is my EllipseCurve in the code above
// (and then changed the extrusion settings to use 'ellipsePath ' instead).
This gave the error "Cannot read property 'distanceTo' of null".
I can't seem to get my head around how the EllipseCurve relates to points that relate to a path.
Can anyone point me in the right direction please, or have code where you've come across the same problem? Many thanks.
I ran into the same problem. After experimenting with EllipseCurve and CurvePath, I concluded that these two are building 2D paths which lead to problems inside ExtrudeGeometry. Examining the source of three.js and the example extrusion based on a 3D spline, I built my own Curve and defined a 3D .getPoint function. This solved the problem and rendered a perfect extrusion. Replace the "var path" line of your code with the following:
var path = new THREE.Curve();
path.getPoint = function (t) {
// trace the arc as t ranges from 0 to 1
var segment = (radiansStart - radiansEnd) * t;
return new THREE.Vector3(radius * Math.cos(segment), radius * Math.sin(segment), 0);
};
Inspired by #james-dunn’s solution, I implemented a Path3D class that’s the same as a regular THREE.Path except that getPoint() returns a Vector3 with z = 0:
class Path3D extends THREE.Path {
constructor(pts) {
super(pts);
}
getPoint(t) {
const pt2d = super.getPoint(t);
const pt3d = new THREE.Vector3(pt2d.x, pt2d.y, 0);
return pt3d;
}
}

recommended way to extend classes in Paper.js

Is there a recommended way to extend classes in Paper.js? In particular, I am interested in extending Path
Pardon if my terminology is incorrect, but I am essentailly asking the same question about paper that is being asked about three here
Based on your comment to the initial version of my answer, you are looking for the 'extend' function (oops, that was exactly what you meant) to do subclassing. In an email to the paper.js mailing list, Jürg Lehni (one of the creators) said:
As for subclassing, that's not something that is supported at the
moment. It might work, it might not, it might work in most cases, but
not in very rare cases that are hard to pinpoint, it might need only a
couple of changes to make it work well, but those might be in many
different places.
For example, each Item subclass has a _type property which is a string
representing its type. Sometimes we check that instead of using
instanceof, because it's faster, and so far, for example for Path we
just assumed there would be no subclassing.
A complication is that there are no paper.Path.Rectangle objects. There are paths, and there are rectangles, but when you call new paper.Path.Rectangle() it creates a new Path using initialization code (createRectangle) that creates a rectangular shape.
So we would need to extend paper.Path. Unfortunately, when you call new paper.Path.Rectangle it calls createPath, which always returns a Path (not your extension). It may be possible to do something like:
var SuperRectangle = paper.Path.extend({
otherFunc: function() {
console.log('dat');
}
});
...and with correctly substituting/overriding for createRectangle or createPath get a subclass to work. Unfortunately, I have not been able to manage it.
My first working recommendation is to make a factory and add your functions to the objects in that factory (jsbin here):
var createSuperRectangle = function(arguments){
var superRect = new paper.Path.Rectangle(arguments);
superRect.otherFunc = function(){
console.log('dat');
}
return superRect;
}
var aRect = new Rectangle(20, 30, 10, 15);
var aPath = createSuperRectangle({
rectangle: aRect,
strokeColor: 'black'
});
aPath.otherFunc();
Similarly, you can use the factory to just change the prototype for your SuperRectangles, having added your functions to that prototype object (and making its prototype the one from paper.Path.__proto__) (jsbin here):
var superRectProto = function(){};
var tempRect = new paper.Path.Rectangle();
tempRect.remove();
superRectProto.__proto__ = tempRect.__proto__;
superRectProto.otherFunc = function(){
console.log('dat');
}
delete tempRect;
var createSuperRectangle = function(arguments){
var superRect = new paper.Path.Rectangle(arguments);
superRect.__proto__ = superRectProto;
return superRect;
}
var aRect = new Rectangle(20, 30, 10, 15);
var aPath = createSuperRectangle({
rectangle: aRect,
strokeColor: 'black'
});
aPath.otherFunc();
Alternatively, you can make an object that encapsulates the Path (jsbin here):
var SuperRectangle = function(arguments){
this.theRect = new paper.Path.Rectangle(arguments);
this.otherFunc = function(){
console.log('dat');
}
}
var aRect = new Rectangle(20, 30, 10, 15);
var aPath = new SuperRectangle({
rectangle: aRect,
strokeColor: 'black'
});
aPath.otherFunc();
aPath.theRect.strokeWidth = 5;
Unfortunately, then to access the path you have to use the theRect variable.
Initial incorrect answer follows:
I don't think you mean "extending classes". In Javascript you can extend objects so that they have more functions, so extending the Path "class" would mean all Path objects have the same new functions. Javascript object extension is further described here.
If I'm wrong, and you do want to extend Path, then you can use:
paper.Path.inject({
yourFunctionName: function(anyArgumentsHere) {
// your function here
}
});
However, I think you are actually talking about creating new objects that mostly behave like Path objects but have different functionality from each other. If that is the case, then you may want to look at this answer about Javascript using prototypical inheritance. For example, here I create two Rectangle objects that behave differently when I ask them to doSomething (jsbin here):
var rect1 = new Path.Rectangle({
point: [0, 10],
size: [100, 100],
strokeColor: 'black'
});
rect1.doSomething = function() {
this.fillColor = new Color('red');
};
var rect2 = new Path.Rectangle({
point: [150, 10],
size: [100, 100],
strokeColor: 'black'
});
rect2.doSomething = function() {
this.strokeWidth *= 10;
};
rect1.doSomething();
rect2.doSomething();
A couple of things.
1) You can wrap the original paperjs object but this is very much a hack
paperjs playground
function SuperSquare() {
this.square = new Path.Rectangle({
size:50,
fillColor:'red',
onFrame:function(base) {
var w2 = paper.view.element.width / 2;
this.position.x = Math.sin(base.time) * w2 + w2;
}
});
}
SuperSquare.prototype.setFillColor = function(str) {
this.square.fillColor = str;
}
var ss = new SuperSquare();
ss.setFillColor('blue');
2) I may clone & create a paper 2017 which operates off of es6 so that you can use the extend keyword.
3) I wrote an application called Flavas but it never gained a following so I just kind of left it. That being said, I have been playing with it lately; upgrading it to es6. With it you can do what you're talking about.
class Square extends com.flanvas.display.DisplayObject {
constructor(size) {
this.graphics.moveTo(this.x, this.y);
this.graphics.lineTo(this.x + size, this.y);
this.graphics.lineTo(this.x + size, this.y + size);
this.graphics.lineTo(this.x, this.y + size);
}
someMethod(param) {
trace("do something else", param);
}
);
I wrote all this kind of quick so feel free to hit me up with Q's.

Thickness of lines using THREE.LineBasicMaterial

I am using the code below to create hundreds of lines in my three.js scene
edgeGeometry[i] = new THREE.Geometry();
edgeGeometry[i].vertices[0] = v(x1,y1,z1);
edgeGeometry[i].vertices[1] = v(x2,y2,z2);
edgesMat[i] = new THREE.LineBasicMaterial({
color: 0x6699FF, linewidth: 1, fog:true});
edge[i] = new THREE.Line(edgeGeometry[i], edgesMat[i]);
edge[i].type = THREE.Lines;
scene2.add(edge[i]);
It works just fine, but when i change the value of "linewidth" to a bigger OR smaller value, i see NO difference in the scene.
How should i change the thickness of the lines? Any ideas?
Thanks, Dimitris
1) Use native OpenGL
You can achieve rendering of line thicknesses with a workaround by setting your browser to use native OpenGL instead of ANGLE. You can read here on how to do this on Chrome.
Keep in mind that you will experience performance differences if you swap to native OpenGL.
EDIT:
The master MrDoob himself posted here how to do this for both Chrome and Firefox.
Note: This first option is no longer a valid solution since the latest OpenGL versions no longer support line thickness either. Check also #gman his answer. This means if you want to use line thickness the second option is the way to go.
2) Use THREE.MeshLine class
There is also another solution; this THREE.MeshLine class on github is a nice workaround. It comes with a special THREE.MeshLineMaterial. According to the docs it is as simple as:
Create and populate a geometry
Create a THREE.MeshLine and assign the geometry
Create a THREE.MeshLineMaterial
Use THREE.MeshLine and THREE.MeshLineMaterial to create a THREE.Mesh
Are you using Windows?
I remember this not working on Windows because it wasn't implemented in ANGLE.
This occurs in Windows Chrome and Firefox, both using ANGLE (WebGL to DirectX wrapper).
The issue is still not solved by the ANGLE project. You can star the issue here to get higher priority and get a notification if it's going to be implemented:
https://code.google.com/p/angleproject/issues/detail?id=119
I use TubeGeometry to create a Thick line between two points:
See Green lines in Helix
// line material
var lineMaterial = new THREE.LineBasicMaterial({ color: 0x00ff00 });
let startVector = new THREE.Vector3(
RADI * Math.cos(t),
RADI * Math.sin(t),
3 * t
);
let endVector = new THREE.Vector3(
RADI * Math.cos(t + 10),
RADI * Math.sin(t + 10),
3 * t
);
let linePoints = [];
linePoints.push(startVector, endVector);
// Create Tube Geometry
var tubeGeometry = new THREE.TubeGeometry(
new THREE.CatmullRomCurve3(linePoints),
512,// path segments
0.5,// THICKNESS
8, //Roundness of Tube
false //closed
);
let line = new THREE.Line(tubeGeometry, lineMaterial);
scene.add(line);
This is no longer an issue just in ANGLE it's an issue on all platforms. Browsers needed to switching to the OpenGL 4+ core profile to support WebGL2 and the OpenGL 4+ core profile does not support line widths greater than 1. From the OpenGL 4.0+ spec, section E.2.1
E.2.1 Deprecated But Still Supported Features
The following features are deprecated, but still present in the core profile. They may be removed from a future version of OpenGL, and are removed in a forward compatible context implementing the core profile.
Wide lines - LineWidth values greater than 1.0 will generate an INVALID_VALUE error.
To draw thicker lines you need generate geometry. For three.js there is this library (pointed out by Wilt as well)
https://github.com/spite/THREE.MeshLine
You can use CanvasRenderer instead of Webglrenderer. Check out the ifficial documentation here where each shape has a border of linewidth = 10;
You can achieve the same effect using extrude-polyline to generate a simplicial complex for the thickened (poly)line and three-simplicial-complex to convert this to a three.js Mesh:
const THREE = require('three');
const extrudePolyline = require('extrude-polyline');
const Complex = require('three-simplicial-complex')(THREE);
function thickPolyline(points, lineWidth) {
const simplicialComplex = extrudePolyline({
// Adjust to taste!
thickness: lineWidth,
cap: 'square', // or 'butt'
join: 'bevel', // or 'miter',
miterLimit: 10,
}).build(points);
// Add a z-coordinate.
for (const position of simplicialComplex.positions) {
position[2] = 0;
}
return Complex(simplicialComplex);
}
const vertices = [[0, 0], [10, 0], [10, 10], [20, 10], [30, 00]];
const geometry = thickPolyline(vertices, 10);
const material = new THREE.MeshBasicMaterial({
color: 0x009900,
side: THREE.DoubleSide
});
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
If you want to texture map the polyline, things get a little more complicated.
Thanks to Wilt's answer for pointing me in the right direction with THREE.MeshLine.
It can be slightly trickier than they make it out to be, however... So here's my solution following their docs and their demo code very carefully... (assuming you've already included Three and MeshLine):
renderer = new THREE.WebGLRenderer({ canvas });
//...
function createCircle(resolution) {
let circleGeometry = new THREE.Geometry();
for (let rotation = 0; rotation <= Math.PI * 2.0; rotation += Math.PI * 0.1) {
circleGeometry.vertices.push(
new THREE.Vector3(Math.cos(rotation), Math.sin(rotation), 0));
}
let circleLine = new MeshLine();
circleLine.setGeometry(circleGeometry);
//Bonus: parabolic width! (See Z rotation below.)
//circleLine.setGeometry(circleGeometry, function(point) {
//return Math.pow(4 * point * (1 - point), 1);
//});
//Note: resolution is *required*!
return new THREE.Mesh(circleLine.geometry,
new MeshLineMaterial({
color: 'blue',
resolution,
sizeAttenuation: 0,
lineWidth: 5.0,
side: THREE.DoubleSide
}));
}
let circle = createCircle(new THREE.Vector2(canvas.width, canvas.height));
circle.rotation.x = Math.PI * 0.5;
circle.position.y = 20.0;
scene.add(circle);
//In update, to rotate the circle (e.g. if using parabola above):
world.circle.rotation.z += 0.05;
With size attenuation off and using THREE.DoubleSide, like I did above, the circle will look like a nice, consistent circle no matter where you're looking at it from (not "true 3D").
For just a line, you can obviously easily adapt.
Why not set the opacity to something like 0.1?
NOTE: This only works if you are giving borders to something, if there's nothing behind it the it won't work.

Categories