改变立方体 WebGL 的旋转

Change the rotation of a cube WebGL

我需要解决一个问题,要求我模拟狗尾巴的行为。这个 "tale" 是一个简单的立方体,我从 0° 旋转到 45°,从 45° 旋转到 0°。问题是当它到达 45° 度时它又从 0° 开始旋转。

我需要不断运动;不恢复初始位置并重新开始从0°到45°的旋转。

var theta = [0, 0, 0, 0, 0, 0, 180, 0, 180, 0, 20, 0];
var tailId = 11;
function move() {
    // TAIL
    var dir = true;
    if ( theta[tailId] < 45  ) {
        theta[tailId] +=1;
    }
    if (theta[tailId] == 45){
        while(theta[tailId] !=45 )theta[tailId]+=-1;}

您应该使用 dir 变量(已指定)但仅作为数字。当值超过一个界限时,只需反转方向。

类似于:

var theta = [0, 0, 0, 0, 0, 0, 180, 0, 180, 0, 20, 0];
var tailId = 11;
var dir = 1;

function move() {
    // TAIL
    theta[tailId] += dir;

    if ( theta[tailId] < 0  ) {
        theta[tailId] = 0;
        dir = -dir;
    } else
     if ( theta[tailId] > 45  ) {
        theta[tailId] = 45;
        dir = -dir;
    } 
}

你可以试试正弦函数。更好看...

var theta = [0, 0, 0, 0, 0, 0, 180, 0, 180, 0, 20, 0];
var tailId = 11;
var phase = 0;
var step = 0.1;

function move() {
    // TAIL

    // convert from -1..1  =>  0..45
    theta[tailId] = 22.5 + (Math.sin(phase) * 22.5);
    phase += step;
}