A 3D example project of remote sensing controller for controlling movement and viewing Angle.

The effect

The principle of

Battle of the Snake! Thinking and realization of snake movement! It uses a joystick controller, but on a 2D level, this time it’s 3D.

rocker

The joystick basically transmits the position of the touch point to the desired component. (Refer to The rocker component of KUOKUO)

After listening for touch events, you need to do a coordinate transformation. In Cocos 3D, coordinate transformations use the UITransformComponent component.

Then you send coordinates and angles as events.

onTouchMove(e: EventTouch) {
    const location = e.getUILocation();
    // Coordinate conversion
    let pos = this.uITransform.convertToNodeSpaceAR(new Vec3(location.x, location.y));
    // Restrict the position according to the radius
    this.clampPos(pos);
    // Set the position of the intermediate point
    this.midNode.setPosition(pos.x, pos.y, 0);
    // find the Angle with (1,0)
    let angle = this.covertToAngle(pos);
    // Trigger the callback
    this.joyCallBack.forEach(c= > c.emit([pos, angle]));
}
Copy the code

Movement and Perspective

There are three nodes to control node movement, character rotation and perspective rotation respectively.

Using the results returned by the joystick, the speed of movement and rotation can be calculated based on the initial state of the model and the Angle of the camera.

/** Moving the joystick triggers a callback */
joysitckCallback(vector: Vec3, angle: number) {
    // Rotate according to the camera Angle
    Vec3.rotateZ(vector, vector, Vec3.ZERO, this.node_camera.eulerAngles.y * macro.RAD);
    this._vector = vector.normalize();
    if (angle) {
        // Start the model facing forward, add 90 degrees
        this.node_role.eulerAngles = new Vec3(0, angle + 90 + this.node_camera.eulerAngles.y, 0); }}/** Rotate the joystick to trigger a callback
joysitckAngleCallback(vector: Vec3, angle: number) {
    this._vectorAngle = vector.normalize();
}
Copy the code

Depending on speed, refresh position and Angle per frame is ok.

fix_update(dt: number) {
    if (this._vector.lengthSqr() > 0) {
        this.node.setPosition(this.node.position.add3f(this._vector.x * SPEED * dt, 0, -this._vector.y * SPEED * dt));
    }  

    if (this._vectorAngle.lengthSqr() > 0) {
        this.node_camera.eulerAngles = this.node_camera.eulerAngles.add3f(0, -this._vectorAngle.x, 0); }}Copy the code

summary

Coordinate transformation! Rotating! Jumping! Don’t stop!

Use Cocos Creator 3D V1.1.1 to achieve “Rocker Controller!” Technology sharing. Welcome to share with friends around!

Those who cannot motivate themselves must be content with mediocrity, no matter how impressive their other talents may be.

More and more



Original navigation


Full code github.com/baiyuwubing…