Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/visual-studio-2010/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript中的旋转正方形(使用p5和三角法)_Javascript_P5.js - Fatal编程技术网

JavaScript中的旋转正方形(使用p5和三角法)

JavaScript中的旋转正方形(使用p5和三角法),javascript,p5.js,Javascript,P5.js,我已经创建了这个代码 var points = [ [100, 100], [100, -100], [-100, -100], [-100, 100] ]; function setup() { createCanvas(400, 400); } function draw() { background(255); translate(200, 200); fill(0); beginShape(); for (var x = 0; x <

我已经创建了这个代码

var points = [
[100, 100],
[100, -100],
[-100, -100],
[-100, 100]
];
function setup() {
    createCanvas(400, 400);
}

function draw() {
    background(255);
    translate(200, 200);
    fill(0);
    beginShape();
    for (var x = 0; x < points.length; x++) {
        points[x] = rotatePoint(0, 0, points[x][0], points[x][1], 1);
        vertex(points[x][0], points[x][1]);
        console.log("vertex: "+String(points[x][0])+" "+String(points[x][1]));
    }
    endShape(CLOSE);
}

function getVectDist(p1X, p1Y, p2X, p2Y) {
    var deltaX = p1X-p2X;
    var deltaY= p1Y-p2Y;
    var vect=[deltaX, deltaY];
    return vect;
}

//Function to rotate a point around the origin or first point

function rotatePoint(originX, originY, pointX, pointY, angle) {
    var dist = getVectDist(originX, originY, pointX, pointY);
    //calculating the hypotenuse of dist
    var hyp = Math.sqrt((dist[0]*dist[0])+(dist[1]*dist[1]));
    console.log("hypotenuse"+String(hyp));
    //calculating coords
    var y = Math.cos(angle) * hyp;
    var x = Math.sin(angle) * hyp;
    return [x, y];
}
var点=[
[100, 100],
[100, -100],
[-100, -100],
[-100, 100]
];
函数设置(){
createCanvas(400400);
}
函数绘图(){
背景(255);
翻译(200200);
填充(0);
beginShape();
对于(变量x=0;x
尝试创建旋转正方形。然而,它只是产生了一条奇怪的像投射物一样移动的对角线,在变成屏幕中心的一个像素之前,它以45度的角度移动。有人知道为什么吗?
谢谢。

我把你的代码做成了一个代码笔,你可以在这里查看:

我用了p5向量,如果你不知道它们是什么,你可能想检查一下。codepen功能齐全,只需对代码进行少量更改。另外,如果您还不知道,p5中有一个
rotate
函数,可以用更少的麻烦产生相同的结果

您可以链接到运行您的代码的代码笔或JSFIDLE吗?