我一直试图用html文件中的paperscript创建一个简单的双球模拟。两个球按预期在浏览器窗口内动画和弹跳。但是,当我尝试插入if语句时:if(((xPos2-xPos1)** 2+(yPos2-yPos1)** 2)** 0.5 <= 100)在下面显示的代码中,动画消失了,而是一个意想不到的令牌&#39; 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>
非常感谢您提前寻求帮助。 安德鲁
答案 0 :(得分:0)
取幂运算符**
在当今流行的浏览器中并没有得到很好的支持。
您应该使用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>
&#13;