Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                
<script async src="https://unpkg.com/es-module-shims@1.6.3/dist/es-module-shims.js"></script>

<script type="importmap">
    {
        "imports": {
            "three": "https://cdn.jsdelivr.net/npm/three@0.156.1/build/three.module.js",
            "addons/": "https://cdn.jsdelivr.net/npm/three@0.156.1/examples/jsm/"
        }
    }

</script>

<div class="container" id="container"></div>
  <div class="buttonContainerr" id="buttonContainerr">
    <div class="buttonContainer" id="inputContainer">
      <p>Tube Mass:</p>
      <input type="range" id="tubeMassInput" min="0.1" max="40" value="0.88" step="0.01" class="slider">
    </div>
  </div>
              
            
!

CSS

              
                html, body{
    width: 100vw;
    height: 100vh;
    padding: 0;
    margin: 0;
    background-color: black;
    margin: 0;
    padding: 0;
    font-family:'mono45-headline';
}

.container{
    position: fixed;
    top: 0;
    left: 0;
    height: 100vh;
    width: 100vw;
    padding: 0;
    margin: 0;
    z-index: 0;
  background: linear-gradient(0deg, rgba(74,74,74,0.2) 0%, rgba(173,173,173,0.5) 53%, rgba(240,240,240,0.7) 100%);
}

.buttonContainerr{
  position: fixed;
  top: 0;
  left: 0;
  display: flex;
  flex-direction: column;
  margin:  10px 10px;
}

.buttonContainer{

  display: flex;
}

.buttonn{
  padding: 5px 10px;
  margin:  10px 10px;
  border: solid 1px white;
  cursor: pointer;
}
              
            
!

JS

              
                import * as THREE from 'three';

import { OrbitControls } from 'addons/controls/OrbitControls.js'

const container = document.querySelector('.container');
const sizes = {
  width:container.offsetWidth,
  height:container.offsetHeight
}

const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(50, sizes.width / sizes.height, 0.1, 1500)
const renderer = new THREE.WebGLRenderer( { antialias: true, gammaOutput: true, alpha: true } );
const orbit = new OrbitControls(camera, renderer.domElement)
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
const clock = new THREE.Clock();
let points, rope, args, ropeGeometry, positions, lineGeometry

const tubeMassInput = document.querySelector('#tubeMassInput')

const start = new THREE.Vector3(-5, 0, 0);
const end = new THREE.Vector3(5, 0, 0);
const resolution = 0.5;
const mass = 0.88;
const damping = 0.95;
const gravity = new THREE.Vector3(0, -9.81, 0);
const solverIterations = 10;

    class RopePoint {
      static integrate(point, gravity, dt, previousFrameDt) {
        point.velocity = new THREE.Vector3().subVectors(point.pos, point.oldPos);
        point.oldPos.copy(point.pos);

        let timeCorrection = previousFrameDt != 0.0 ? dt / previousFrameDt : 0.0;
        let accel = new THREE.Vector3().copy(gravity).multiplyScalar(point.mass);

        const velCoef = timeCorrection * point.damping;
        const accelCoef = Math.pow(dt, 2);

        point.pos.addScaledVector(point.velocity, velCoef).addScaledVector(accel, accelCoef);
      }

      static constrain(point) {
        if (point.next) {
          const delta = new THREE.Vector3().subVectors(point.next.pos, point.pos);
          const len = delta.length();
          const diff = len - point.distanceToNextPoint;
          const normal = delta.normalize();

          if (!point.isFixed) point.pos.addScaledVector(normal, diff * 0.25);
          if (!point.next.isFixed) point.next.pos.addScaledVector(normal, -diff * 0.25);
        }

        if (point.prev) {
          const delta = new THREE.Vector3().subVectors(point.prev.pos, point.pos);
          const len = delta.length();
          const diff = len - point.distanceToNextPoint;
          const normal = delta.normalize();

          if (!point.isFixed) point.pos.addScaledVector(normal, diff * 0.25);
          if (!point.prev.isFixed) point.prev.pos.addScaledVector(normal, -diff * 0.25);
        }
      }
      

  setMass(newMass) {
    this.mass = newMass;
  }

  constructor(initialPos, distanceToNextPoint) {
    this.pos = new THREE.Vector3().copy(initialPos);
    this.oldPos = new THREE.Vector3().copy(initialPos);
    this.velocity = new THREE.Vector3();
    this.distanceToNextPoint = distanceToNextPoint;
    this.isFixed = false;
    this.mass = 1.0;
    this.damping = 1.0;
    this.prev = null;
    this.next = null;
  }
    }

    class Rope {
      static generate(start, end, resolution, mass, damping) {
        const delta = new THREE.Vector3().subVectors(end, start);
        const len = delta.length();
        let points = [];
        const pointsLen = Math.floor(len / resolution);

        for (let i = 0; i < pointsLen; i++) {
          const percentage = i / (pointsLen - 1);
          const pos = new THREE.Vector3().lerpVectors(start, end, percentage);
          let point = new RopePoint(pos, resolution);
          point.mass = mass;
          point.damping = damping;
          points.push(point);
        }

        for (let i = 0; i < pointsLen; i++) {
          points[i].prev = i > 0 ? points[i - 1] : null;
          points[i].next = i < pointsLen - 1 ? points[i + 1] : null;
        }

        points[0].isFixed = points[points.length - 1].isFixed = true;
        return points;
      }

  setMassForAllPoints(newMass) {
    this._points.forEach(point => {
      point.setMass(newMass);
    });
  }

  // Or, if you want to set mass for a specific point by index:
  setMassForPoint(index, newMass) {
    if (index >= 0 && index < this._points.length) {
      this._points[index].setMass(newMass);
    }
  }

  constructor(points, solverIterations) {
    this._points = points;
    this._prevDelta = 0;
    this._solverIterations = solverIterations;
  }

  update(gravity, dt) {
    for (let i = 1; i < this._points.length - 1; i++) {
      RopePoint.integrate(this._points[i], gravity, dt, this._prevDelta);
    }

    for (let iteration = 0; iteration < this._solverIterations; iteration++) {
      for (let i = 1; i < this._points.length - 1; i++) {
        RopePoint.constrain(this._points[i]);
      }
    }

    this._prevDelta = dt;
  }

  getPoint(index) {
    return this._points[index];
  }
    }

