HomeWork7
by omgazero
HTML
<div id="info">
homework7
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/84/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stats.js/r16/Stats.min.js"></script>
CSS
#info {
position: absolute;
top: 0px;
width: 100%;
padding: 10px;
text-align: center;
color: #ff0000;
}
JavaScript
var frame = [],
scene, camera, renderer, light, controls;
var stats, raycaster, num = 0,
Height = 200,
Width = 200;
var pickables = [];
var mouse = new THREE.Vector2();
class Punk {
constructor(r, m) {
this.r = r; //半徑
this.m = m; //質量
this.v = new THREE.Vector3(0, 10, 0); //速度
this.ball = new THREE.Mesh(new THREE.CylinderGeometry(r, r, 10, 20), new THREE.MeshNormalMaterial());
this.ball.rotation.x = Math.PI / 2;
this.punk = new THREE.Object3D();
this.punk.add(this.ball);
}
wallcollision() { //球與牆壁的碰撞
//摩擦力
this.v = this.v.clone().normalize().multiplyScalar(0.995 * this.v.length()) ;
//上下方牆壁
if (this.punk.position.y >= Height / 2 - this.r && this.v.y > 0) {
this.v.y = -0.9 * this.v.y;
} else if (this.punk.position.y <= -Height / 2 + this.r && this.v.y < 0) {
this.v.y = -0.9 * this.v.y;
}
//左右方牆壁
if (this.punk.position.x >= Width / 2 - this.r && this.v.x > 0) {
this.v.x = -0.9 * this.v.x;
} else if (this.punk.position.x <= -Width / 2 + this.r && this.v.x < 0) {
this.v.x = -0.9 * this.v.x;
}
}
punkcollsion(punk2) { //球之間的碰撞
//兩球距離
let dis = punk2.punk.position.clone().distanceTo(this.punk.position.clone());
if (dis <= this.r * 2) {
let v1v2 = this.v.clone().sub(punk2.v.clone());
let v2v1 = punk2.v.clone().sub(this.v.clone());
let x1x2 = this.punk.position.clone().sub(punk2.punk.position.clone());
let x2x1 = punk2.punk.position.clone().sub(this.punk.position.clone());
//碰撞後的速度
let vn = this.v.clone().sub(x1x2.clone().multiplyScalar((2 * punk2.m) / (this.m + punk2.m) * v1v2.clone().dot(x1x2) / (x1x2.length() * x1x2.length())));
let vn2 = punk2.v.clone().sub(x2x1.clone().multiplyScalar((2 * this.m) / (this.m + punk2.m) * v2v1.clone().dot(x2x1) / (x2x1.length() * x2x1.length())));
this.v = vn;
punk2.v = vn2;
//位置修正
let delta = punk2.punk.position.clone().sub(...