gamehw2_test
by omgazero
HTML
<div id="info">
hw2
<br><button id="play" style="width:20%">Play</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/96/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
CSS
#info {
position: absolute;
top: 0px;
width: 100%;
padding: 10px;
text-align: center;
color: #ff0000;
}
body {
overflow: hidden;
}
JavaScript
var frame, scene, light, camera, renderer, controls;
var balls = [], planes = [], blocks = [], normals = [];
class Point2{
constructor(x, y){
this.x = x;
this.y = y;
}
}
class Box2{
constructor(max, min){
this.max = max;
this.min = min;
}
}
class Ball{
constructor(mesh, rad , color){
this.pos = new THREE.Vector3();
this.vel = new THREE.Vector3();
this.force = new THREE.Vector3();
this.m = 1;
this.mesh = mesh;
this.radius = rad;
this.light = new THREE.PointLight ( color, 1, 50 );
scene.add( this.light );
scene.add( this.mesh );
this.mesh.material.color.copy( color.clone() );
}
update(dt){
this.vel.add(this.force.clone().multiplyScalar(dt));
this.pos.add(this.vel.clone().multiplyScalar(dt));
this.collidingPlanes(planes);
this.collidingBlocks(blocks);
this.mesh.position.copy(this.pos);
this.light.position.copy(this.pos);
this.light.position.y += 20;
}
collidingPlanes(planes){
const EPS = 1e-3;
const CR = 0.96;
for(let i = 0 ; i < planes.length; i++){
let plane = planes[i];
let point = this.pos.clone().sub(plane.ptOnPl);
if( point.dot(plane.normal) < EPS + this.radius ){
this.pos.copy( plane.ptOnPl.clone().add( point.projectOnPlane( plane.normal ) ) );
this.pos.add( plane.normal.clone().multiplyScalar( this.radius ) );
this.vel.sub( plane.normal.clone().multiplyScalar( (1+CR ) * this.vel.dot( plane.normal )) );
}
}
}
collidingBalls(ball2) { //球之間的碰撞
//兩球距離
let dis = ball2.pos.clone().distanceTo(this.pos.clone());
if (dis <= this.radius * 2) {
let v1v2 = this.vel.clone().sub(ball2.vel.clone());
let v2v1 = ball2.vel.clone().sub(this.vel.clone());
let x1x2 = this.pos.clone().sub(ball2.pos.clone());
let x2x1 = ball2.pos.clone().sub(this.pos.clone());
//碰撞後的速度
let vn = this.vel.clone().sub(x1x2.clone().multiplyScalar((2 * ball2.m) / (this.m + ball2.m) * v1v2.clone().dot(x1x2) / (x1x2.length() * x1x2.length())));
let vn2...