init()

function init(){

  camera.position.set(0,10,10)

  let ambLight = new THREE.AmbientLight(0xffffff, 4.4)
  scene.add(ambLight)

  let light = new THREE.DirectionalLight( 0x999999, 3.6 );
  scene.add(light)
  
  renderer.setSize(sizes.width, sizes.height)
  renderer.setClearColor( 0xfb97e6, 0.0 );
  container.appendChild(renderer.domElement)

  orbit.autoRotateSpeed = 4
  orbit.enableDamping = true
  orbit.enablePan = false
  orbit.rotateSpeed = 0.6
  orbit.target.set(0,0,0)
  
  
  
  
  let flGeo = new THREE.CircleGeometry(5,46,1)
  
  let mat2 = new THREE.MeshStandardMaterial({
    color:0x666666, 
    roughness:0.4,
    // side: THREE.DoubleSide,
    transparent:true,
    opacity:0.7
  })

  
  const floor = new THREE.Mesh(flGeo, mat2)
  floor.rotation.x = -90 * Math.PI / 180
  floor.position.y = -1.5
  // scene.add(floor)
  
  


    points = Rope.generate(start, end, resolution, mass, damping);
    rope = new Rope(points, solverIterations);

    lineGeometry = new THREE.BufferGeometry();
    positions = new Float32Array(points.length * 3);
    lineGeometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
    const lineMaterial = new THREE.LineBasicMaterial({ color: 0xff0000 });
    const line = new THREE.Line(lineGeometry, lineMaterial);
    scene.add(line);

  
  window.addEventListener('resize', onWindowResize, false)
  // window.addEventListener('mousemove', mouseMove, false)
  tubeMassInput.addEventListener('input', (e)=>{
    console.log(e.target.value)
    rope.setMassForAllPoints(e.target.value);
  })
                          
  animate()
}

function mouseMove() {
  mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

  raycaster.setFromCamera(mouse, camera);

  const intersection = raycaster.ray.intersectPlane(new THREE.Plane(new THREE.Vector3(0, 0, 1)), new THREE.Vector3());
  
  if (intersection) {
    let point = rope.getPoint(0);
    point.pos.copy(intersection);
  }
};

function onWindowResize() {
    sizes.width = container.offsetWidth;
    sizes.height = container.offsetHeight;
    camera.aspect = sizes.width / sizes.height;
    camera.updateProjectionMatrix()
    renderer.setSize(sizes.width, sizes.height)
    render()
}

function animate(t) {
    window.requestAnimationFrame(animate)
  
      const dt = 1 / 60;
      rope.update(gravity, dt);

      for (let i = 0; i < points.length; i++) {
        positions[i * 3] = points[i].pos.x;
        positions[i * 3 + 1] = points[i].pos.y;
        positions[i * 3 + 2] = points[i].pos.z;
      }

      lineGeometry.attributes.position.needsUpdate = true;
  
    render(t)
}

function render(t) {
  orbit.update()
  renderer.render(scene, camera)
} 

              
            
!
999px

Console