我有这个代码。我想要代码做的是让球移动,当球越过灰色点(洞)时,它会回到起点。我通过为灰洞创建一个随机位置来做到这一点。我只需要找到一种方法来定义这些孔的位置,即使它们是随机的。
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);
}
};
我希望球在越过灰洞(var Holes)时回到点(40, 40),但我无法让它工作。知道如何解决这个问题吗?
最佳答案
您想要测试球相对于孔的位置,看看球是否回到起始位置。我能想到的最简单的方法是创建一组孔,然后测试球相对于该组的位置。在以下代码中,通过 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.
}
}
关于javascript - PaperJS随机点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35004381/