0

I am new to this forum although I have been lurking here for help. I am currently messing with AR with A-frame and javascript for fun. I am working on moving my 3d model with a joystick I found on github. fortunately, I was able to move the model around with the joystick, but unfortunately I am unable to figure out how to rotate the model while it moves. Any help would be appreciated!

// turn joystick data into WASD movement in AFRAME
var f;
var ang;
var x_vec;
var y_vec;
var cam;

function updatePosition(data) {
    f = data.force;
    ang = data.angle.radian
    cam = document.getElementById("model");    

    x_vec = Math.cos(ang + 3.14 / 180 * cam.getAttribute('rotation')['x']);
    y_vec = Math.sin(ang + 3.14 / 180 * cam.getAttribute('rotation')['y']);

    x = cam.getAttribute("position")["x"] + f / 15 * (x_vec);
    y = cam.getAttribute("position")["y"]
    z = cam.getAttribute("position")["z"] - f / 15 * (y_vec);

    cam.setAttribute('position', `${x} ${y} ${z}`)
    cam.setAttribute('rotation', `${x} ${y} ${z}`)
}
angel.bonev
  • 2,154
  • 3
  • 20
  • 30

1 Answers1

0

Having the new angle, just add it to the current rotation.y(since you're moving on an XZ plane).

The only catch is that the rotation should be in degrees:

ang = data.angle.radian
cam = document.getElementById("model"); 
// grab the rotation
var rotation = cam.getAttribute("rotation")
rotation.y += ang * 180 / Math.PI
// set the new rotation
cam.setAttribute('rotation', rotation)

A simple example of rotating an entity and moving it forward would be a component like this

AFRAME.registerComponent("joystick-controls", {
  init: function() {
    // initialize the joystick  
    this.joystick = new JoyStick("joyDiv");
    // grab the rotation and position for later use
    this.rot = this.el.getAttribute("rotation");
    this.pos = this.el.getAttribute("position");
  },
  tick: function() {
    // wait until the joystick is ready
    if (!this.joystick) return;
    
    // handle rotation
    this.rot.y -= this.joystick.GetX() / 100;
    this.el.setAttribute("rotation", this.rot);
    
    // handle position 
    var speed = this.joystick.GetY() / 2000;
    this.pos.z += speed * Math.cos(this.rot.y * Math.PI / 180);
    this.pos.x += speed * Math.sin(this.rot.y * Math.PI / 180);
    this.el.setAttribute("position", this.pos);
  }
});

Glitch here. I'm using this joystick.

Piotr Adam Milewski
  • 14,150
  • 3
  • 21
  • 42