我有这个密码。我想要的代码是让球移动,当球越过一个灰色点(洞),它回到起点。我为灰洞创造了一个随机的地方。我只需要找到一种方法来定义这些洞的位置,即使它们是随机的。
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);
}
};我想让球回到点(40,40),当它越过一个灰洞(var孔),但我不能让它工作。知道怎么解决这个问题吗?
发布于 2016-01-26 15:52:45
你想要测试球在洞上的位置,看看球是否回到了开始的位置。我能想到的最简单的方法就是创建一组洞,然后测试球对该组的位置。在下面的代码中,通过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';
}下面是一个实现:素描。用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.
}
}发布于 2016-01-25 23:53:35
@Luke使用数组是正确的。
测试每一个新的点,通过确保它是一个距离所有其他现有的点。下面的示例(没有缩放到view.size)。
p = Point.random();
while ( isTooClose(p, points) ) {
p = Point.random();
}这是有可能的无限循环,但如果你是人口稀少的地区,应该没有问题。
isTooClose测试数组p中的每个点,其中距离= sqrt(dx_dx + dy_dy)。如果有很多点,可以通过避免sqrt()、测试原始dx和dy值是否小于测试半径来进行优化。
您也可以在每个框架上使用类似的函数来测试冲突。
https://stackoverflow.com/questions/35004381
复制相似问题