PaperJS随机点

PaperJS random point

我有这个代码。我想让代码做的是让球移动,当球越过灰色点(洞)时它会回到起点。我通过为灰洞创建一个随机位置来做到这一点。我只需要找到一种方法来定义这些孔的位置,即使它们是随机的。

var startPoint = new Path.Circle(new Point(40, 40), 40);
startPoint.fillColor = "green";

//finishPoint 
var finishPoint = new Path.Circle(new Point(1300, 600), 40);
finishPoint.fillColor = "red";

var ball = new Path.Circle(new Point(40, 40), 20);
ball.fillColor = "black";

//holes 
var path = new Path(new Point(20, 20), new Point(20, 23));
path.style = {
    strokeColor: 'grey',
    strokeWidth: 70,
    strokeCap: 'round'
};

var holes = new Symbol(path);

for (var i = 0; i < 10; i++) {
    var placement = view.size * Point.random();
    var placed = holes.place(placement);
}





var vector = new Point(0, 0);

function onFrame(event) {

    ball.position += vector / 100;
}
var moves = new Point(100, 1);

function onKeyDown(event) {
    if (event.key === "s") {
        vector.y += 10;
    }
    if (event.key === "d") {
        vector.x += 10;
    }
    if (event.key === "a") {
        vector.x -= 10;
    }
    if (event.key === "w") {
        vector.y -= 10;
    }

    var ballPlace = ball.position;
    if (ballPlace.isClose(finishPoint.position, 40) == true) {

        var text = new PointText(view.center);
        text.content = 'Congratulations';
        text.style = {
            fontFamily: 'Courier New',
            fontWeight: 'bold',
            fontSize: 100,
            fillColor: 'gold',
            justification: 'center'
        };
        ball.remove();
    }
if(ballPlace.isClose(placement.position, 40) == true) {
    ball = new Point(40, 40);
}
};

我希望球在越过灰色洞(可变洞)时回到 Point(40, 40),但我无法让它工作。知道如何解决这个问题吗?

@Luke Park 使用数组是正确的。

尝试每个新点,确保它与所有其他现有点有一定距离。下面的示例(未缩放到 view.size)。

p = Point.random();
while ( isTooClose(p, points) ) {
    p = Point.random();
}

这可能会无限循环,但如果您稀疏地填充该区域,应该没有问题。

isTooClose 测试数组 p 中的每个点,其中 distance = sqrt(dxdx + dydy)。如果你有很多点,你可以通过避免sqrt()来优化,通过测试原始dx和dy值是否小于测试半径。

您也可以在每一帧上使用类似的函数来测试碰撞。

您想测试球相对于孔的位置,看球是否回到起始位置。我能想到的最简单的方法是创建一组孔,然后测试球对着该组的位置。在下面的代码中,球的位置是通过 onMouseMove 函数模拟的,孔会闪烁红色以指示球何时会返回到起始位置。

var holes = [];
var hole;

for (var i = 0; i < 10; i++) {
    hole = new Path.Circle(view.size * Point.random(), 10);
    hole.fillColor = 'grey';
    holes.push(hole);
}

holes = new Group(holes);

onMouseMove = function(e) {
    if (holes.hitTest(e.point)) {
        holes.fillColor = 'red';
    } else {
        holes.fillColor = 'grey';
    }

这是一个实现:sketch。将onMouseMove换成onFrame应该很简单,像现在一样移动球,然后测试它是否落入洞中。

为了测试球是否越过洞,您可以删除 onMouseMove 函数并将其替换为:

onFrame = function(e) {
    ball.position += vector / 100;
    if (holes.hitTest(ball.position)) {
        // move the ball wherever you want to move it, position text,
        // etc. you might have to loop through the array to find which
        // hole was hit.
    }
}