How to initialize vr ? Shuold I add google/webvr-polyfill into my project?
var canvas = document.getElementById('application');
var app = new pc.Application(canvas, { });
app.start();
// What should I do here ?
How to initialize vr ? Shuold I add google/webvr-polyfill into my project?
var canvas = document.getElementById('application');
var app = new pc.Application(canvas, { });
app.start();
// What should I do here ?
I found the solution !
Step1: Add webvr-polyfill into your project.
<script src="./libs/webvr-polyfill.js"></script>
<script src="./libs/playcanvas.js"></script>
Step2: Create VrManager.
var canvas = document.getElementById('application');
var app = new pc.Application(canvas, { });
app.vr = new pc.VrManager(app); // add this line
app.start();
Step 3: Call camera.enterVr
or camera.exitVr
by your self.
That’s it !
I’ve add the following script to solve the CameraOffsetEntity.
var VrCamera = pc.createScript('vrCamera');
// initialize code called once per entity
VrCamera.prototype.initialize = function() {
this.cameraOffsetEntity = new pc.Entity();
this.cameraOffsetEntity.name = 'Camera Offset';
this.root = null;
this.vrEntered = false;
var parent = this.entity.parent;
while (parent.parent) {
parent = parent.parent;
}
this.root = parent;
this.root.addChild(this.cameraOffsetEntity);
};
VrCamera.prototype.toggleVr = function() {
var self = this;
if (this.app.vr && this.app.vr.display) {
if (this.vrEntered) {
// Exit vr (needed for non-mobile)
this.entity.camera.exitVr(function (err) {
console.log('exit vr: ', err);
if (err) {
console.error(err);
return;
}
self.entity.reparent(self.root);
self.entity.setPosition(self.cameraOffsetEntity.getPosition());
self.vrEntered = false;
});
} else {
// Enter vr
this.entity.camera.enterVr(function (err) {
console.log('enter vr: ', err);
if (err) {
console.error(err);
return;
}
self.entity.reparent(self.cameraOffsetEntity);
self.entity.setLocalPosition(0, 0, 0);
self.vrEntered = true;
});
}
}
};
// update code called every frame
VrCamera.prototype.update = function(dt) {
if (this.entity.parent !== this.cameraOffsetEntity) {
this.cameraOffsetEntity.setPosition(this.entity.getPosition());
}
};
The core of this script is entity.reparent
method.
I add the cameraOffsetEntity as the same hierarchy of the camera.
Root
-- Camera
-- CameraOffsetEntity
-- other entities
And then update CameraOffsetEntity
's position every frame.
When camera enter vr, change camera’s parent to the CameraOffsetEntity
.
When camera exit vr, change camera’s parent to the Root
.