☑ Rotate entity by mouse


I try to rotate model by mouse, and I got stuck in some points.

I use quaternions to describe the rotation of my model. I plan to interpolate between current and target points to reach smooth rotation to specified angle. There is it:

LookCamera.prototype.update = function (dt) {
    var result = new pc.Quat().slerp(this.entity.getLocalRotation(), this.toQuat, dt);

So now I have to calculate toQuat in order to use it as a target.

I have targetX and targetY. I got dx and dy from MouseEvent and increase my values by them:

LookCamera.prototype.onMouseMove = function (event) {
     if (this.app.mouse.isPressed(pc.MOUSEBUTTON_LEFT)) {
        this.targetEx += event.dy / 5 ;
        this.targetEy += event.dx / 5;
        this.setTarget(this.targetEx, this.targetEy, 0);

And finally I have to set my target values to quaternion:

LookCamera.prototype.setTarget = function(x,y,z) {

It’s hard to explain, but when I rotate model by mouse, it’s like I broke asixs.
When I rotate it by X it’s okay, but if I rotate it by Y, then I cant rotate by X because it rotates by Z.

I thought problem with co-ordinate system, but no.

So i tried to multiply my quaternion by localRotation and it’s seems to fix it, but it creates a lot of other problems with angles and I think I chose a wrong way and this goal is trivial.

So, if somebody already did that and can explain algorithme, i’d really appreciate it.


We are looking at creating an example for this. Ultimately, what you are trying to do is rotate an object in screen/camera space. At the moment, it looks like you are rotating in world or local space.

My problem was trigonometric. Quaternions contains sin and cos of angles, and they can be same for different angles, it creates artefacts. I clamp my rotation for max 90 degrees and it gone away.

We’ve created a project that does full rotation of the entity with the mouse :slight_smile: https://playcanvas.com/project/442490/overview/rotating-objects-with-mouse

We will add it to the tutorials section later.

It basically uses the quaternions to build a rotation around a specific axis using setFromAxisAngle and the axes from the camera.

1 Like

It looks pretty well, thanks a lot!