我一直在尝试在html文件中创建一个简单的两个球的模拟。这两个球会按照预期在浏览器窗口内进行动画和反弹。但是,当我试图在如下所示的代码中插入if语句: if(((xPos2-xPos1)**2+(yPos2-yPos1)**2)**0.5<=100)时,动画消失了,取而代之的是在chrome控制台中出现了一个“意外的令牌”错误。我试图在代码中插入一些非常基本的碰撞事件,但一无所获。你知道问题出在哪里吗?
<!DOCTYPE html>
<html>
<head>
<title>Ball Animation</title>
<link rel="stylesheet" type="text/css" href="ballAnimation.css">
<!-- Load the Paper.js library -->
<script type="text/javascript" src="paper-full.js"></script>
<!-- Define inlined PaperScript associate it with myCanvas -->
<script type="text/paperscript" canvas="myCanvas">
// }
var xPos1 = 100;
var yPos1 = 100;
var xPos2 = 100;
var yPos2 = 100;
var xInc1 = 10;
var yInc1 = 12;
var xInc2 = -10;
var yInc2 = 20;
var circle2 = new Path.Circle(new Point(100, 70), 50);
circle2.fillColor = 'purple';
var circle3 = new Path.Circle(new Point(250, 120), 50);
circle3.fillColor = 'yellow';
function onFrame(){
if(xPos1>=1000 || xPos1 <= 0){
xInc1 = (-1)*xInc1;
}
if(yPos1>=680 || yPos1<=0){
yInc1 = (-1)*yInc1;
}
xPos1 += xInc1;
yPos1 += yInc1;
if(xPos2>=1000 || xPos2 <= 0){
xInc2 = (-1)*xInc2;
}
if(yPos2>=680 || yPos2<=0){
yInc2 = (-1)*yInc2;
}
if(((xPos2-xPos1)**2+(yPos2-yPos1)**2)**0.5<=100) {
xInc1 = (-1)*xInc1;
yInc1 = (-1)*yInc1;
xInc2 = (-1)*xInc2;
yInc2 = (-1)*yInc2;
}
xPos2 += xInc2;
yPos2 += yInc2;
circle2.position += [xInc1,yInc1];
circle3.position += [xInc2,yInc2];
}
</script>
</head>
<body>
<canvas id="myCanvas" resize="true"></canvas>
</body>
</html>非常提前感谢您的帮助。安德鲁
发布于 2017-03-25 10:25:52
在当今流行的浏览器中,求幂运算符**并没有得到很好的支持。
您应该使用Math.pow(x, n)而不是x**n
<!DOCTYPE html>
<html>
<head>
<title>Ball Animation</title>
<link rel="stylesheet" type="text/css" href="ballAnimation.css">
<!-- Load the Paper.js library -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.10.3/paper-full.min.js"></script>
<!-- Define inlined PaperScript associate it with myCanvas -->
<script type="text/paperscript" canvas="myCanvas">
var xPos1 = 100;
var yPos1 = 100;
var xPos2 = 100;
var yPos2 = 100;
var xInc1 = 10;
var yInc1 = 12;
var xInc2 = -10;
var yInc2 = 20;
var circle2 = new Path.Circle(new Point(100, 70), 50);
circle2.fillColor = 'purple';
var circle3 = new Path.Circle(new Point(250, 120), 50);
circle3.fillColor = 'yellow';
function onFrame(){
if(xPos1>=1000 || xPos1 <= 0){
xInc1 = (-1)*xInc1;
}
if(yPos1>=680 || yPos1<=0){
yInc1 = (-1)*yInc1;
}
xPos1 += xInc1;
yPos1 += yInc1;
if(xPos2>=1000 || xPos2 <= 0){
xInc2 = (-1)*xInc2;
}
if(yPos2>=680 || yPos2<=0){
yInc2 = (-1)*yInc2;
}
if(Math.pow(Math.pow(xPos2-xPos1,2)+Math.pow(yPos2-yPos1,2),0.5)<=100) {
xInc1 = (-1)*xInc1;
yInc1 = (-1)*yInc1;
xInc2 = (-1)*xInc2;
yInc2 = (-1)*yInc2;
}
xPos2 += xInc2;
yPos2 += yInc2;
circle2.position += [xInc1,yInc1];
circle3.position += [xInc2,yInc2];
}
</script>
</head>
<body>
<canvas id="myCanvas" resize="true"></canvas>
</body>
</html>
https://stackoverflow.com/questions/43011778
复制相似问题