Spaces:
Running
Running
| // ctrl_camera_pr_env.js | |
| // ============================================================================ | |
| // FREE CAMERA (sans orbite) + COLLISION "FIRST-PERSON" style PlayCanvas | |
| // - Souris : rotation libre (FPS) | |
| // - ZQSD / Flèches : déplacement local (avant/arrière & strafe) | |
| // - Molette / Pinch : dolly (avance/recul le long du regard) | |
| // - Collisions : Capsule (caméra) vs AABBs dérivés des meshes sous focusEntity | |
| // - Step offset (monte les marches) + Snap down (redescend sur le sol) | |
| // - Pas d'auto-spawn : la position JSON est respectée strictement | |
| // ============================================================================ | |
| var FreeCamera = pc.createScript('orbitCamera'); // garder le nom public pour compat viewer | |
| // ======================== Attributs =========================== | |
| // Look | |
| FreeCamera.attributes.add('inertiaFactor', { type: 'number', default: 0.10, title: 'Inertia (rotation)' }); | |
| FreeCamera.attributes.add('pitchAngleMin', { type: 'number', default: -89, title: 'Pitch Min (deg)' }); | |
| FreeCamera.attributes.add('pitchAngleMax', { type: 'number', default: 89, title: 'Pitch Max (deg)' }); | |
| // Sol mini (filet de sécurité) | |
| FreeCamera.attributes.add('minY', { type: 'number', default: -10, title: 'Minimum camera Y' }); | |
| // Vitesse (m/s) | |
| FreeCamera.attributes.add('moveSpeed', { type: 'number', default: 2.2, title: 'Move Speed' }); | |
| FreeCamera.attributes.add('strafeSpeed', { type: 'number', default: 2.2, title: 'Strafe Speed' }); | |
| FreeCamera.attributes.add('dollySpeed', { type: 'number', default: 2.2, title: 'Mouse/Pinch Dolly Speed' }); | |
| // Capsule caméra | |
| FreeCamera.attributes.add('capsuleRadius', { type: 'number', default: 0.30, title: 'Capsule Radius (m)' }); | |
| FreeCamera.attributes.add('capsuleHeight', { type: 'number', default: 1.60, title: 'Capsule Height (m) — yeux à ~0.9m au-dessus du centre' }); | |
| FreeCamera.attributes.add('collisionEps', { type: 'number', default: 0.0005, title: 'Collision Epsilon' }); | |
| // Mouvement "swept" | |
| FreeCamera.attributes.add('maxStepDistance', { type: 'number', default: 0.20, title: 'Max step distance (swept move)' }); | |
| FreeCamera.attributes.add('maxResolveIters', { type: 'number', default: 6, title: 'Max resolve iterations per step' }); | |
| // Escaliers | |
| FreeCamera.attributes.add('stepHeight', { type: 'number', default: 0.35, title: 'Max step-up height (m)' }); | |
| FreeCamera.attributes.add('stepAhead', { type: 'number', default: 0.20, title: 'Probe distance ahead for step (m)' }); | |
| FreeCamera.attributes.add('snapDownMax', { type: 'number', default: 0.60, title: 'Max snap-down (m)' }); | |
| FreeCamera.attributes.add('enableGroundSnap', { type: 'boolean', default: true, title: 'Enable ground snap' }); | |
| // AABBs (construction "indoor-safe") | |
| FreeCamera.attributes.add('inflateBias', { type: 'number', default: 0.0, title: 'Extra inflate AABB (m)' }); | |
| FreeCamera.attributes.add('mergeGap', { type: 'number', default: 0.0, title: 'Merge AABBs gap (0: chevauchement réel seulement)' }); | |
| FreeCamera.attributes.add('globalCullFrac',{ type: 'number', default: 0.08, title: 'Cull near-global AABBs (0.08=8%)' }); | |
| // BBox globale optionnelle (filet) | |
| FreeCamera.attributes.add('Xmin', { type: 'number', default: -Infinity, title: 'BBox Xmin' }); | |
| FreeCamera.attributes.add('Xmax', { type: 'number', default: Infinity, title: 'BBox Xmax' }); | |
| FreeCamera.attributes.add('Ymin', { type: 'number', default: -Infinity, title: 'BBox Ymin' }); | |
| FreeCamera.attributes.add('Ymax', { type: 'number', default: Infinity, title: 'BBox Ymax' }); | |
| FreeCamera.attributes.add('Zmin', { type: 'number', default: -Infinity, title: 'BBox Zmin' }); | |
| FreeCamera.attributes.add('Zmax', { type: 'number', default: Infinity, title: 'BBox Zmax' }); | |
| // Compat (pour le viewer) | |
| FreeCamera.attributes.add('focusEntity', { type: 'entity', title: 'Collision Root (ENV GLB)' }); | |
| FreeCamera.attributes.add('frameOnStart', { type: 'boolean', default: false, title: 'Compat: Frame on Start (unused)' }); | |
| FreeCamera.attributes.add('yawAngleMin', { type: 'number', default: -360, title: 'Compat: Yaw Min (unused)' }); | |
| FreeCamera.attributes.add('yawAngleMax', { type: 'number', default: 360, title: 'Compat: Yaw Max (unused)' }); | |
| FreeCamera.attributes.add('distanceMin', { type: 'number', default: 0.1, title: 'Compat: Distance Min (unused)' }); | |
| // ======================== Helpers =========================== | |
| function vAdd(a,b){ return new pc.Vec3(a.x+b.x,a.y+b.y,a.z+b.z); } | |
| function vSub(a,b){ return new pc.Vec3(a.x-b.x,a.y-b.y,a.z-b.z); } | |
| function vScale(v,s){ return new pc.Vec3(v.x*s,v.y*s,v.z*s); } | |
| function vLen(v){ return Math.sqrt(v.x*v.x+v.y*v.y+v.z*v.z); } | |
| function vDot(a,b){ return a.x*b.x+a.y*b.y+a.z*b.z; } | |
| function vNorm(v){ var l=vLen(v)||1; return new pc.Vec3(v.x/l,v.y/l,v.z/l); } | |
| function clamp(v,a,b){ return Math.max(a, Math.min(b,v)); } | |
| // Capsule util: point bas et point haut (segment) centrés sur p | |
| function capsuleSegment(p, height, radius) { | |
| // Capsule vertical : segment longueur (height - 2*radius), clampée >= 0 | |
| var seg = Math.max(0, height - 2*radius); | |
| var half = seg * 0.5; | |
| return { | |
| a: new pc.Vec3(p.x, p.y - half, p.z), | |
| b: new pc.Vec3(p.x, p.y + half, p.z), | |
| len: seg | |
| }; | |
| } | |
| // Distance point-segment au cube AABB (renvoie penetration > 0 si intersecte) | |
| function capsuleVsAabbPenetration(center, height, radius, aabb, outPush) { | |
| // approx : on projette les extrémités de la capsule et on prend le pire cas | |
| var seg = capsuleSegment(center, height, radius); | |
| // Trouver le point du segment le plus proche de l'AABB (on fait binaire en échantillonnant) | |
| // Optimisation simple: on teste 3 points: a, b et milieu | |
| var pts = [seg.a, seg.b, new pc.Vec3((seg.a.x+seg.b.x)/2,(seg.a.y+seg.b.y)/2,(seg.a.z+seg.b.z)/2)]; | |
| var amin = aabb.getMin(); | |
| var amax = aabb.getMax(); | |
| var eps = 1e-9; | |
| var bestPen = 0; | |
| var bestPush = null; | |
| for (var i=0;i<pts.length;i++){ | |
| var p = pts[i]; | |
| var cx = clamp(p.x, amin.x, amax.x); | |
| var cy = clamp(p.y, amin.y, amax.y); | |
| var cz = clamp(p.z, amin.z, amax.z); | |
| var dx = p.x - cx, dy = p.y - cy, dz = p.z - cz; | |
| var d2 = dx*dx + dy*dy + dz*dz; | |
| var d = Math.sqrt(Math.max(d2, eps)); | |
| var pen = radius - d; | |
| if (pen > bestPen) { | |
| if (d > 1e-6) { | |
| bestPush = new pc.Vec3(dx/d * pen, dy/d * pen, dz/d * pen); | |
| } else { | |
| // si coïncident, pousse le long de l'axe le plus proche | |
| var ex = Math.min(Math.abs(p.x - amin.x), Math.abs(amax.x - p.x)); | |
| var ey = Math.min(Math.abs(p.y - amin.y), Math.abs(amax.y - p.y)); | |
| var ez = Math.min(Math.abs(p.z - amin.z), Math.abs(amax.z - p.z)); | |
| if (ex <= ey && ex <= ez) bestPush = new pc.Vec3((Math.abs(p.x - amin.x) < Math.abs(amax.x - p.x) ? -1:1)*pen,0,0); | |
| else if (ey <= ex && ey <= ez) bestPush = new pc.Vec3(0,(Math.abs(p.y - amin.y) < Math.abs(amax.y - p.y) ? -1:1)*pen,0); | |
| else bestPush = new pc.Vec3(0,0,(Math.abs(p.z - amin.z) < Math.abs(amax.z - p.z) ? -1:1)*pen); | |
| } | |
| bestPen = pen; | |
| } | |
| } | |
| if (bestPen > 0 && outPush) outPush.copy(bestPush); | |
| return bestPen; | |
| } | |
| // ======================== Getters pitch/yaw =========================== | |
| Object.defineProperty(FreeCamera.prototype, 'pitch', { | |
| get: function () { return this._targetPitch; }, | |
| set: function (v) { this._targetPitch = pc.math.clamp(v, this.pitchAngleMin, this.pitchAngleMax); } | |
| }); | |
| Object.defineProperty(FreeCamera.prototype, 'yaw', { | |
| get: function () { return this._targetYaw; }, | |
| set: function (v) { this._targetYaw = v; } | |
| }); | |
| // ======================== Init =========================== | |
| FreeCamera.prototype.initialize = function () { | |
| // angles init | |
| var q = this.entity.getRotation(); | |
| var f = new pc.Vec3(); q.transformVector(pc.Vec3.FORWARD, f); | |
| this._yaw = Math.atan2(f.x, f.z) * pc.math.RAD_TO_DEG; | |
| var yawQuat = new pc.Quat().setFromEulerAngles(0, -this._yaw, 0); | |
| var noYawQ = new pc.Quat().mul2(yawQuat, q); | |
| var fNoYaw = new pc.Vec3(); noYawQ.transformVector(pc.Vec3.FORWARD, fNoYaw); | |
| this._pitch = pc.math.clamp(Math.atan2(-fNoYaw.y, -fNoYaw.z) * pc.math.RAD_TO_DEG, this.pitchAngleMin, this.pitchAngleMax); | |
| this._targetYaw = this._yaw; | |
| this._targetPitch = this._pitch; | |
| this.entity.setLocalEulerAngles(this._pitch, this._yaw, 0); | |
| // état partagé | |
| this.app.systems.script.app.freeCamState = this.app.systems.script.app.freeCamState || {}; | |
| this.state = this.app.systems.script.app.freeCamState; | |
| // Construire les colliders depuis focusEntity (GLB environnement) | |
| this._buildAabbsFromFocus(); | |
| // Clamp très léger au spawn (sans déplacement “loin”) | |
| var p0 = this.entity.getPosition().clone(); | |
| var p1 = this._resolveCapsuleCollisions(p0, this.maxResolveIters); | |
| if (vLen(vSub(p1,p0)) > this.capsuleRadius * 0.25) { | |
| // limite la correction pour ne PAS expulser hors bâtiment | |
| var dir = vSub(p1,p0); var L = vLen(dir)||1; | |
| p1 = vAdd(p0, vScale(dir, (this.capsuleRadius*0.25)/L)); | |
| } | |
| this._clampBBoxMinY(p1); | |
| this.entity.setPosition(p1); | |
| // Aspect ratio | |
| var self = this; | |
| this._onResize = function(){ self._checkAspectRatio(); }; | |
| window.addEventListener('resize', this._onResize, false); | |
| this._checkAspectRatio(); | |
| }; | |
| FreeCamera.prototype.update = function (dt) { | |
| // rotation lissée | |
| var t = this.inertiaFactor === 0 ? 1 : Math.min(dt / this.inertiaFactor, 1); | |
| this._yaw = pc.math.lerp(this._yaw, this._targetYaw, t); | |
| this._pitch = pc.math.lerp(this._pitch, this._targetPitch, t); | |
| this.entity.setLocalEulerAngles(this._pitch, this._yaw, 0); | |
| // maintien propre (au cas où) | |
| var pos = this.entity.getPosition().clone(); | |
| pos = this._resolveCapsuleCollisions(pos, this.maxResolveIters); | |
| this._clampBBoxMinY(pos); | |
| this.entity.setPosition(pos); | |
| }; | |
| FreeCamera.prototype._checkAspectRatio = function () { | |
| var gd = this.app.graphicsDevice; | |
| if (!gd) return; | |
| this.entity.camera.horizontalFov = (gd.height > gd.width); | |
| }; | |
| // ======================== Build colliders =========================== | |
| FreeCamera.prototype._buildAabbsFromFocus = function () { | |
| this._colliders = []; | |
| this._worldAabb = null; | |
| this._useCollision = false; | |
| var root = this.focusEntity; | |
| if (!root) return; | |
| // 1) collecter | |
| var boxes = []; | |
| var stack = [root]; | |
| while (stack.length) { | |
| var e = stack.pop(); | |
| var rc = e.render; | |
| if (rc && rc.meshInstances && rc.meshInstances.length) { | |
| for (var i=0;i<rc.meshInstances.length;i++){ | |
| var bb = rc.meshInstances[i].aabb; | |
| boxes.push(new pc.BoundingBox(bb.center.clone(), bb.halfExtents.clone())); | |
| } | |
| } | |
| var ch = e.children; | |
| if (ch && ch.length) for (var j=0;j<ch.length;j++) stack.push(ch[j]); | |
| } | |
| if (boxes.length === 0) return; | |
| // 2) monde | |
| var world = boxes[0].clone(); | |
| for (var k=1;k<boxes.length;k++) world.add(boxes[k]); | |
| // 3) filtrer quasi-global | |
| var frac = pc.math.clamp(this.globalCullFrac, 0, 0.49); | |
| var wh = world.halfExtents; | |
| var filtered = []; | |
| for (var m=0;m<boxes.length;m++){ | |
| var h = boxes[m].halfExtents; | |
| var nearGlobal = (h.x >= wh.x*(1-frac)) && (h.y >= wh.y*(1-frac)) && (h.z >= wh.z*(1-frac)); | |
| if (!nearGlobal) filtered.push(boxes[m]); | |
| } | |
| // 4) merge strict | |
| var merged = this._mergeAabbs(filtered, Math.max(0, this.mergeGap||0)); | |
| // 5) petit gonflage | |
| var inflate = Math.max(0, this.inflateBias||0); | |
| for (var n=0;n<merged.length;n++){ | |
| merged[n].halfExtents.add(new pc.Vec3(inflate, inflate, inflate)); | |
| } | |
| // 6) enregistrer | |
| if (merged.length>0) { | |
| for (var t=0;t<merged.length;t++) this._colliders.push({ aabb: merged[t] }); | |
| this._worldAabb = world; | |
| this._useCollision = true; | |
| } | |
| console.log('[FREE-CAM] colliders:', boxes.length); | |
| }; | |
| FreeCamera.prototype._mergeAabbs = function (boxes, gap) { | |
| if (!boxes || boxes.length<=1) return boxes.slice(); | |
| var out = boxes.slice(); | |
| var tol = Math.max(0, gap||0); | |
| var changed = true; | |
| function overlap(a,b,t){ | |
| var amin=a.getMin(), amax=a.getMax(); | |
| var bmin=b.getMin(), bmax=b.getMax(); | |
| return !( | |
| amax.x < bmin.x - t || amin.x > bmax.x + t || | |
| amax.y < bmin.y - t || amin.y > bmax.y + t || | |
| amax.z < bmin.z - t || amin.z > bmax.z + t | |
| ); | |
| } | |
| while (changed){ | |
| changed=false; | |
| var next=[], used=new Array(out.length).fill(false); | |
| for (var i=0;i<out.length;i++){ | |
| if (used[i]) continue; | |
| var acc = out[i]; | |
| for (var j=i+1;j<out.length;j++){ | |
| if (used[j]) continue; | |
| if (overlap(acc,out[j],tol)){ | |
| var aMin=acc.getMin(), aMax=acc.getMax(); | |
| var bMin=out[j].getMin(), bMax=out[j].getMax(); | |
| var nMin=new pc.Vec3(Math.min(aMin.x,bMin.x), Math.min(aMin.y,bMin.y), Math.min(aMin.z,bMin.z)); | |
| var nMax=new pc.Vec3(Math.max(aMax.x,bMax.x), Math.max(aMax.y,bMax.y), Math.max(aMax.z,bMax.z)); | |
| var c=nMin.clone().add(nMax).mulScalar(0.5); | |
| var h=new pc.Vec3(Math.abs(nMax.x-c.x), Math.abs(nMax.y-c.y), Math.abs(nMax.z-c.z)); | |
| acc = new pc.BoundingBox(c,h); | |
| used[j]=true; changed=true; | |
| } | |
| } | |
| used[i]=true; next.push(acc); | |
| } | |
| out=next; | |
| } | |
| return out; | |
| }; | |
| // ======================== BBox globale + minY =========================== | |
| FreeCamera.prototype._bboxEnabled = function () { | |
| return (this.Xmin < this.Xmax) && (this.Ymin < this.Ymax) && (this.Zmin < this.Zmax); | |
| }; | |
| FreeCamera.prototype._clampBBoxMinY = function (p) { | |
| if (p.y < this.minY) p.y = this.minY; | |
| if (!this._bboxEnabled()) return; | |
| p.x = clamp(p.x, this.Xmin, this.Xmax); | |
| p.y = clamp(p.y, Math.max(this.Ymin, this.minY), this.Ymax); | |
| p.z = clamp(p.z, this.Zmin, this.Zmax); | |
| }; | |
| // ======================== Capsule vs AABBs : resolve =========================== | |
| FreeCamera.prototype._resolveCapsuleCollisions = function (pos, maxIters) { | |
| if (!this._useCollision) return pos.clone(); | |
| var p = pos.clone(); | |
| var R = Math.max(0, this.capsuleRadius); | |
| var H = Math.max(2*R, this.capsuleHeight); // clamp min | |
| var eps = Math.max(1e-7, this.collisionEps); | |
| if (!this._colliders || this._colliders.length===0) return p; | |
| var iters = Math.max(1, maxIters||1); | |
| for (var iter=0; iter<iters; iter++){ | |
| var moved = false; | |
| for (var i=0;i<this._colliders.length;i++){ | |
| var aabb = this._colliders[i].aabb; | |
| var push = new pc.Vec3(); | |
| var pen = capsuleVsAabbPenetration(p, H, R, aabb, push); | |
| if (pen > eps) { | |
| p.add(push); | |
| moved = true; | |
| } | |
| } | |
| if (!moved) break; | |
| } | |
| return p; | |
| }; | |
| // ======================== Mvt principal : swept + step + snap =========================== | |
| FreeCamera.prototype._moveSwept = function (from, delta) { | |
| if (!this._useCollision) return vAdd(from, delta); | |
| var maxStep = Math.max(0.01, this.maxStepDistance||0.2); | |
| var dist = vLen(delta); | |
| if (dist <= maxStep) return this._moveStep(from, delta); | |
| var steps = Math.ceil(dist / maxStep); | |
| var step = vScale(delta, 1/steps); | |
| var cur = from.clone(); | |
| for (var i=0;i<steps;i++) cur = this._moveStep(cur, step); | |
| return cur; | |
| }; | |
| FreeCamera.prototype._moveStep = function (from, delta) { | |
| // A) tentative directe | |
| var target = vAdd(from, delta); | |
| var after = this._resolveCapsuleCollisions(target, this.maxResolveIters); | |
| var collided = (vLen(vSub(after, target)) > 0); | |
| if (!collided) { | |
| if (this.enableGroundSnap) after = this._snapDown(after); | |
| return after; | |
| } | |
| // B) slide (supprimer la composante contre la "normale" approx) | |
| var n = this._estimateNormal(after); | |
| if (n) { | |
| var desire = delta.clone(); | |
| // projeter le déplacement sur le plan perpendiculaire à n | |
| var slide = vSub(desire, vScale(n, vDot(desire, n))); | |
| var slideTarget = vAdd(from, slide); | |
| var slideAfter = this._resolveCapsuleCollisions(slideTarget, this.maxResolveIters); | |
| // C) step-up si slide insuffisant | |
| if (vLen(vSub(slideAfter, slideTarget)) > 0) { | |
| var stepped = this._tryStepUp(from, desire); | |
| if (stepped) { | |
| if (this.enableGroundSnap) stepped = this._snapDown(stepped); | |
| return stepped; | |
| } | |
| } | |
| if (this.enableGroundSnap) slideAfter = this._snapDown(slideAfter); | |
| return slideAfter; | |
| } | |
| if (this.enableGroundSnap) after = this._snapDown(after); | |
| return after; | |
| }; | |
| // Normale approx via micro-probes | |
| FreeCamera.prototype._estimateNormal = function (p) { | |
| if (!this._colliders) return null; | |
| var probe = 0.02; | |
| var base = this._resolveCapsuleCollisions(p, this.maxResolveIters); | |
| var nx = this._resolveCapsuleCollisions(new pc.Vec3(p.x+probe,p.y,p.z), this.maxResolveIters); | |
| var px = this._resolveCapsuleCollisions(new pc.Vec3(p.x-probe,p.y,p.z), this.maxResolveIters); | |
| var ny = this._resolveCapsuleCollisions(new pc.Vec3(p.x,p.y+probe,p.z), this.maxResolveIters); | |
| var py = this._resolveCapsuleCollisions(new pc.Vec3(p.x,p.y-probe,p.z), this.maxResolveIters); | |
| var nz = this._resolveCapsuleCollisions(new pc.Vec3(p.x,p.y,p.z+probe), this.maxResolveIters); | |
| var pz = this._resolveCapsuleCollisions(new pc.Vec3(p.x,p.y,p.z-probe), this.maxResolveIters); | |
| function d(a,b){ return vLen(vSub(a,b)); } | |
| var dx = d(nx,base) - d(px,base); | |
| var dy = d(ny,base) - d(py,base); | |
| var dz = d(nz,base) - d(pz,base); | |
| var n = new pc.Vec3(dx,dy,dz); | |
| var L = vLen(n); | |
| if (L < 1e-5) return null; | |
| return vScale(n, 1/L); | |
| }; | |
| // Step-up : monter une marche (jusqu'à stepHeight) | |
| FreeCamera.prototype._tryStepUp = function (from, wishDelta) { | |
| var R = Math.max(0, this.capsuleRadius); | |
| var H = Math.max(2*R, this.capsuleHeight); | |
| var eps = Math.max(1e-4, this.collisionEps); | |
| var maxH = Math.max(0, this.stepHeight || 0.35); | |
| var ahead = Math.max(0.05, this.stepAhead || 0.20); | |
| var horiz = new pc.Vec3(wishDelta.x, 0, wishDelta.z); | |
| var hLen = vLen(horiz); | |
| if (hLen < 1e-6) return null; | |
| horiz = vScale(horiz, 1/hLen); | |
| // on avance un peu, on monte, puis on applique le delta complet | |
| var probe = vAdd(from, vScale(horiz, Math.min(hLen, ahead))); | |
| // tester plusieurs hauteurs jusqu'à maxH | |
| var trials = 3; | |
| for (var i=1;i<=trials;i++){ | |
| var up = maxH * (i/trials); | |
| var raised = new pc.Vec3(probe.x, probe.y + up, probe.z); | |
| raised = this._resolveCapsuleCollisions(raised, this.maxResolveIters); | |
| var stepped = this._resolveCapsuleCollisions(vAdd(raised, wishDelta), this.maxResolveIters); | |
| // validé si on a gagné horizontalement | |
| if (vLen(vSub(stepped, raised)) > 0.02) return stepped; | |
| } | |
| return null; | |
| }; | |
| // Snap-down : redéposer sur le sol si on flotte un peu (descente d'escalier) | |
| FreeCamera.prototype._snapDown = function (p) { | |
| var R = Math.max(0, this.capsuleRadius); | |
| var H = Math.max(2*R, this.capsuleHeight); | |
| var maxDown = Math.max(0, this.snapDownMax || 0.6); | |
| // On descend par petits incréments pour “chercher” le sol | |
| var steps = 4; | |
| var step = maxDown / steps; | |
| var cur = p.clone(); | |
| for (var i=0;i<steps;i++){ | |
| var down = new pc.Vec3(cur.x, cur.y - step, cur.z); | |
| var resolved = this._resolveCapsuleCollisions(down, this.maxResolveIters); | |
| if (vLen(vSub(resolved, down)) > 0) { | |
| // on a tapé quelque chose : remonter légèrement et arrêter | |
| return this._resolveCapsuleCollisions(new pc.Vec3(resolved.x, resolved.y + 0.01, resolved.z), this.maxResolveIters); | |
| } | |
| cur.copy(down); | |
| } | |
| return p; | |
| }; | |
| // ===================== INPUT SOURIS ===================== | |
| var FreeCameraInputMouse = pc.createScript('orbitCameraInputMouse'); | |
| FreeCameraInputMouse.attributes.add('lookSensitivity', { type: 'number', default: 0.3, title: 'Look Sensitivity' }); | |
| FreeCameraInputMouse.attributes.add('wheelSensitivity',{ type: 'number', default: 1.0, title: 'Wheel Sensitivity' }); | |
| FreeCameraInputMouse.prototype.initialize = function () { | |
| this.freeCam = this.entity.script.orbitCamera; | |
| this.last = new pc.Vec2(); | |
| this.isLooking = false; | |
| if (this.app.mouse) { | |
| this.app.mouse.on(pc.EVENT_MOUSEDOWN, this.onMouseDown, this); | |
| this.app.mouse.on(pc.EVENT_MOUSEUP, this.onMouseUp, this); | |
| this.app.mouse.on(pc.EVENT_MOUSEMOVE, this.onMouseMove, this); | |
| this.app.mouse.on(pc.EVENT_MOUSEWHEEL, this.onMouseWheel, this); | |
| this.app.mouse.disableContextMenu(); | |
| } | |
| var self = this; | |
| this._onOut = function(){ self.isLooking = false; }; | |
| window.addEventListener('mouseout', this._onOut, false); | |
| this.on('destroy', () => { | |
| if (this.app.mouse) { | |
| this.app.mouse.off(pc.EVENT_MOUSEDOWN, this.onMouseDown, this); | |
| this.app.mouse.off(pc.EVENT_MOUSEUP, this.onMouseUp, this); | |
| this.app.mouse.off(pc.EVENT_MOUSEMOVE, this.onMouseMove, this); | |
| this.app.mouse.off(pc.EVENT_MOUSEWHEEL, this.onMouseWheel, this); | |
| } | |
| window.removeEventListener('mouseout', this._onOut, false); | |
| }); | |
| }; | |
| FreeCameraInputMouse.prototype.onMouseDown = function (e) { | |
| this.isLooking = true; | |
| this.last.set(e.x, e.y); | |
| }; | |
| FreeCameraInputMouse.prototype.onMouseUp = function () { | |
| this.isLooking = false; | |
| }; | |
| FreeCameraInputMouse.prototype.onMouseMove = function (e) { | |
| if (!this.isLooking || !this.freeCam) return; | |
| var sens = this.lookSensitivity; | |
| this.freeCam.yaw = this.freeCam.yaw - e.dx * sens; | |
| this.freeCam.pitch = this.freeCam.pitch - e.dy * sens; | |
| this.last.set(e.x, e.y); | |
| }; | |
| FreeCameraInputMouse.prototype.onMouseWheel = function (e) { | |
| if (!this.freeCam) return; | |
| var cam = this.entity; | |
| var move = -e.wheelDelta * this.wheelSensitivity * this.freeCam.dollySpeed * 0.05; | |
| var fwd = cam.forward.clone(); if (fwd.lengthSq()>1e-8) fwd.normalize(); | |
| var from = cam.getPosition().clone(); | |
| var to = from.clone().add(fwd.mulScalar(move)); | |
| var next = this.freeCam._moveSwept(from, to.sub(from)); | |
| this.freeCam._clampBBoxMinY(next); | |
| cam.setPosition(next); | |
| e.event.preventDefault(); | |
| }; | |
| // ===================== INPUT TOUCH ===================== | |
| var FreeCameraInputTouch = pc.createScript('orbitCameraInputTouch'); | |
| FreeCameraInputTouch.attributes.add('lookSensitivity', { type: 'number', default: 0.5, title: 'Look Sensitivity' }); | |
| FreeCameraInputTouch.attributes.add('pinchDollyFactor', { type: 'number', default: 0.02, title: 'Pinch Dolly Factor' }); | |
| FreeCameraInputTouch.prototype.initialize = function () { | |
| this.freeCam = this.entity.script.orbitCamera; | |
| this.last = new pc.Vec2(); | |
| this.isLooking = false; | |
| this.lastPinch = 0; | |
| if (this.app.touch) { | |
| this.app.touch.on(pc.EVENT_TOUCHSTART, this.onTouchStartEndCancel, this); | |
| this.app.touch.on(pc.EVENT_TOUCHEND, this.onTouchStartEndCancel, this); | |
| this.app.touch.on(pc.EVENT_TOUCHCANCEL, this.onTouchStartEndCancel, this); | |
| this.app.touch.on(pc.EVENT_TOUCHMOVE, this.onTouchMove, this); | |
| } | |
| this.on('destroy', () => { | |
| if (this.app.touch) { | |
| this.app.touch.off(pc.EVENT_TOUCHSTART, this.onTouchStartEndCancel, this); | |
| this.app.touch.off(pc.EVENT_TOUCHEND, this.onTouchStartEndCancel, this); | |
| this.app.touch.off(pc.EVENT_TOUCHCANCEL, this.onTouchStartEndCancel, this); | |
| this.app.touch.off(pc.EVENT_TOUCHMOVE, this.onTouchMove, this); | |
| } | |
| }); | |
| }; | |
| FreeCameraInputTouch.prototype.onTouchStartEndCancel = function (e) { | |
| var t = e.touches; | |
| if (t.length === 1) { | |
| this.isLooking = (e.event.type === 'touchstart'); | |
| this.last.set(t[0].x, t[0].y); | |
| } else if (t.length === 2) { | |
| var dx = t[0].x - t[1].x, dy = t[0].y - t[1].y; | |
| this.lastPinch = Math.sqrt(dx*dx + dy*dy); | |
| } else { | |
| this.isLooking = false; | |
| } | |
| }; | |
| FreeCameraInputTouch.prototype.onTouchMove = function (e) { | |
| var t = e.touches; | |
| if (!this.freeCam) return; | |
| if (t.length === 1 && this.isLooking) { | |
| var s = this.lookSensitivity; | |
| var dx = t[0].x - this.last.x, dy = t[0].y - this.last.y; | |
| this.freeCam.yaw = this.freeCam.yaw - dx * s; | |
| this.freeCam.pitch = this.freeCam.pitch - dy * s; | |
| this.last.set(t[0].x, t[0].y); | |
| } else if (t.length === 2) { | |
| var dx = t[0].x - t[1].x, dy = t[0].y - t[1].y; | |
| var dist = Math.sqrt(dx*dx + dy*dy); | |
| var delta = dist - this.lastPinch; this.lastPinch = dist; | |
| var cam = this.entity; | |
| var fwd = cam.forward.clone(); if (fwd.lengthSq()>1e-8) fwd.normalize(); | |
| var from = cam.getPosition().clone(); | |
| var to = from.clone().add(fwd.mulScalar(delta * this.pinchDollyFactor * this.freeCam.dollySpeed)); | |
| var next = this.freeCam._moveSwept(from, to.sub(from)); | |
| this.freeCam._clampBBoxMinY(next); | |
| cam.setPosition(next); | |
| } | |
| }; | |
| // ===================== INPUT CLAVIER ===================== | |
| var FreeCameraInputKeyboard = pc.createScript('orbitCameraInputKeyboard'); | |
| FreeCameraInputKeyboard.attributes.add('acceleration', { type: 'number', default: 1.0, title: 'Accel (unused, future)' }); | |
| FreeCameraInputKeyboard.prototype.initialize = function () { | |
| this.freeCam = this.entity.script.orbitCamera; | |
| this.kb = this.app.keyboard || null; | |
| }; | |
| FreeCameraInputKeyboard.prototype.update = function (dt) { | |
| if (!this.freeCam || !this.kb) return; | |
| var fwd = (this.kb.isPressed(pc.KEY_UP) || this.kb.isPressed(pc.KEY_Z)) ? 1 : | |
| (this.kb.isPressed(pc.KEY_DOWN) || this.kb.isPressed(pc.KEY_S)) ? -1 : 0; | |
| var strf = (this.kb.isPressed(pc.KEY_RIGHT) || this.kb.isPressed(pc.KEY_D)) ? 1 : | |
| (this.kb.isPressed(pc.KEY_LEFT) || this.kb.isPressed(pc.KEY_Q)) ? -1 : 0; | |
| if (fwd !== 0 || strf !== 0) { | |
| var cam = this.entity; | |
| var from = cam.getPosition().clone(); | |
| var forward = cam.forward.clone(); if (forward.lengthSq()>1e-8) forward.normalize(); | |
| var right = cam.right.clone(); if (right.lengthSq()>1e-8) right.normalize(); | |
| var delta = new pc.Vec3() | |
| .add(forward.mulScalar(fwd * this.freeCam.moveSpeed * dt)) | |
| .add(right .mulScalar(strf * this.freeCam.strafeSpeed * dt)); | |
| var next = this.freeCam._moveSwept(from, delta); | |
| this.freeCam._clampBBoxMinY(next); | |
| cam.setPosition(next); | |
| } | |
| // Rotation clavier (Shift + flèches) | |
| var shift = this.kb.isPressed(pc.KEY_SHIFT); | |
| if (shift) { | |
| var yawDir = (this.kb.isPressed(pc.KEY_LEFT) ? 1 : 0) - (this.kb.isPressed(pc.KEY_RIGHT) ? 1 : 0); | |
| var pitchDir = (this.kb.isPressed(pc.KEY_UP) ? 1 : 0) - (this.kb.isPressed(pc.KEY_DOWN) ? 1 : 0); | |
| var yawSpeed = 120, pitchSpeed = 90; | |
| if (yawDir !== 0) this.freeCam.yaw = this.freeCam.yaw + yawDir * yawSpeed * dt; | |
| if (pitchDir !== 0) this.freeCam.pitch = this.freeCam.pitch + pitchDir * pitchSpeed * dt; | |
| } | |
| }; | |